diff options
Diffstat (limited to 'parameter')
186 files changed, 7908 insertions, 7196 deletions
diff --git a/parameter/Android.mk b/parameter/Android.mk deleted file mode 100644 index 7fa83fc..0000000 --- a/parameter/Android.mk +++ /dev/null @@ -1,193 +0,0 @@ -# Copyright (c) 2011-2014, Intel Corporation -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation and/or -# other materials provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors -# may be used to endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -LOCAL_PATH := $(call my-dir) - -#################### -# Common definitions - -common_copy_headers_to := parameter - -common_copy_headers := \ - include/ParameterMgrLoggerForward.h \ - include/ParameterMgrPlatformConnector.h \ - include/ParameterMgrFullConnector.h \ - include/SelectionCriterionTypeInterface.h \ - include/SelectionCriterionInterface.h \ - include/ParameterHandle.h - -common_src_files := \ - AreaConfiguration.cpp \ - ArrayParameter.cpp \ - AutoLog.cpp \ - BaseParameter.cpp \ - BinarySerializableElement.cpp \ - BinaryStream.cpp \ - BitParameterBlock.cpp \ - BitParameterBlockType.cpp \ - BitParameter.cpp \ - BitParameterType.cpp \ - BitwiseAreaConfiguration.cpp \ - BooleanParameterType.cpp \ - ComponentInstance.cpp \ - ComponentLibrary.cpp \ - ComponentType.cpp \ - CompoundRule.cpp \ - ConfigurableDomain.cpp \ - ConfigurableDomains.cpp \ - ConfigurableElementAggregator.cpp \ - ConfigurableElement.cpp \ - ConfigurationAccessContext.cpp \ - DomainConfiguration.cpp \ - Element.cpp \ - ElementLibrary.cpp \ - ElementLibrarySet.cpp \ - ElementLocator.cpp \ - EnumParameterType.cpp \ - EnumValuePair.cpp \ - ErrorContext.cpp \ - FixedPointParameterType.cpp \ - FormattedSubsystemObject.cpp \ - FrameworkConfigurationLocation.cpp \ - HardwareBackSynchronizer.cpp \ - InstanceConfigurableElement.cpp \ - InstanceDefinition.cpp \ - IntegerParameterType.cpp \ - LinearParameterAdaptation.cpp \ - LogarithmicParameterAdaptation.cpp \ - MappingContext.cpp \ - MappingData.cpp \ - ParameterAccessContext.cpp \ - ParameterAdaptation.cpp \ - ParameterBlackboard.cpp \ - ParameterBlockType.cpp \ - Parameter.cpp \ - ParameterFrameworkConfiguration.cpp \ - ParameterHandle.cpp \ - ParameterMgr.cpp \ - ParameterMgrFullConnector.cpp \ - ParameterMgrPlatformConnector.cpp \ - ParameterType.cpp \ - PathNavigator.cpp \ - PluginLocation.cpp \ - RuleParser.cpp \ - SelectionCriteria.cpp \ - SelectionCriteriaDefinition.cpp \ - SelectionCriterion.cpp \ - SelectionCriterionLibrary.cpp \ - SelectionCriterionRule.cpp \ - SelectionCriterionType.cpp \ - SimulatedBackSynchronizer.cpp \ - StringParameter.cpp \ - StringParameterType.cpp \ - Subsystem.cpp \ - SubsystemElementBuilder.cpp \ - SubsystemObject.cpp \ - SubsystemObjectCreator.cpp \ - SyncerSet.cpp \ - SystemClass.cpp \ - TypeElement.cpp \ - VirtualSubsystem.cpp \ - VirtualSyncer.cpp \ - XmlElementSerializingContext.cpp \ - XmlFileIncluderElement.cpp \ - XmlParameterSerializingContext.cpp - -common_module := libparameter -common_module_tags := optional - -common_cflags := \ - -Wall \ - -Werror \ - -Wextra \ - -Wno-unused-parameter \ - -Wno-maybe-uninitialized - -common_c_includes := \ - $(LOCAL_PATH)/include/ \ - $(LOCAL_PATH)/../utility/ \ - $(LOCAL_PATH)/../remote-processor/ - -############################# -# Target build - -include $(CLEAR_VARS) - -LOCAL_COPY_HEADERS_TO := $(common_copy_headers_to) -LOCAL_COPY_HEADERS := $(common_copy_headers) - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) - -LOCAL_CFLAGS := $(common_cflags) - -LOCAL_SRC_FILES := $(common_src_files) - -LOCAL_MODULE := $(common_module) -LOCAL_MODULE_OWNER := intel -LOCAL_MODULE_TAGS := $(common_module_tags) - -LOCAL_C_INCLUDES := $(common_c_includes) - -LOCAL_SHARED_LIBRARIES := libxmlserializer libdl -LOCAL_STATIC_LIBRARIES := libpfw_utility - -LOCAL_REQUIRED_MODULES := libremote-processor - -ifeq ($(INCLUDE_STLPORT), true) -include external/stlport/libstlport.mk -endif - -include $(BUILD_SHARED_LIBRARY) - -############################## -# Host build - -include $(CLEAR_VARS) - -LOCAL_COPY_HEADERS_TO := $(common_copy_headers_to) -LOCAL_COPY_HEADERS := $(common_copy_headers) - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) - -LOCAL_CFLAGS := $(common_cflags) -O0 -ggdb - -LOCAL_SRC_FILES := $(common_src_files) - -LOCAL_MODULE := $(common_module)_host -LOCAL_MODULE_OWNER := intel -LOCAL_MODULE_TAGS := $(common_module_tags) - -LOCAL_C_INCLUDES += \ - $(common_c_includes) - -LOCAL_SHARED_LIBRARIES := libxmlserializer_host -LOCAL_STATIC_LIBRARIES := libpfw_utility_host libxml2 - -LOCAL_LDLIBS += -ldl - -include $(BUILD_HOST_SHARED_LIBRARY) diff --git a/parameter/AreaConfiguration.cpp b/parameter/AreaConfiguration.cpp index b3a556e..aaf7df8 100644 --- a/parameter/AreaConfiguration.cpp +++ b/parameter/AreaConfiguration.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -30,42 +30,44 @@ #include "AreaConfiguration.h" #include "ConfigurableElement.h" #include "ConfigurationAccessContext.h" -#include "BinaryStream.h" #include <assert.h> -CAreaConfiguration::CAreaConfiguration(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet) - : _pConfigurableElement(pConfigurableElement), _pSyncerSet(pSyncerSet), _bValid(false) +CAreaConfiguration::CAreaConfiguration(const CConfigurableElement *pConfigurableElement, + const CSyncerSet *pSyncerSet) + : _pConfigurableElement(pConfigurableElement), _pSyncerSet(pSyncerSet) { // Size blackboard _blackboard.setSize(_pConfigurableElement->getFootPrint()); } -CAreaConfiguration::CAreaConfiguration(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet, uint32_t uiSize) - : _pConfigurableElement(pConfigurableElement), _pSyncerSet(pSyncerSet), _bValid(false) +CAreaConfiguration::CAreaConfiguration(const CConfigurableElement *pConfigurableElement, + const CSyncerSet *pSyncerSet, size_t size) + : _pConfigurableElement(pConfigurableElement), _pSyncerSet(pSyncerSet) { // Size blackboard - _blackboard.setSize(uiSize); + _blackboard.setSize(size); } // Save data from current -void CAreaConfiguration::save(const CParameterBlackboard* pMainBlackboard) +void CAreaConfiguration::save(const CParameterBlackboard *pMainBlackboard) { copyFrom(pMainBlackboard, _pConfigurableElement->getOffset()); } // Apply data to current -bool CAreaConfiguration::restore(CParameterBlackboard* pMainBlackboard, bool bSync, std::list<std::string>* plstrError) const +bool CAreaConfiguration::restore(CParameterBlackboard *pMainBlackboard, bool bSync, + core::Results *errors) const { assert(_bValid); copyTo(pMainBlackboard, _pConfigurableElement->getOffset()); // Synchronize if required - return !bSync || _pSyncerSet->sync(*pMainBlackboard, false, plstrError); + return !bSync || _pSyncerSet->sync(*pMainBlackboard, false, errors); } // Ensure validity -void CAreaConfiguration::validate(const CParameterBlackboard* pMainBlackboard) +void CAreaConfiguration::validate(const CParameterBlackboard *pMainBlackboard) { if (!_bValid) { @@ -83,7 +85,7 @@ bool CAreaConfiguration::isValid() const } // Ensure validity against given valid area configuration -void CAreaConfiguration::validateAgainst(const CAreaConfiguration* pValidAreaConfiguration) +void CAreaConfiguration::validateAgainst(const CAreaConfiguration *pValidAreaConfiguration) { // Should be called on purpose assert(!_bValid); @@ -102,7 +104,9 @@ void CAreaConfiguration::validateAgainst(const CAreaConfiguration* pValidAreaCon } // XML configuration settings parsing -bool CAreaConfiguration::serializeXmlSettings(CXmlElement& xmlConfigurableElementSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) +bool CAreaConfiguration::serializeXmlSettings( + CXmlElement &xmlConfigurableElementSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) { // Assign blackboard to configuration context configurationAccessContext.setParameterBlackboard(&_blackboard); @@ -111,7 +115,8 @@ bool CAreaConfiguration::serializeXmlSettings(CXmlElement& xmlConfigurableElemen configurationAccessContext.setBaseOffset(_pConfigurableElement->getOffset()); // Parse configuration settings (element contents) - if (_pConfigurableElement->serializeXmlSettings(xmlConfigurableElementSettingsElementContent, configurationAccessContext)) { + if (_pConfigurableElement->serializeXmlSettings(xmlConfigurableElementSettingsElementContent, + configurationAccessContext)) { if (!configurationAccessContext.serializeOut()) { @@ -124,55 +129,40 @@ bool CAreaConfiguration::serializeXmlSettings(CXmlElement& xmlConfigurableElemen } // Compound handling -const CConfigurableElement* CAreaConfiguration::getConfigurableElement() const +const CConfigurableElement *CAreaConfiguration::getConfigurableElement() const { return _pConfigurableElement; } -void CAreaConfiguration::copyToOuter(CAreaConfiguration* pToAreaConfiguration) const +void CAreaConfiguration::copyToOuter(CAreaConfiguration *pToAreaConfiguration) const { assert(_pConfigurableElement->isDescendantOf(pToAreaConfiguration->getConfigurableElement())); - copyTo(&pToAreaConfiguration->_blackboard, _pConfigurableElement->getOffset() - pToAreaConfiguration->getConfigurableElement()->getOffset()); + copyTo(&pToAreaConfiguration->_blackboard, + _pConfigurableElement->getOffset() - + pToAreaConfiguration->getConfigurableElement()->getOffset()); } -void CAreaConfiguration::copyFromOuter(const CAreaConfiguration* pFromAreaConfiguration) +void CAreaConfiguration::copyFromOuter(const CAreaConfiguration *pFromAreaConfiguration) { assert(_pConfigurableElement->isDescendantOf(pFromAreaConfiguration->getConfigurableElement())); - copyFrom(&pFromAreaConfiguration->_blackboard, _pConfigurableElement->getOffset() - pFromAreaConfiguration->getConfigurableElement()->getOffset()); + copyFrom(&pFromAreaConfiguration->_blackboard, + _pConfigurableElement->getOffset() - + pFromAreaConfiguration->getConfigurableElement()->getOffset()); // Inner becomes valid setValid(true); } -// Serialization -void CAreaConfiguration::serialize(CBinaryStream& binaryStream) -{ - // Delegate to blackboard - _blackboard.serialize(binaryStream); - - if (!binaryStream.isOut()) { - - // Serialized in areas are valid - _bValid = true; - } -} - -// Data size -uint32_t CAreaConfiguration::getSize() const -{ - return _blackboard.getSize(); -} - -CParameterBlackboard& CAreaConfiguration::getBlackboard() +CParameterBlackboard &CAreaConfiguration::getBlackboard() { return _blackboard; } -const CParameterBlackboard& CAreaConfiguration::getBlackboard() const +const CParameterBlackboard &CAreaConfiguration::getBlackboard() const { - return _blackboard; + return _blackboard; } // Store validity @@ -182,13 +172,12 @@ void CAreaConfiguration::setValid(bool bValid) } // Blackboard copies -void CAreaConfiguration::copyTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const +void CAreaConfiguration::copyTo(CParameterBlackboard *pToBlackboard, size_t offset) const { - pToBlackboard->restoreFrom(&_blackboard, uiOffset); + pToBlackboard->restoreFrom(&_blackboard, offset); } -void CAreaConfiguration::copyFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset) +void CAreaConfiguration::copyFrom(const CParameterBlackboard *pFromBlackboard, size_t offset) { - pFromBlackboard->saveTo(&_blackboard, uiOffset); + pFromBlackboard->saveTo(&_blackboard, offset); } - diff --git a/parameter/AreaConfiguration.h b/parameter/AreaConfiguration.h index 3ea4718..c20db37 100644 --- a/parameter/AreaConfiguration.h +++ b/parameter/AreaConfiguration.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -30,8 +30,8 @@ #pragma once #include "ParameterBlackboard.h" -#include "BinaryStream.h" #include "SyncerSet.h" +#include "Results.h" class CConfigurableElement; class CXmlElement; @@ -40,71 +40,72 @@ class CConfigurationAccessContext; class CAreaConfiguration { public: - CAreaConfiguration(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet); + CAreaConfiguration(const CConfigurableElement *pConfigurableElement, + const CSyncerSet *pSyncerSet); - /* FIXME this was missing and probably buggy*/ - virtual ~CAreaConfiguration() {} + virtual ~CAreaConfiguration() = default; // Save data from current - void save(const CParameterBlackboard* pMainBlackboard); + void save(const CParameterBlackboard *pMainBlackboard); - // Apply data to current - bool restore(CParameterBlackboard* pMainBlackboard, bool bSync, std::list<std::string>* plstrError) const; + /** Restore the configuration area + * + * @param[in] pMainBlackboard the application main blackboard + * @param[in] bSync indicates if a synchronisation has to be done + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool restore(CParameterBlackboard *pMainBlackboard, bool bSync, core::Results *errors) const; // Ensure validity - void validate(const CParameterBlackboard* pMainBlackboard); + void validate(const CParameterBlackboard *pMainBlackboard); // Return validity bool isValid() const; // Ensure validity against given valid area configuration - void validateAgainst(const CAreaConfiguration* pValidAreaConfiguration); + void validateAgainst(const CAreaConfiguration *pValidAreaConfiguration); // Compound handling - const CConfigurableElement* getConfigurableElement() const; + const CConfigurableElement *getConfigurableElement() const; // Configuration merging - virtual void copyToOuter(CAreaConfiguration* pToAreaConfiguration) const; + virtual void copyToOuter(CAreaConfiguration *pToAreaConfiguration) const; // Configuration splitting - virtual void copyFromOuter(const CAreaConfiguration* pFromAreaConfiguration); + virtual void copyFromOuter(const CAreaConfiguration *pFromAreaConfiguration); // XML configuration settings parsing/composing - bool serializeXmlSettings(CXmlElement& xmlConfigurableElementSettingsElementContent, CConfigurationAccessContext& configurationAccessContext); - - // Serialization - void serialize(CBinaryStream& binaryStream); - - // Data size - uint32_t getSize() const; + bool serializeXmlSettings(CXmlElement &xmlConfigurableElementSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext); // Fetch the Configuration Blackboard - CParameterBlackboard& getBlackboard(); - const CParameterBlackboard& getBlackboard() const; + CParameterBlackboard &getBlackboard(); + const CParameterBlackboard &getBlackboard() const; protected: - CAreaConfiguration(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet, uint32_t uiSize); + CAreaConfiguration(const CConfigurableElement *pConfigurableElement, + const CSyncerSet *pSyncerSet, size_t size); private: // Blackboard copies - virtual void copyTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const; - virtual void copyFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset); + virtual void copyTo(CParameterBlackboard *pToBlackboard, size_t offset) const; + virtual void copyFrom(const CParameterBlackboard *pFromBlackboard, size_t offset); // Store validity void setValid(bool bValid); protected: // Associated configurable element - const CConfigurableElement* _pConfigurableElement; + const CConfigurableElement *_pConfigurableElement; // Configurable element settings CParameterBlackboard _blackboard; private: // Syncer set (required for immediate synchronization) - const CSyncerSet* _pSyncerSet; + const CSyncerSet *_pSyncerSet; // Area configuration validity (invalid area configurations can't be restored) - bool _bValid; + bool _bValid{false}; }; - diff --git a/parameter/ArrayParameter.cpp b/parameter/ArrayParameter.cpp index 291b6a1..83ffe04 100644 --- a/parameter/ArrayParameter.cpp +++ b/parameter/ArrayParameter.cpp @@ -41,83 +41,55 @@ using std::string; -CArrayParameter::CArrayParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CArrayParameter::CArrayParameter(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } -uint32_t CArrayParameter::getFootPrint() const +size_t CArrayParameter::getFootPrint() const { return getSize() * getArrayLength(); } // Array length -uint32_t CArrayParameter::getArrayLength() const +size_t CArrayParameter::getArrayLength() const { return getTypeElement()->getArrayLength(); } // Element properties -void CArrayParameter::showProperties(string& strResult) const +void CArrayParameter::showProperties(string &strResult) const { base::showProperties(strResult); // Array length strResult += "Array length: "; - strResult += CUtility::toString(getArrayLength()); + strResult += std::to_string(getArrayLength()); strResult += "\n"; } -// XML configuration settings parsing -bool CArrayParameter::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const -{ - // Check for value space - handleValueSpaceAttribute(xmlConfigurationSettingsElementContent, configurationAccessContext); - - // Handle access - if (!configurationAccessContext.serializeOut()) { - - // Actually set values to blackboard - if (!setValues(0, configurationAccessContext.getBaseOffset(), xmlConfigurationSettingsElementContent.getTextContent(), configurationAccessContext)) { - - return false; - } - } else { - - // Get string value - string strValue; - - // Whole array requested - getValues(configurationAccessContext.getBaseOffset(), strValue, configurationAccessContext); - - // Populate value into xml text node - xmlConfigurationSettingsElementContent.setTextContent(strValue); - } - - // Done - return true; -} - // User set/get -bool CArrayParameter::accessValue(CPathNavigator& pathNavigator, string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { - uint32_t uiIndex; + size_t index; - if (!getIndex(pathNavigator, uiIndex, parameterAccessContext)) { + if (!getIndex(pathNavigator, index, parameterAccessContext)) { return false; } if (bSet) { // Set - if (uiIndex == (uint32_t)-1) { + if (index == (size_t)-1) { // No index provided, start with 0 - uiIndex = 0; + index = 0; } // Actually set values - if (!setValues(uiIndex, parameterAccessContext.getBaseOffset(), strValue, parameterAccessContext)) { - + if (!setValues(index, getOffset() - parameterAccessContext.getBaseOffset(), strValue, + parameterAccessContext)) { return false; } @@ -129,108 +101,129 @@ bool CArrayParameter::accessValue(CPathNavigator& pathNavigator, string& strValu } } else { // Get - if (uiIndex == (uint32_t)-1) { + if (index == (size_t)-1) { // Whole array requested - getValues(parameterAccessContext.getBaseOffset(), strValue, parameterAccessContext); + strValue = getValues(getOffset() - parameterAccessContext.getBaseOffset(), + parameterAccessContext); } else { // Scalar requested - doGetValue(strValue, getOffset() + uiIndex * getSize(), parameterAccessContext); + CParameter::doGetValue(strValue, getOffset() + index * getSize(), + parameterAccessContext); } } return true; } +/// Actual parameter access +// String access +bool CArrayParameter::doSetValue(const string &value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const +{ + return setValues(0, offset, value, parameterAccessContext); +} + +void CArrayParameter::doGetValue(string &value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const +{ + // Whole array requested + value = getValues(offset, parameterAccessContext); +} + // Boolean -bool CArrayParameter::accessAsBooleanArray(std::vector<bool>& abValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::access(std::vector<bool> &abValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return accessValues(abValues, bSet, parameterAccessContext); } // Integer -bool CArrayParameter::accessAsIntegerArray(std::vector<uint32_t>& auiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::access(std::vector<uint32_t> &auiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return accessValues(auiValues, bSet, parameterAccessContext); } // Signed Integer Access -bool CArrayParameter::accessAsSignedIntegerArray(std::vector<int32_t>& aiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::access(std::vector<int32_t> &aiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return accessValues(aiValues, bSet, parameterAccessContext); } // Double Access -bool CArrayParameter::accessAsDoubleArray(std::vector<double>& adValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::access(std::vector<double> &adValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return accessValues(adValues, bSet, parameterAccessContext); } // String Access -bool CArrayParameter::accessAsStringArray(std::vector<string>& astrValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::access(std::vector<string> &astrValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return accessValues(astrValues, bSet, parameterAccessContext); } // Dump -void CArrayParameter::logValue(string& strValue, CErrorContext& errorContext) const +string CArrayParameter::logValue(CParameterAccessContext &context) const { - // Parameter context - CParameterAccessContext& parameterAccessContext = static_cast<CParameterAccessContext&>(errorContext); - // Dump values - getValues(0, strValue, parameterAccessContext); + return getValues(0, context); } // Used for simulation and virtual subsystems -void CArrayParameter::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CArrayParameter::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { // Get default value from type - uint32_t uiDefaultValue = static_cast<const CParameterType*>(getTypeElement())->getDefaultValue(); + uint32_t uiDefaultValue = + static_cast<const CParameterType *>(getTypeElement())->getDefaultValue(); // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Process - uint32_t uiValueIndex; - uint32_t uiSize = getSize(); - uint32_t uiOffset = getOffset(); - bool bSubsystemIsBigEndian = parameterAccessContext.isBigEndianSubsystem(); - uint32_t uiArrayLength = getArrayLength(); + size_t valueIndex; + size_t size = getSize(); + size_t offset = getOffset(); + size_t arrayLength = getArrayLength(); - for (uiValueIndex = 0; uiValueIndex < uiArrayLength; uiValueIndex++) { + for (valueIndex = 0; valueIndex < arrayLength; valueIndex++) { // Beware this code works on little endian architectures only! - pBlackboard->writeInteger(&uiDefaultValue, uiSize, uiOffset, bSubsystemIsBigEndian); + pBlackboard->writeInteger(&uiDefaultValue, size, offset); - uiOffset += uiSize; + offset += size; } } // Index from path -bool CArrayParameter::getIndex(CPathNavigator& pathNavigator, uint32_t& uiIndex, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::getIndex(CPathNavigator &pathNavigator, size_t &index, + CParameterAccessContext ¶meterAccessContext) const { - uiIndex = (uint32_t)-1; + index = (size_t)-1; - string* pStrChildName = pathNavigator.next(); + string *pStrChildName = pathNavigator.next(); if (pStrChildName) { // Check index is numeric - std::istringstream iss(*pStrChildName); + std::istringstream iss(*pStrChildName); - iss >> uiIndex; + iss >> index; if (!iss) { - parameterAccessContext.setError("Expected numerical expression as last item in " + pathNavigator.getCurrentPath()); + parameterAccessContext.setError("Expected numerical expression as last item in " + + pathNavigator.getCurrentPath()); return false; } - if (uiIndex >= getArrayLength()) { - std::ostringstream oss; + if (index >= getArrayLength()) { + std::ostringstream oss; oss << "Provided index out of range (max is " << getArrayLength() - 1 << ")"; @@ -255,16 +248,17 @@ bool CArrayParameter::getIndex(CPathNavigator& pathNavigator, uint32_t& uiIndex, } // Common set value processing -bool CArrayParameter::setValues(uint32_t uiStartIndex, uint32_t uiBaseOffset, const string& strValue, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::setValues(size_t uiStartIndex, size_t offset, const string &strValue, + CParameterAccessContext ¶meterAccessContext) const { // Deal with value(s) Tokenizer tok(strValue, Tokenizer::defaultDelimiters + ","); std::vector<string> astrValues = tok.split(); - size_t uiNbValues = astrValues.size(); + size_t nbValues = astrValues.size(); // Check number of provided values - if (uiNbValues + uiStartIndex > getArrayLength()) { + if (nbValues + uiStartIndex > getArrayLength()) { // Out of bounds parameterAccessContext.setError("Too many values provided"); @@ -273,60 +267,62 @@ bool CArrayParameter::setValues(uint32_t uiStartIndex, uint32_t uiBaseOffset, co } // Process - uint32_t uiValueIndex; - uint32_t uiSize = getSize(); - uint32_t uiOffset = getOffset() + uiStartIndex * uiSize - uiBaseOffset; + size_t valueIndex; + size_t size = getSize(); + offset += uiStartIndex * size; - for (uiValueIndex = 0; uiValueIndex < uiNbValues; uiValueIndex++) { + for (valueIndex = 0; valueIndex < nbValues; valueIndex++) { - if (!doSetValue(astrValues[uiValueIndex], uiOffset, parameterAccessContext)) { + if (!doSet(astrValues[valueIndex], offset, parameterAccessContext)) { // Append parameter path to error parameterAccessContext.appendToError(" " + getPath() + "/" + - CUtility::toString(uiValueIndex + uiStartIndex)); + std::to_string(valueIndex + uiStartIndex)); return false; } - uiOffset += uiSize; + offset += size; } return true; } // Common get value processing -void CArrayParameter::getValues(uint32_t uiBaseOffset, string& strValues, CParameterAccessContext& parameterAccessContext) const +string CArrayParameter::getValues(size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - uint32_t uiValueIndex; - uint32_t uiSize = getSize(); - uint32_t uiOffset = getOffset() - uiBaseOffset; - uint32_t uiArrayLength = getArrayLength(); + size_t size = getSize(); + size_t arrayLength = getArrayLength(); - strValues.clear(); + string output; bool bFirst = true; - for (uiValueIndex = 0; uiValueIndex < uiArrayLength; uiValueIndex++) { + for (size_t valueIndex = 0; valueIndex < arrayLength; valueIndex++) { string strReadValue; - doGetValue(strReadValue, uiOffset, parameterAccessContext); + doGet(strReadValue, offset, parameterAccessContext); if (!bFirst) { - strValues += " "; + output += " "; } else { bFirst = false; } - strValues += strReadValue; + output += strReadValue; - uiOffset += uiSize; + offset += size; } + + return output; } // Generic Access template <typename type> -bool CArrayParameter::accessValues(std::vector<type>& values, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::accessValues(std::vector<type> &values, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { if (bSet) { @@ -353,83 +349,86 @@ bool CArrayParameter::accessValues(std::vector<type>& values, bool bSet, CParame } template <typename type> -bool CArrayParameter::setValues(const std::vector<type>& values, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::setValues(const std::vector<type> &values, + CParameterAccessContext ¶meterAccessContext) const { - uint32_t uiNbValues = getArrayLength(); - uint32_t uiValueIndex; - uint32_t uiSize = getSize(); - uint32_t uiOffset = getOffset(); + size_t nbValues = getArrayLength(); + size_t size = getSize(); + size_t offset = getOffset(); - assert(values.size() == uiNbValues); + assert(values.size() == nbValues); // Process - for (uiValueIndex = 0; uiValueIndex < uiNbValues; uiValueIndex++) { + for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) { - if (!doSet(values[uiValueIndex], uiOffset, parameterAccessContext)) { + if (!doSet(values[valueIndex], offset, parameterAccessContext)) { return false; } - uiOffset += uiSize; + offset += size; } - return true; + return true; } template <typename type> -bool CArrayParameter::getValues(std::vector<type>& values, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::getValues(std::vector<type> &values, + CParameterAccessContext ¶meterAccessContext) const { - uint32_t uiNbValues = getArrayLength(); - uint32_t uiValueIndex; - uint32_t uiSize = getSize(); - uint32_t uiOffset = getOffset(); + size_t nbValues = getArrayLength(); + size_t size = getSize(); + size_t offset = getOffset(); values.clear(); - for (uiValueIndex = 0; uiValueIndex < uiNbValues; uiValueIndex++) { + for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) { type readValue; - if (!doGet(readValue, uiOffset, parameterAccessContext)) { + if (!doGet(readValue, offset, parameterAccessContext)) { return false; } values.push_back(readValue); - uiOffset += uiSize; + offset += size; } return true; } template <typename type> -bool CArrayParameter::doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::doSet(type value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint32_t uiData; - if (!static_cast<const CParameterType*>(getTypeElement())->toBlackboard(value, uiData, parameterAccessContext)) { + if (!static_cast<const CParameterType *>(getTypeElement()) + ->toBlackboard(value, uiData, parameterAccessContext)) { return false; } // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->writeInteger(&uiData, getSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->writeInteger(&uiData, getSize(), offset); return true; } template <typename type> -bool CArrayParameter::doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CArrayParameter::doGet(type &value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint32_t uiData = 0; // Read blackboard - const CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->readInteger(&uiData, getSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->readInteger(&uiData, getSize(), offset); - return static_cast<const CParameterType*>(getTypeElement())->fromBlackboard(value, uiData, parameterAccessContext); + return static_cast<const CParameterType *>(getTypeElement()) + ->fromBlackboard(value, uiData, parameterAccessContext); } - diff --git a/parameter/ArrayParameter.h b/parameter/ArrayParameter.h index bdc5632..b2018c2 100644 --- a/parameter/ArrayParameter.h +++ b/parameter/ArrayParameter.h @@ -34,55 +34,71 @@ class CArrayParameter : public CParameter { public: - CArrayParameter(const std::string& strName, const CTypeElement* pTypeElement); + CArrayParameter(const std::string &strName, const CTypeElement *pTypeElement); // Instantiation, allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; - // XML configuration settings parsing - virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const; - - // Value access - // Boolean - virtual bool accessAsBooleanArray(std::vector<bool>& abValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; - // Integer - virtual bool accessAsIntegerArray(std::vector<uint32_t>& auiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; - // Signed Integer Access - virtual bool accessAsSignedIntegerArray(std::vector<int32_t>& aiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; - // Double Access - virtual bool accessAsDoubleArray(std::vector<double>& adValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; - // String Access - virtual bool accessAsStringArray(std::vector<std::string>& astrValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + /// Value access + using CBaseParameter::access; + bool access(std::vector<bool> &abValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; + bool access(std::vector<uint32_t> &auiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; + bool access(std::vector<int32_t> &aiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; + bool access(std::vector<double> &adValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; + bool access(std::vector<std::string> &astrValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; protected: // User set/get - virtual bool accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + virtual bool accessValue(CPathNavigator &pathNavigator, std::string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; + private: // Array length - uint32_t getArrayLength() const; + size_t getArrayLength() const; // Common set value processing - bool setValues(uint32_t uiStartIndex, uint32_t uiBaseOffset, const std::string& strValue, CParameterAccessContext& parameterAccessContext) const; + bool setValues(size_t uiStartIndex, size_t offset, const std::string &strValue, + CParameterAccessContext ¶meterAccessContext) const; // Log / get values common - void getValues(uint32_t uiBaseOffset, std::string& strValues, CParameterAccessContext& parameterAccessContext) const; + std::string getValues(size_t baseOffset, CParameterAccessContext ¶meterAccessContext) const; + std::string logValue(CParameterAccessContext &context) const override; // Index retrieval from user set/get request - bool getIndex(CPathNavigator& pathNavigator, uint32_t& uiIndex, CParameterAccessContext& parameterAccessContext) const; + bool getIndex(CPathNavigator &pathNavigator, size_t &index, + CParameterAccessContext ¶meterAccessContext) const; + + /** Access whole array. + * + * @param[in] offset Offset of the array in the context blackboard. + * @{ + */ + bool doSetValue(const std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const override; + void doGetValue(std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const override; + /** @} */ /// Value access // Generic Access template <typename type> - bool accessValues(std::vector<type>& values, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool accessValues(std::vector<type> &values, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool setValues(const std::vector<type>& values, CParameterAccessContext& parameterAccessContext) const; + bool setValues(const std::vector<type> &values, + CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool getValues(std::vector<type>& values, CParameterAccessContext& parameterAccessContext) const; + bool getValues(std::vector<type> &values, + CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + bool doSet(type value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + bool doGet(type &value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; }; diff --git a/parameter/BackSynchronizer.h b/parameter/BackSynchronizer.h index 0d6fcb5..ff6c4f6 100644 --- a/parameter/BackSynchronizer.h +++ b/parameter/BackSynchronizer.h @@ -31,15 +31,18 @@ #include "ConfigurableElementAggregator.h" #include "ConfigurableElement.h" +#include <NonCopyable.hpp> + #include <list> class CParameterBlackboard; -class CBackSynchronizer +class CBackSynchronizer : private utility::NonCopyable { public: - CBackSynchronizer(const CConfigurableElement* pConfigurableElement) - : _configurableElementAggregator(_needingBackSyncList, &CConfigurableElement::hasNoValidDomainAssociated) + CBackSynchronizer(const CConfigurableElement *pConfigurableElement) + : _configurableElementAggregator(_needingBackSyncList, + &CConfigurableElement::hasNoValidDomainAssociated) { // Aggegate elements _configurableElementAggregator.aggegate(pConfigurableElement); @@ -47,14 +50,13 @@ public: // Back synchronization virtual void sync() = 0; - virtual ~CBackSynchronizer() {} + virtual ~CBackSynchronizer() = default; protected: // Aggregate list - std::list<const CConfigurableElement*> _needingBackSyncList; + std::list<const CConfigurableElement *> _needingBackSyncList; private: // Aggegator CConfigurableElementAggregator _configurableElementAggregator; }; - diff --git a/parameter/BaseParameter.cpp b/parameter/BaseParameter.cpp index 07314bd..f28a26c 100644 --- a/parameter/BaseParameter.cpp +++ b/parameter/BaseParameter.cpp @@ -38,18 +38,23 @@ using std::string; -CBaseParameter::CBaseParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CBaseParameter::CBaseParameter(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } // XML configuration settings parsing/composing -bool CBaseParameter::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const +bool CBaseParameter::serializeXmlSettings( + CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const { // Handle access if (!configurationAccessContext.serializeOut()) { // Write to blackboard - if (!doSetValue(xmlConfigurationSettingsElementContent.getTextContent(), getOffset() - configurationAccessContext.getBaseOffset(), configurationAccessContext)) { + if (!doSetValue(xmlConfigurationSettingsElementContent.getTextContent(), + getOffset() - configurationAccessContext.getBaseOffset(), + configurationAccessContext)) { appendParameterPathToError(configurationAccessContext); return false; @@ -59,24 +64,25 @@ bool CBaseParameter::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsE // Get string value string strValue; - doGetValue(strValue, getOffset() - configurationAccessContext.getBaseOffset(), configurationAccessContext); + doGetValue(strValue, getOffset() - configurationAccessContext.getBaseOffset(), + configurationAccessContext); // Populate value into xml text node xmlConfigurationSettingsElementContent.setTextContent(strValue); } // Done - return true; + return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, + configurationAccessContext); } // Dump -void CBaseParameter::logValue(string& strValue, CErrorContext& errorContext) const +string CBaseParameter::logValue(CParameterAccessContext &context) const { - // Parameter context - CParameterAccessContext& parameterAccessContext = static_cast<CParameterAccessContext&>(errorContext); - // Dump value - doGetValue(strValue, getOffset(), parameterAccessContext); + string output; + doGetValue(output, getOffset(), context); + return output; } // Check element is a parameter @@ -85,98 +91,67 @@ bool CBaseParameter::isParameter() const return true; } -/// Value access -// Boolean access -bool CBaseParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(bool & /*bValue*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)bValue; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } - -bool CBaseParameter::accessAsBooleanArray(std::vector<bool>& abValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(std::vector<bool> & /*abValues*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)abValues; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } -// Integer Access -bool CBaseParameter::accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(uint32_t & /*bValue*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)uiValue; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } - -bool CBaseParameter::accessAsIntegerArray(std::vector<uint32_t>& auiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(std::vector<uint32_t> & /*abValues*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)auiValues; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } -// Signed Integer Access -bool CBaseParameter::accessAsSignedInteger(int32_t& iValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(int32_t & /*bValue*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)iValue; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } - -bool CBaseParameter::accessAsSignedIntegerArray(std::vector<int32_t>& aiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(std::vector<int32_t> & /*abValues*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)aiValues; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } -// Double Access -bool CBaseParameter::accessAsDouble(double& dValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(double & /*bValue*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)dValue; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } - -bool CBaseParameter::accessAsDoubleArray(std::vector<double>& adValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(std::vector<double> & /*abValues*/, bool /*bSet*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)adValues; - (void)bSet; - parameterAccessContext.setError("Unsupported conversion"); - return false; } // String Access -bool CBaseParameter::accessAsString(string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { if (bSet) { // Set Value - if (!doSetValue(strValue, getOffset() - parameterAccessContext.getBaseOffset(), parameterAccessContext)) { + if (!doSetValue(strValue, getOffset() - parameterAccessContext.getBaseOffset(), + parameterAccessContext)) { appendParameterPathToError(parameterAccessContext); return false; @@ -190,18 +165,16 @@ bool CBaseParameter::accessAsString(string& strValue, bool bSet, CParameterAcces } else { // Get Value - doGetValue(strValue, getOffset() - parameterAccessContext.getBaseOffset(), parameterAccessContext); + doGetValue(strValue, getOffset() - parameterAccessContext.getBaseOffset(), + parameterAccessContext); } return true; } -bool CBaseParameter::accessAsStringArray(std::vector<string>& astrValues, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::access(std::vector<string> & /*astrValues*/, bool /*bSet*/, + CParameterAccessContext & /*ctx*/) const { - (void)astrValues; - (void)bSet; - (void)parameterAccessContext; - // Generic string array access to scalar parameter must have been filtered out before assert(0); @@ -209,7 +182,8 @@ bool CBaseParameter::accessAsStringArray(std::vector<string>& astrValues, bool b } // Parameter Access -bool CBaseParameter::accessValue(CPathNavigator& pathNavigator, string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBaseParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { // Check path validity if (!checkPathExhausted(pathNavigator, parameterAccessContext)) { @@ -217,19 +191,19 @@ bool CBaseParameter::accessValue(CPathNavigator& pathNavigator, string& strValue return false; } - return accessAsString(strValue, bSet, parameterAccessContext); + return access(strValue, bSet, parameterAccessContext); } -void CBaseParameter::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CBaseParameter::structureToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Delegate to type element getTypeElement()->toXml(xmlElement, serializingContext); } - -void CBaseParameter::appendParameterPathToError(CParameterAccessContext& parameterAccessContext) -const +void CBaseParameter::appendParameterPathToError( + CParameterAccessContext ¶meterAccessContext) const { parameterAccessContext.appendToError(" " + getPath()); } diff --git a/parameter/BaseParameter.h b/parameter/BaseParameter.h index 848d638..1b80fb8 100644 --- a/parameter/BaseParameter.h +++ b/parameter/BaseParameter.h @@ -40,51 +40,71 @@ class CConfigurationAccessContext; class CBaseParameter : public CInstanceConfigurableElement { public: - CBaseParameter(const std::string& strName, const CTypeElement* pTypeElement); + CBaseParameter(const std::string &strName, const CTypeElement *pTypeElement); // XML configuration settings parsing/composing - virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const; + virtual bool serializeXmlSettings( + CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const; // Check element is a parameter virtual bool isParameter() const; - /// Value access // Boolean access - virtual bool accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual bool accessAsBooleanArray(std::vector<bool>& abValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + virtual bool access(bool &bValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool access(std::vector<bool> &abValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // Integer Access - virtual bool accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual bool accessAsIntegerArray(std::vector<uint32_t>& auiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + virtual bool access(uint32_t &uiValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool access(std::vector<uint32_t> &auiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // Signed Integer Access - virtual bool accessAsSignedInteger(int32_t& iValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual bool accessAsSignedIntegerArray(std::vector<int32_t>& aiValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + virtual bool access(int32_t &iValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool access(std::vector<int32_t> &aiValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // Double Access - virtual bool accessAsDouble(double& dValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual bool accessAsDoubleArray(std::vector<double>& adValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + virtual bool access(double &dValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool access(std::vector<double> &adValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // String Access - bool accessAsString(std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual bool accessAsStringArray(std::vector<std::string>& astrValues, bool bSet, CParameterAccessContext& parameterAccessContext) const; + // This one is not virtual because it is very generic. You can think if it + // as the client saying: "I don't care about the type, here's the value as + // a string - convert it yourself". Then, string-to-anything and + // anything-to-string methods are used to convert it into a suitable type. + bool access(std::string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool access(std::vector<std::string> &astrValues, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; - // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + void structureToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const override final; protected: // Parameter Access - virtual bool accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + virtual bool accessValue(CPathNavigator &pathNavigator, std::string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; // Actual value access (to be implemented by derived) - virtual bool doSetValue(const std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const = 0; - virtual void doGetValue(std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const = 0; + virtual bool doSetValue(const std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const = 0; + virtual void doGetValue(std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const = 0; /** * Append the parameter path to the error. * - * @param[in:out] parameterAccessContext Parameter Access Context object. + * @param[in,out] parameterAccessContext Parameter Access Context object. */ - void appendParameterPathToError(CParameterAccessContext& parameterAccessContext) const; + void appendParameterPathToError(CParameterAccessContext ¶meterAccessContext) const; + +private: + std::string logValue(CParameterAccessContext &context) const override; }; diff --git a/parameter/BinarySerializableElement.cpp b/parameter/BinarySerializableElement.cpp deleted file mode 100644 index 744d140..0000000 --- a/parameter/BinarySerializableElement.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2011-2014, Intel Corporation - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "BinarySerializableElement.h" - -#define base CElement - -using std::string; - -CBinarySerializableElement::CBinarySerializableElement(const string& strName) : base(strName) -{ -} - -// Binary Serialization -void CBinarySerializableElement::binarySerialize(CBinaryStream& binaryStream) -{ - // Propagate - size_t uiNbChildren = getNbChildren(); - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - CBinarySerializableElement* pChild = static_cast<CBinarySerializableElement*>(getChild(uiChild)); - - pChild->binarySerialize(binaryStream); - } -} - -// Data size -size_t CBinarySerializableElement::getDataSize() const -{ - // Propagate - size_t uiDataSize = 0; - size_t uiNbChildren = getNbChildren(); - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - const CBinarySerializableElement* pChild = static_cast<const CBinarySerializableElement*>(getChild(uiChild)); - - uiDataSize += pChild->getDataSize(); - } - - return uiDataSize; -} - diff --git a/parameter/BinaryStream.cpp b/parameter/BinaryStream.cpp deleted file mode 100644 index 2dc3380..0000000 --- a/parameter/BinaryStream.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2011-2014, Intel Corporation - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "BinaryStream.h" -#include <string.h> -#include <assert.h> - -using namespace std; - -CBinaryStream::CBinaryStream(const string& strFileName, bool bOut, size_t uiDataSize, uint8_t uiStructureChecksum) : - _strFileName(strFileName), - _bOut(bOut), - _uiDataSize(uiDataSize), - _uiStructureChecksum(uiStructureChecksum), - _puiData(new uint8_t[uiDataSize]), - _uiPos(0), - _bOpen(false) -{ -} - -CBinaryStream::~CBinaryStream() -{ - if (_bOpen) { - - close(); - } - - delete [] _puiData; -} - -bool CBinaryStream::open(string& strError) -{ - assert(!_bOpen); - - _fileStream.open(_strFileName.c_str(), (_bOut ? ios::out : ios::in|ios::ate)|ios::binary); - - if (!_fileStream.is_open() || !_fileStream.good()) { - - strError = string("Failed to ") + (_bOut ? "write" : "read") + "-open"; - - return false; - } - if (!_bOut) { - - // Get file size - size_t uiFileSize = _fileStream.tellg(); - - // Validate file size - if (_uiDataSize + sizeof(_uiStructureChecksum) != uiFileSize) { - - // Size different from expected - strError = "Unexpected file size"; - - return false; - } - - // Back to beginning of file - _fileStream.seekg(0, ios::beg); - - // Get data - _fileStream.read((char*)_puiData, _uiDataSize); - - // File checksum - uint8_t uiFileChecksum; - _fileStream.read((char*)&uiFileChecksum, sizeof(uiFileChecksum)); - - // Data checksum - uint8_t uiDataChecksum = computeChecksum(); - - // Validate checksum - if (uiDataChecksum != uiFileChecksum) { - - strError = "Integrity checks failed"; - - return false; - } - } - - // Keep track - _bOpen = true; - - return true; -} - -void CBinaryStream::close() -{ - assert(_bOpen); - - if (_bOut) { - - // Get data - _fileStream.write((const char*)_puiData, _uiDataSize); - - // Compute checksum - uint8_t uiDataChecksum = computeChecksum(); - - // Write checksum - _fileStream.write((const char*)&uiDataChecksum, sizeof(uiDataChecksum)); - } - - // Keep track - _bOpen = false; - - // Close file - _fileStream.close(); -} - -void CBinaryStream::reset() -{ - _uiPos = 0; -} - -void CBinaryStream::write(const uint8_t* puiData, size_t uiSize) -{ - assert(_uiPos + uiSize <= _uiDataSize); - - memcpy(&_puiData[_uiPos], puiData, uiSize); - - _uiPos += uiSize; -} - -void CBinaryStream::read(uint8_t* puiData, size_t uiSize) -{ - assert(_uiPos + uiSize <= _uiDataSize); - - memcpy(puiData, &_puiData[_uiPos], uiSize); - - _uiPos += uiSize; -} - -uint8_t CBinaryStream::computeChecksum() const -{ - uint32_t uiIndex; - uint8_t uiDataChecksum = _uiStructureChecksum; - - for (uiIndex = 0; uiIndex < _uiDataSize; uiIndex++) { - - uiDataChecksum += _puiData[uiIndex]; - } - return uiDataChecksum; -} - -bool CBinaryStream::isOut() const -{ - return _bOut; -} diff --git a/parameter/BitParameter.cpp b/parameter/BitParameter.cpp index 2a53afd..81a9800 100644 --- a/parameter/BitParameter.cpp +++ b/parameter/BitParameter.cpp @@ -39,7 +39,8 @@ using std::string; -CBitParameter::CBitParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CBitParameter::CBitParameter(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } @@ -50,35 +51,37 @@ CInstanceConfigurableElement::Type CBitParameter::getType() const } // Size -uint32_t CBitParameter::getBelongingBlockSize() const +size_t CBitParameter::getBelongingBlockSize() const { - return static_cast<const CBitParameterBlock*>(getParent())->getSize(); + return static_cast<const CBitParameterBlock *>(getParent())->getSize(); } // Instantiation, allocation -uint32_t CBitParameter::getFootPrint() const +size_t CBitParameter::getFootPrint() const { // Allocation done at parent level return 0; } // Actual parameter access (tuning) -bool CBitParameter::doSetValue(const string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CBitParameter::doSetValue(const string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - return doSet(strValue, uiOffset, parameterAccessContext); + return doSet(strValue, offset, parameterAccessContext); } -void CBitParameter::doGetValue(string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +void CBitParameter::doGetValue(string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - doGet(strValue, uiOffset, parameterAccessContext); + doGet(strValue, offset, parameterAccessContext); } /// Value access -// Boolean access -bool CBitParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBitParameter::access(bool &bValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { // Check boolean access validity here - if (static_cast<const CBitParameterType*>(getTypeElement())->getBitSize() != 1) { + if (static_cast<const CBitParameterType *>(getTypeElement())->getBitSize() != 1) { parameterAccessContext.setError("Type mismatch"); appendParameterPathToError(parameterAccessContext); @@ -94,7 +97,7 @@ bool CBitParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessCon uiValue = bValue; } - if (!accessAsInteger(uiValue, bSet, parameterAccessContext)) { + if (!access(uiValue, bSet, parameterAccessContext)) { return false; } @@ -107,15 +110,15 @@ bool CBitParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessCon return true; } -// Integer Access -bool CBitParameter::accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CBitParameter::access(uint32_t &uiValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { - uint32_t uiOffset = getOffset(); + size_t offset = getOffset(); if (bSet) { // Set Value - if (!doSet(uiValue, uiOffset, parameterAccessContext)) { + if (!doSet(uiValue, offset, parameterAccessContext)) { appendParameterPathToError(parameterAccessContext); return false; @@ -129,50 +132,54 @@ bool CBitParameter::accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAcce } else { // Convert - doGet(uiValue, uiOffset, parameterAccessContext); + doGet(uiValue, offset, parameterAccessContext); } return true; } template <typename type> -bool CBitParameter::doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CBitParameter::doSet(type value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint64_t uiData = 0; // Read/modify/write - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->readInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->readInteger(&uiData, getBelongingBlockSize(), offset); // Convert - if (!static_cast<const CBitParameterType*>(getTypeElement())->toBlackboard(value, uiData, parameterAccessContext)) { + if (!static_cast<const CBitParameterType *>(getTypeElement()) + ->toBlackboard(value, uiData, parameterAccessContext)) { return false; } // Write blackboard - pBlackboard->writeInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->writeInteger(&uiData, getBelongingBlockSize(), offset); return true; } template <typename type> -void CBitParameter::doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +void CBitParameter::doGet(type &value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint64_t uiData = 0; // Read blackboard - const CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->readInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->readInteger(&uiData, getBelongingBlockSize(), offset); // Convert - static_cast<const CBitParameterType*>(getTypeElement())->fromBlackboard(value, uiData, parameterAccessContext); + static_cast<const CBitParameterType *>(getTypeElement()) + ->fromBlackboard(value, uiData, parameterAccessContext); } // AreaConfiguration creation -CAreaConfiguration* CBitParameter::createAreaConfiguration(const CSyncerSet* pSyncerSet) const +CAreaConfiguration *CBitParameter::createAreaConfiguration(const CSyncerSet *pSyncerSet) const { return new CBitwiseAreaConfiguration(this, pSyncerSet); } @@ -181,5 +188,5 @@ CAreaConfiguration* CBitParameter::createAreaConfiguration(const CSyncerSet* pSy uint64_t CBitParameter::merge(uint64_t uiOriginData, uint64_t uiNewData) const { // Convert - return static_cast<const CBitParameterType*>(getTypeElement())->merge(uiOriginData, uiNewData); + return static_cast<const CBitParameterType *>(getTypeElement())->merge(uiOriginData, uiNewData); } diff --git a/parameter/BitParameter.h b/parameter/BitParameter.h index f9e2b9d..cbe071e 100644 --- a/parameter/BitParameter.h +++ b/parameter/BitParameter.h @@ -36,39 +36,42 @@ class CBitParameter : public CBaseParameter { public: - CBitParameter(const std::string& strName, const CTypeElement* pTypeElement); + CBitParameter(const std::string &strName, const CTypeElement *pTypeElement); // Instantiation, allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; // Type virtual Type getType() const; /// Value access // Boolean access - virtual bool accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(bool &bValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; // Integer Access - virtual bool accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(uint32_t &uiValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override final; // AreaConfiguration creation - virtual CAreaConfiguration* createAreaConfiguration(const CSyncerSet* pSyncerSet) const; + virtual CAreaConfiguration *createAreaConfiguration(const CSyncerSet *pSyncerSet) const; // Size - uint32_t getBelongingBlockSize() const; + size_t getBelongingBlockSize() const; // Access from area configuration uint64_t merge(uint64_t uiOriginData, uint64_t uiNewData) const; -private: +private: // String Access - virtual bool doSetValue(const std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; - virtual void doGetValue(std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + virtual bool doSetValue(const std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; + virtual void doGetValue(std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; // Generic Access template <typename type> - bool doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + bool doSet(type value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; template <typename type> - void doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; - + void doGet(type &value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; }; diff --git a/parameter/BitParameterBlock.cpp b/parameter/BitParameterBlock.cpp index a394aab..360a6f5 100644 --- a/parameter/BitParameterBlock.cpp +++ b/parameter/BitParameterBlock.cpp @@ -36,7 +36,8 @@ using std::string; -CBitParameterBlock::CBitParameterBlock(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CBitParameterBlock::CBitParameterBlock(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } @@ -46,27 +47,30 @@ CInstanceConfigurableElement::Type CBitParameterBlock::getType() const } // Instantiation, allocation -uint32_t CBitParameterBlock::getFootPrint() const +size_t CBitParameterBlock::getFootPrint() const { return getSize(); } // Size -uint32_t CBitParameterBlock::getSize() const +size_t CBitParameterBlock::getSize() const { - return static_cast<const CBitParameterBlockType*>(getTypeElement())->getSize(); + return static_cast<const CBitParameterBlockType *>(getTypeElement())->getSize(); } // Used for simulation and virtual subsystems -void CBitParameterBlock::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CBitParameterBlock::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { - // Get default value from type - uint32_t uiDefaultValue = 0; + // Default value is 0 as their is no min bound for bit parameters, + // thus 0 is always a valid value. + // BitParameterBlock can be as long a 64 bit, thus an 64 bit long variable + // is necessary to initialize it. + uint64_t uiDefaultValue = 0; // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->writeInteger(&uiDefaultValue, getSize(), getOffset() - parameterAccessContext.getBaseOffset(), parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->writeInteger(&uiDefaultValue, getSize(), + getOffset() - parameterAccessContext.getBaseOffset()); } - diff --git a/parameter/BitParameterBlock.h b/parameter/BitParameterBlock.h index f965b30..f1068f6 100644 --- a/parameter/BitParameterBlock.h +++ b/parameter/BitParameterBlock.h @@ -34,18 +34,23 @@ class CBitParameterBlock : public CInstanceConfigurableElement { public: - CBitParameterBlock(const std::string& strName, const CTypeElement* pTypeElement); + CBitParameterBlock(const std::string &strName, const CTypeElement *pTypeElement); // Instantiation, allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; // Type virtual Type getType() const; // Size - uint32_t getSize() const; + size_t getSize() const; // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; -}; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; + void structureToXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const + { + xmlElement.setAttribute("Size", getSize() * 8); + CInstanceConfigurableElement::structureToXml(xmlElement, serializingContext); + } +}; diff --git a/parameter/BitParameterBlockType.cpp b/parameter/BitParameterBlockType.cpp index 0d344f2..316676d 100644 --- a/parameter/BitParameterBlockType.cpp +++ b/parameter/BitParameterBlockType.cpp @@ -35,7 +35,7 @@ using std::string; -CBitParameterBlockType::CBitParameterBlockType(const string& strName) : base(strName), _uiSize(0) +CBitParameterBlockType::CBitParameterBlockType(const string &strName) : base(strName) { } @@ -50,32 +50,35 @@ bool CBitParameterBlockType::childrenAreDynamic() const } // Size -uint32_t CBitParameterBlockType::getSize() const +size_t CBitParameterBlockType::getSize() const { - return _uiSize; + return _size; } // From IXmlSink -bool CBitParameterBlockType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CBitParameterBlockType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Size - _uiSize = xmlElement.getAttributeInteger("Size") / 8; + xmlElement.getAttribute("Size", _size); + _size /= 8; // Base return base::fromXml(xmlElement, serializingContext); } // Instantiation -CInstanceConfigurableElement* CBitParameterBlockType::doInstantiate() const +CInstanceConfigurableElement *CBitParameterBlockType::doInstantiate() const { return new CBitParameterBlock(getName(), this); } // From IXmlSource -void CBitParameterBlockType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CBitParameterBlockType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Size - xmlElement.setAttributeString("Size", CUtility::toString(_uiSize * 8)); + xmlElement.setAttribute("Size", _size * 8); base::toXml(xmlElement, serializingContext); } diff --git a/parameter/BitParameterBlockType.h b/parameter/BitParameterBlockType.h index 0808e94..419d7aa 100644 --- a/parameter/BitParameterBlockType.h +++ b/parameter/BitParameterBlockType.h @@ -36,25 +36,25 @@ class CBitParameterBlockType : public CTypeElement { public: - CBitParameterBlockType(const std::string& strName); + CBitParameterBlockType(const std::string &strName); // Size - uint32_t getSize() const; + size_t getSize() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // CElement virtual std::string getKind() const; + private: virtual bool childrenAreDynamic() const; // Instantiation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Size in bytes - uint32_t _uiSize; + size_t _size{0}; }; - diff --git a/parameter/BitParameterType.cpp b/parameter/BitParameterType.cpp index 14fe901..5a5c353 100644 --- a/parameter/BitParameterType.cpp +++ b/parameter/BitParameterType.cpp @@ -39,7 +39,7 @@ using std::string; -CBitParameterType::CBitParameterType(const string& strName) : base(strName), _uiBitPos(0), _uiBitSize(0), _uiMax(uint64_t(-1)) +CBitParameterType::CBitParameterType(const string &strName) : base(strName) { } @@ -50,46 +50,49 @@ string CBitParameterType::getKind() const } // Element properties -void CBitParameterType::showProperties(string& strResult) const +void CBitParameterType::showProperties(string &strResult) const { base::showProperties(strResult); // Bit Pos strResult += "Bit pos: "; - strResult += CUtility::toString(_uiBitPos); + strResult += std::to_string(_bitPos); strResult += "\n"; // Bit size strResult += "Bit size: "; - strResult += CUtility::toString(_uiBitSize); + strResult += std::to_string(_uiBitSize); strResult += "\n"; // Max strResult += "Max: "; - strResult += CUtility::toString(_uiMax); + strResult += std::to_string(_uiMax); strResult += "\n"; } // From IXmlSink -bool CBitParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CBitParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Pos - _uiBitPos = xmlElement.getAttributeInteger("Pos"); + xmlElement.getAttribute("Pos", _bitPos); // Size - _uiBitSize = xmlElement.getAttributeInteger("Size"); + xmlElement.getAttribute("Size", _uiBitSize); // Validate bit pos and size still fit into parent type - const CBitParameterBlockType* pBitParameterBlockType = static_cast<const CBitParameterBlockType*>(getParent()); + const CBitParameterBlockType *pBitParameterBlockType = + static_cast<const CBitParameterBlockType *>(getParent()); - uint32_t uiParentBlockBitSize = pBitParameterBlockType->getSize() * 8; + size_t uiParentBlockBitSize = pBitParameterBlockType->getSize() * 8; - if (_uiBitPos + _uiBitSize > uiParentBlockBitSize) { + if (_bitPos + _uiBitSize > uiParentBlockBitSize) { // Range exceeded - std::ostringstream strStream; + std::ostringstream strStream; - strStream << "Pos and Size attributes inconsistent with maximum container element size (" << uiParentBlockBitSize << " bits) for " + getKind(); + strStream << "Pos and Size attributes inconsistent with maximum container element size (" + << uiParentBlockBitSize << " bits) for " + getKind(); serializingContext.setError(strStream.str()); @@ -97,24 +100,18 @@ bool CBitParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingCo } // Max - if (xmlElement.hasAttribute("Max")) { + _uiMax = getMaxEncodableValue(); + if (xmlElement.getAttribute("Max", _uiMax) && (_uiMax > getMaxEncodableValue())) { - _uiMax = xmlElement.getAttributeInteger("Max"); + // Max value exceeded + std::ostringstream strStream; - if (_uiMax > getMaxEncodableValue()) { + strStream << "Max attribute inconsistent with maximum encodable size (" + << getMaxEncodableValue() << ") for " + getKind(); - // Max value exceeded - std::ostringstream strStream; - - strStream << "Max attribute inconsistent with maximum encodable size (" << getMaxEncodableValue() << ") for " + getKind(); - - serializingContext.setError(strStream.str()); - - return false; - } - } else { + serializingContext.setError(strStream.str()); - _uiMax = getMaxEncodableValue(); + return false; } // Base @@ -122,24 +119,23 @@ bool CBitParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingCo } // Conversion -bool CBitParameterType::toBlackboard(const string& strValue, uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBitParameterType::toBlackboard(const string &strValue, uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - // Hexa - bool bValueProvidedAsHexa = !strValue.compare(0, 2, "0x"); - // Get value uint64_t uiConvertedValue = strtoull(strValue.c_str(), NULL, 0); if (uiConvertedValue > _uiMax) { // Range exceeded - std::ostringstream strStream; + std::ostringstream strStream; strStream << "Value " << strValue << " standing out of admitted range ["; - if (bValueProvidedAsHexa) { + if (utility::isHexadecimal(strValue)) { - strStream << "0x0, " << "0x" << std::hex << std::uppercase; + strStream << "0x0, " + << "0x" << std::hex << std::uppercase; } else { strStream << "0, "; @@ -152,14 +148,15 @@ bool CBitParameterType::toBlackboard(const string& strValue, uint64_t& uiValue, } // Do bitwise RMW operation - uiValue = (uiValue & ~getMask()) | (uiConvertedValue << _uiBitPos); + uiValue = (uiValue & ~getMask()) | (uiConvertedValue << _bitPos); return true; } -void CBitParameterType::fromBlackboard(string& strValue, const uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const +void CBitParameterType::fromBlackboard(string &strValue, const uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - uint64_t uiConvertedValue = (uiValue & getMask()) >> _uiBitPos; + uint64_t uiConvertedValue = (uiValue & getMask()) >> _bitPos; // Format std::ostringstream strStream; @@ -177,7 +174,8 @@ void CBitParameterType::fromBlackboard(string& strValue, const uint64_t& uiValue // Value access // Integer -bool CBitParameterType::toBlackboard(uint64_t uiUserValue, uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBitParameterType::toBlackboard(uint64_t uiUserValue, uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { if (uiUserValue > _uiMax) { @@ -187,16 +185,15 @@ bool CBitParameterType::toBlackboard(uint64_t uiUserValue, uint64_t& uiValue, CP } // Do bitwise RMW operation - uiValue = (uiValue & ~getMask()) | (uiUserValue << _uiBitPos); + uiValue = (uiValue & ~getMask()) | (uiUserValue << _bitPos); return true; } -void CBitParameterType::fromBlackboard(uint32_t& uiUserValue, uint64_t uiValue, CParameterAccessContext& parameterAccessContext) const +void CBitParameterType::fromBlackboard(uint32_t &userValue, uint64_t value, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - - uiUserValue = (uiValue & getMask()) >> _uiBitPos; + userValue = static_cast<uint32_t>((value & getMask()) >> _bitPos); } // Access from area configuration @@ -206,12 +203,12 @@ uint64_t CBitParameterType::merge(uint64_t uiOriginData, uint64_t uiNewData) con } // Bit Size -uint32_t CBitParameterType::getBitSize() const +size_t CBitParameterType::getBitSize() const { return _uiBitSize; } -CInstanceConfigurableElement* CBitParameterType::doInstantiate() const +CInstanceConfigurableElement *CBitParameterType::doInstantiate() const { return new CBitParameter(getName(), this); } @@ -225,13 +222,13 @@ uint64_t CBitParameterType::getMaxEncodableValue() const // Biwise mask uint64_t CBitParameterType::getMask() const { - return getMaxEncodableValue() << _uiBitPos; + return getMaxEncodableValue() << _bitPos; } // Check data has no bit set outside available range bool CBitParameterType::isEncodable(uint64_t uiData) const { - uint32_t uiShift = 8 * sizeof(uiData) - _uiBitSize; + size_t uiShift = 8 * sizeof(uiData) - _uiBitSize; if (uiShift) { @@ -243,17 +240,17 @@ bool CBitParameterType::isEncodable(uint64_t uiData) const } // From IXmlSource -void CBitParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CBitParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Position - xmlElement.setAttributeString("Pos", CUtility::toString(_uiBitPos)); + xmlElement.setAttribute("Pos", _bitPos); // Size - xmlElement.setAttributeString("Size", CUtility::toString(_uiBitSize)); + xmlElement.setAttribute("Size", _uiBitSize); // Maximum - xmlElement.setAttributeString("Max", CUtility::toString(_uiMax)); + xmlElement.setAttribute("Max", _uiMax); base::toXml(xmlElement, serializingContext); - } diff --git a/parameter/BitParameterType.h b/parameter/BitParameterType.h index 4c91a1a..f8d67ed 100644 --- a/parameter/BitParameterType.h +++ b/parameter/BitParameterType.h @@ -34,34 +34,39 @@ #include "TypeElement.h" #include <string> +#include <limits> class CParameterAccessContext; class CBitParameterType : public CTypeElement { public: - CBitParameterType(const std::string& strName); + CBitParameterType(const std::string &strName); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; /// Conversion // String - bool toBlackboard(const std::string& strValue, uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - void fromBlackboard(std::string& strValue, const uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + bool toBlackboard(const std::string &strValue, uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + void fromBlackboard(std::string &strValue, const uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Integer - bool toBlackboard(uint64_t uiUserValue, uint64_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - void fromBlackboard(uint32_t& uiUserValue, uint64_t uiValue, CParameterAccessContext& parameterAccessContext) const; + bool toBlackboard(uint64_t uiUserValue, uint64_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + void fromBlackboard(uint32_t &uiUserValue, uint64_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Access from area configuration uint64_t merge(uint64_t uiOriginData, uint64_t uiNewData) const; // Bit Size - uint32_t getBitSize() const; + size_t getBitSize() const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // CElement virtual std::string getKind() const; @@ -72,10 +77,10 @@ public: * * @return position of the bit. */ - uint32_t getBitPos() const { return _uiBitPos; } + size_t getBitPos() const { return _bitPos; } private: // Instantiation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Max encodable value uint64_t getMaxEncodableValue() const; // Biwise mask @@ -84,9 +89,9 @@ private: bool isEncodable(uint64_t uiData) const; // Pos in bits - uint32_t _uiBitPos; + size_t _bitPos{0}; // Size in bits - uint32_t _uiBitSize; + size_t _uiBitSize{0}; // Max value - uint64_t _uiMax; + uint64_t _uiMax{std::numeric_limits<uint64_t>::max()}; }; diff --git a/parameter/BitwiseAreaConfiguration.cpp b/parameter/BitwiseAreaConfiguration.cpp index 6440019..f2a09f0 100644 --- a/parameter/BitwiseAreaConfiguration.cpp +++ b/parameter/BitwiseAreaConfiguration.cpp @@ -33,17 +33,18 @@ #define base CAreaConfiguration -CBitwiseAreaConfiguration::CBitwiseAreaConfiguration(const CConfigurableElement *pConfigurableElement, const CSyncerSet *pSyncerSet) - : base(pConfigurableElement, pSyncerSet, static_cast<const CBitParameter*>(pConfigurableElement)->getBelongingBlockSize()), - _bBigEndian(pConfigurableElement->getBelongingSubsystem()->isBigEndian()) +CBitwiseAreaConfiguration::CBitwiseAreaConfiguration( + const CConfigurableElement *pConfigurableElement, const CSyncerSet *pSyncerSet) + : base(pConfigurableElement, pSyncerSet, + static_cast<const CBitParameter *>(pConfigurableElement)->getBelongingBlockSize()) { } // Blackboard copies -void CBitwiseAreaConfiguration::copyTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const +void CBitwiseAreaConfiguration::copyTo(CParameterBlackboard *pToBlackboard, size_t offset) const { // Beware this code works on little endian architectures only! - const CBitParameter* pBitParameter = static_cast<const CBitParameter*>(_pConfigurableElement); + const CBitParameter *pBitParameter = static_cast<const CBitParameter *>(_pConfigurableElement); uint64_t uiSrcData = 0; uint64_t uiDstData = 0; @@ -51,22 +52,22 @@ void CBitwiseAreaConfiguration::copyTo(CParameterBlackboard* pToBlackboard, uint /// Read/modify/write // Read dst blackboard - pToBlackboard->readInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), uiOffset, _bBigEndian); + pToBlackboard->readInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), offset); // Read src blackboard - _blackboard.readInteger(&uiSrcData, pBitParameter->getBelongingBlockSize(), 0, _bBigEndian); + _blackboard.readInteger(&uiSrcData, pBitParameter->getBelongingBlockSize(), 0); // Convert uiDstData = pBitParameter->merge(uiDstData, uiSrcData); // Write dst blackboard - pToBlackboard->writeInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), uiOffset, _bBigEndian); + pToBlackboard->writeInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), offset); } -void CBitwiseAreaConfiguration::copyFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset) +void CBitwiseAreaConfiguration::copyFrom(const CParameterBlackboard *pFromBlackboard, size_t offset) { // Beware this code works on little endian architectures only! - const CBitParameter* pBitParameter = static_cast<const CBitParameter*>(_pConfigurableElement); + const CBitParameter *pBitParameter = static_cast<const CBitParameter *>(_pConfigurableElement); uint64_t uiSrcData = 0; uint64_t uiDstData = 0; @@ -74,15 +75,14 @@ void CBitwiseAreaConfiguration::copyFrom(const CParameterBlackboard* pFromBlackb /// Read/modify/write // Read dst blackboard - _blackboard.readInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), 0, _bBigEndian); + _blackboard.readInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), 0); // Read src blackboard - pFromBlackboard->readInteger(&uiSrcData, pBitParameter->getBelongingBlockSize(), uiOffset, _bBigEndian); + pFromBlackboard->readInteger(&uiSrcData, pBitParameter->getBelongingBlockSize(), offset); // Convert uiDstData = pBitParameter->merge(uiDstData, uiSrcData); // Write dst blackboard - _blackboard.writeInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), 0, _bBigEndian); + _blackboard.writeInteger(&uiDstData, pBitParameter->getBelongingBlockSize(), 0); } - diff --git a/parameter/BitwiseAreaConfiguration.h b/parameter/BitwiseAreaConfiguration.h index 96b972a..4a10c2c 100644 --- a/parameter/BitwiseAreaConfiguration.h +++ b/parameter/BitwiseAreaConfiguration.h @@ -36,14 +36,11 @@ class CBitParameter; class CBitwiseAreaConfiguration : public CAreaConfiguration { public: - CBitwiseAreaConfiguration(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet); + CBitwiseAreaConfiguration(const CConfigurableElement *pConfigurableElement, + const CSyncerSet *pSyncerSet); private: // Blackboard copies - virtual void copyTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const; - virtual void copyFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset); - - // Endianness - bool _bBigEndian; + virtual void copyTo(CParameterBlackboard *pToBlackboard, size_t offset) const; + virtual void copyFrom(const CParameterBlackboard *pFromBlackboard, size_t offset); }; - diff --git a/parameter/BooleanParameterType.cpp b/parameter/BooleanParameterType.cpp index 87088ef..66556d3 100644 --- a/parameter/BooleanParameterType.cpp +++ b/parameter/BooleanParameterType.cpp @@ -29,25 +29,23 @@ */ #include "BooleanParameterType.h" #include "ParameterAccessContext.h" +#include "Utility.h" #define base CParameterType -CBooleanParameterType::CBooleanParameterType(const std::string& strName) : base(strName) +CBooleanParameterType::CBooleanParameterType(const std::string &strName) : base(strName) { setSize(1); } -CBooleanParameterType::~CBooleanParameterType() -{ -} - std::string CBooleanParameterType::getKind() const { return "BooleanParameter"; } // Tuning interface -bool CBooleanParameterType::toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { if (strValue == "1" || strValue == "0x1") { @@ -58,10 +56,7 @@ bool CBooleanParameterType::toBlackboard(const std::string& strValue, uint32_t& } else { parameterAccessContext.setError(strValue + " value not part of numerical space {"); - // Hexa - bool bValueProvidedAsHexa = !strValue.compare(0, 2, "0x"); - - if (bValueProvidedAsHexa) { + if (utility::isHexadecimal(strValue)) { parameterAccessContext.appendToError("0x0, 0x1"); } else { @@ -76,7 +71,8 @@ bool CBooleanParameterType::toBlackboard(const std::string& strValue, uint32_t& return true; } -bool CBooleanParameterType::fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { strValue = uiValue ? "1" : "0"; @@ -89,26 +85,25 @@ bool CBooleanParameterType::fromBlackboard(std::string& strValue, const uint32_t } // Value access -bool CBooleanParameterType::toBlackboard(bool bUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::toBlackboard(bool bUserValue, uint32_t &uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - uiValue = bUserValue; return true; } -bool CBooleanParameterType::fromBlackboard(bool& bUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::fromBlackboard(bool &bUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - bUserValue = uiValue != 0; return true; } // Integer -bool CBooleanParameterType::toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::toBlackboard(uint32_t uiUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { if (uiUserValue > 1) { @@ -120,10 +115,9 @@ bool CBooleanParameterType::toBlackboard(uint32_t uiUserValue, uint32_t& uiValue return true; } -bool CBooleanParameterType::fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CBooleanParameterType::fromBlackboard(uint32_t &uiUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - uiUserValue = uiValue != 0; return true; diff --git a/parameter/BooleanParameterType.h b/parameter/BooleanParameterType.h index 2f95eb7..6a88488 100644 --- a/parameter/BooleanParameterType.h +++ b/parameter/BooleanParameterType.h @@ -36,20 +36,26 @@ class CBooleanParameterType : public CParameterType { public: - CBooleanParameterType(const std::string& strName); - virtual ~CBooleanParameterType(); + CBooleanParameterType(const std::string &strName); + virtual ~CBooleanParameterType() = default; // Kind virtual std::string getKind() const; /// Conversion // String - virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Boolean - virtual bool toBlackboard(bool bUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(bool& bUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(bool bUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(bool &bUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Integer - virtual bool toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(uint32_t uiUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(uint32_t &uiUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; }; diff --git a/parameter/CMakeLists.txt b/parameter/CMakeLists.txt index 94369fb..230dd5f 100644 --- a/parameter/CMakeLists.txt +++ b/parameter/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014, Intel Corporation +# Copyright (c) 2014-2015, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, @@ -26,19 +26,23 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +if(WIN32) + set(parameter_RESOURCE_FILE "${CMAKE_CURRENT_BINARY_DIR}/Resource.rc") + set(parameter_OS_SPECIFIC_SRCS ${parameter_RESOURCE_FILE}) +endif() + add_library(parameter SHARED + ${parameter_OS_SPECIFIC_SRCS} AreaConfiguration.cpp ArrayParameter.cpp - AutoLog.cpp BaseParameter.cpp - BinarySerializableElement.cpp - BinaryStream.cpp BitParameterBlock.cpp BitParameterBlockType.cpp BitParameter.cpp BitParameterType.cpp BitwiseAreaConfiguration.cpp BooleanParameterType.cpp + CommandHandlerWrapper.cpp ComponentInstance.cpp ComponentLibrary.cpp ComponentType.cpp @@ -55,8 +59,8 @@ add_library(parameter SHARED ElementLocator.cpp EnumParameterType.cpp EnumValuePair.cpp - ErrorContext.cpp FixedPointParameterType.cpp + FloatingPointParameterType.cpp FormattedSubsystemObject.cpp FrameworkConfigurationLocation.cpp HardwareBackSynchronizer.cpp @@ -65,6 +69,7 @@ add_library(parameter SHARED IntegerParameterType.cpp LinearParameterAdaptation.cpp LogarithmicParameterAdaptation.cpp + LoggingElementBuilderTemplate.cpp MappingContext.cpp MappingData.cpp ParameterAccessContext.cpp @@ -73,7 +78,7 @@ add_library(parameter SHARED ParameterBlockType.cpp Parameter.cpp ParameterFrameworkConfiguration.cpp - ParameterHandle.cpp + ElementHandle.cpp ParameterMgr.cpp ParameterMgrFullConnector.cpp ParameterMgrPlatformConnector.cpp @@ -103,19 +108,43 @@ add_library(parameter SHARED XmlFileIncluderElement.cpp XmlParameterSerializingContext.cpp) -include_directories( - include - "${PROJECT_SOURCE_DIR}/xmlserializer" - "${PROJECT_SOURCE_DIR}/utility" - "${PROJECT_SOURCE_DIR}/remote-processor") +include(GenerateExportHeader) +generate_export_header(parameter) + +if(WIN32) + set(WINRC_MAJOR ${PF_VERSION_MAJOR}) + set(WINRC_MINOR ${PF_VERSION_MINOR}) + set(WINRC_PATCH ${PF_VERSION_PATCH}) + set(WINRC_TWEAK ${PF_VERSION_TWEAK}) + target_compile_definitions(parameter PRIVATE + WINRC_DLL + WINRC_FILENAME="$<TARGET_FILE_NAME:parameter>") + set(WINRC_FILE_DESCRIPTION "Parameter Framework library") + configure_file("${PROJECT_SOURCE_DIR}/support/windows/Resource.rc.in" + "${parameter_RESOURCE_FILE}") +endif() + +configure_file(version.h.in "${CMAKE_CURRENT_BINARY_DIR}/version.h") + +target_link_libraries(parameter + # Unfortunatly xmlSink and xmlSource need to be exposed to the plugins + PUBLIC xmlserializer + PRIVATE pfw_utility remote-processor + PRIVATE ${CMAKE_DL_LIBS}) -# No need to link with libremote-processor: it is accessed via dlopen() -find_library(dl dl) -target_link_libraries(parameter xmlserializer pfw_utility dl) +target_include_directories(parameter + PUBLIC include log/include + # Export symbol macro header + PUBLIC "${CMAKE_CURRENT_BINARY_DIR}" + # FIXE: define . as an PUBLIC include directory only for plugins + PUBLIC .) -install(TARGETS parameter LIBRARY DESTINATION lib) +install(TARGETS parameter LIBRARY DESTINATION lib RUNTIME DESTINATION bin ARCHIVE DESTINATION lib) # Client headers install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/parameter_export.h" + include/CommandHandlerInterface.h + include/ElementHandle.h include/ParameterHandle.h include/ParameterMgrLoggerForward.h include/ParameterMgrFullConnector.h @@ -125,10 +154,9 @@ install(FILES DESTINATION "include/parameter/client") # Core (plugin) headers install(FILES - AutoLog.h + "${CMAKE_CURRENT_BINARY_DIR}/parameter_export.h" BitParameterBlockType.h ConfigurableElement.h - ConfigurableElementWithMapping.h DefaultElementLibrary.h Element.h ElementBuilder.h @@ -136,12 +164,13 @@ install(FILES FileIncluderElementBuilder.h FormattedSubsystemObject.h InstanceConfigurableElement.h + LoggingElementBuilderTemplate.h Mapper.h MappingContext.h - NamedElementBuilderTemplate.h ParameterBlockType.h ParameterType.h PathNavigator.h + Plugin.h Subsystem.h SubsystemLibrary.h SubsystemObject.h @@ -151,3 +180,5 @@ install(FILES TypeElement.h VirtualSubsystem.h DESTINATION "include/parameter/plugin") +install(DIRECTORY log/include/log/ + DESTINATION "include/parameter/plugin/log") diff --git a/parameter/AutoLog.cpp b/parameter/CommandHandlerWrapper.cpp index ff7151a..c291f34 100644 --- a/parameter/AutoLog.cpp +++ b/parameter/CommandHandlerWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,27 +27,23 @@ * (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 "AutoLog.h" -using std::string; +#include "CommandHandlerWrapper.h" +#include <RequestMessage.h> -CAutoLog::CAutoLog(const CElement* pElement, const string& strContext, bool bLogOn) - : _pElement(pElement), _strContext(strContext), _bLogOn(bLogOn) +CommandHandlerWrapper::CommandHandlerWrapper(std::unique_ptr<IRemoteCommandHandler> &&wrapped) + : mWrapped(std::move(wrapped)) { - if (_bLogOn) { - // Log - _pElement->doLog(false, _strContext + " {"); - // Nest - _pElement->nestLog(); - } } -CAutoLog::~CAutoLog() +bool CommandHandlerWrapper::process(const std::string &command, + const std::vector<std::string> &arguments, std::string &output) { - if (_bLogOn) { - // Unnest - _pElement->unnestLog(); - // Log - _pElement->doLog(false, "} " + _strContext); + CRequestMessage request(command); + + for (auto &arg : arguments) { + request.addArgument(arg); } + + return mWrapped->remoteCommandProcess(request, output); } diff --git a/parameter/AutoLog.h b/parameter/CommandHandlerWrapper.h index 0454514..8794018 100644 --- a/parameter/AutoLog.h +++ b/parameter/CommandHandlerWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,24 +29,18 @@ */ #pragma once -#include "Element.h" +#include "CommandHandlerInterface.h" +#include <RemoteCommandHandler.h> +#include <memory> -#include <string> - -class CAutoLog +class CommandHandlerWrapper : public CommandHandlerInterface { public: - CAutoLog(const CElement* pElement, const std::string& strContext, bool bLogOn = true); - ~CAutoLog(); + CommandHandlerWrapper(std::unique_ptr<IRemoteCommandHandler> &&wrapped); + + bool process(const std::string &command, const std::vector<std::string> &arguments, + std::string &output) override; private: - CAutoLog(const CAutoLog&); - CAutoLog& operator=(const CAutoLog&); - // Logger element - const CElement* _pElement; - // Context - std::string _strContext; - // Log on - bool _bLogOn; + std::unique_ptr<IRemoteCommandHandler> mWrapped; }; - diff --git a/parameter/Component.h b/parameter/Component.h index 4ec1f71..b89ea0b 100644 --- a/parameter/Component.h +++ b/parameter/Component.h @@ -36,14 +36,11 @@ class CComponent : public CInstanceConfigurableElement { public: - CComponent(const std::string& strName, const CTypeElement* pTypeElement) : CInstanceConfigurableElement(strName, pTypeElement) + CComponent(const std::string &strName, const CTypeElement *pTypeElement) + : CInstanceConfigurableElement(strName, pTypeElement) { } // Type - virtual Type getType() const - { - return EComponent; - } + virtual Type getType() const { return EComponent; } }; - diff --git a/parameter/ComponentInstance.cpp b/parameter/ComponentInstance.cpp index f26a383..22fcdcc 100644 --- a/parameter/ComponentInstance.cpp +++ b/parameter/ComponentInstance.cpp @@ -31,17 +31,25 @@ #include "ComponentLibrary.h" #include "ComponentType.h" #include "Component.h" +#include "ParameterBlock.h" // for "array" instantiation #include "XmlParameterSerializingContext.h" #define base CTypeElement -CComponentInstance::CComponentInstance(const std::string& strName) : base(strName), _pComponentType(NULL) +CComponentInstance::CComponentInstance(const std::string &strName) : base(strName) { } std::string CComponentInstance::getKind() const { - return "Component"; + return "ComponentInstance"; +} + +std::string CComponentInstance::getXmlElementName() const +{ + // Once instantiated components are reflected as parameter blocks + // in XML documents + return "ParameterBlock"; } bool CComponentInstance::childrenAreDynamic() const @@ -49,10 +57,12 @@ bool CComponentInstance::childrenAreDynamic() const return true; } -bool CComponentInstance::getMappingData(const std::string& strKey, const std::string*& pStrValue) const +bool CComponentInstance::getMappingData(const std::string &strKey, + const std::string *&pStrValue) const { // Try myself first then associated component type - return base::getMappingData(strKey, pStrValue) || (_pComponentType && _pComponentType->getMappingData(strKey, pStrValue)); + return base::getMappingData(strKey, pStrValue) || + (_pComponentType && _pComponentType->getMappingData(strKey, pStrValue)); } bool CComponentInstance::hasMappingData() const @@ -63,36 +73,35 @@ bool CComponentInstance::hasMappingData() const std::string CComponentInstance::getFormattedMapping() const { - // Try myself first then associated component type - std::string strValue = base::getFormattedMapping(); - if (_pComponentType) { - - strValue += _pComponentType->getFormattedMapping(); - } - - return strValue; + return base::getFormattedMapping(_pComponentType); } -bool CComponentInstance::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CComponentInstance::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Context - CXmlParameterSerializingContext& parameterBuildContext = static_cast<CXmlParameterSerializingContext&>(serializingContext); + CXmlParameterSerializingContext ¶meterBuildContext = + static_cast<CXmlParameterSerializingContext &>(serializingContext); - const CComponentLibrary* pComponentLibrary = parameterBuildContext.getComponentLibrary(); + const CComponentLibrary *pComponentLibrary = parameterBuildContext.getComponentLibrary(); - std::string strComponentType = xmlElement.getAttributeString("Type"); + std::string strComponentType; + xmlElement.getAttribute("Type", strComponentType); _pComponentType = pComponentLibrary->getComponentType(strComponentType); if (!_pComponentType) { - serializingContext.setError("Unable to create Component " + xmlElement.getPath() + ". ComponentType " + strComponentType + " not found!"); + serializingContext.setError("Unable to create Component " + xmlElement.getPath() + + ". ComponentType " + strComponentType + " not found!"); return false; } if (_pComponentType == getParent()) { - serializingContext.setError("Recursive definition of " + _pComponentType->getName() + " due to " + xmlElement.getPath() + " referring to one of its own type."); + serializingContext.setError("Recursive definition of " + _pComponentType->getName() + + " due to " + xmlElement.getPath() + + " referring to one of its own type."); return false; } @@ -100,14 +109,35 @@ bool CComponentInstance::fromXml(const CXmlElement& xmlElement, CXmlSerializingC return base::fromXml(xmlElement, serializingContext); } -CInstanceConfigurableElement* CComponentInstance::doInstantiate() const +CInstanceConfigurableElement *CComponentInstance::doInstantiate() const { - return new CComponent(getName(), this); + if (isScalar()) { + return new CComponent(getName(), this); + } else { + return new CParameterBlock(getName(), this); + } } -void CComponentInstance::populate(CElement* pElement) const +void CComponentInstance::populate(CElement *pElement) const { - base::populate(pElement); + size_t arrayLength = getArrayLength(); - _pComponentType->populate(static_cast<CComponent*>(pElement)); + if (arrayLength != 0) { + + // Create child elements + for (size_t child = 0; child < arrayLength; child++) { + + CComponent *pChildComponent = new CComponent(std::to_string(child), this); + + pElement->addChild(pChildComponent); + + base::populate(pChildComponent); + + _pComponentType->populate(pChildComponent); + } + } else { + base::populate(pElement); + + _pComponentType->populate(static_cast<CComponent *>(pElement)); + } } diff --git a/parameter/ComponentInstance.h b/parameter/ComponentInstance.h index 0c49a54..27af963 100644 --- a/parameter/ComponentInstance.h +++ b/parameter/ComponentInstance.h @@ -38,10 +38,10 @@ class CComponentType; class CComponentInstance : public CTypeElement { public: - CComponentInstance(const std::string& strName); + CComponentInstance(const std::string &strName); // Mapping info - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const; + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const; virtual bool hasMappingData() const; /** * Returns the mapping associated to the current TypeElement instance @@ -51,16 +51,17 @@ public: virtual std::string getFormattedMapping() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // CElement virtual std::string getKind() const; + std::string getXmlElementName() const override; + private: virtual bool childrenAreDynamic() const; - virtual CInstanceConfigurableElement* doInstantiate() const; - virtual void populate(CElement* pElement) const; + virtual CInstanceConfigurableElement *doInstantiate() const; + virtual void populate(CElement *pElement) const; // Related component type - const CComponentType* _pComponentType; + const CComponentType *_pComponentType{nullptr}; }; - diff --git a/parameter/ComponentLibrary.cpp b/parameter/ComponentLibrary.cpp index 1c6daa2..8b27c46 100644 --- a/parameter/ComponentLibrary.cpp +++ b/parameter/ComponentLibrary.cpp @@ -31,10 +31,6 @@ #include "ComponentType.h" #include <assert.h> -CComponentLibrary::CComponentLibrary() -{ -} - bool CComponentLibrary::childrenAreDynamic() const { return true; @@ -45,13 +41,13 @@ std::string CComponentLibrary::getKind() const return "ComponentLibrary"; } -const CComponentType* CComponentLibrary::getComponentType(const std::string& strName) const +const CComponentType *CComponentLibrary::getComponentType(const std::string &strName) const { - return static_cast<const CComponentType*>(findChild(strName)); + return static_cast<const CComponentType *>(findChild(strName)); } -bool CComponentLibrary::fromXml(const CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) +bool CComponentLibrary::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { CXmlElement childElement; @@ -70,7 +66,7 @@ bool CComponentLibrary::fromXml(const CXmlElement& xmlElement, } } else { // Regular child creation and populating - CElement* pChild = createChild(childElement, serializingContext); + CElement *pChild = createChild(childElement, serializingContext); if (!pChild || !pChild->fromXml(childElement, serializingContext)) { @@ -81,4 +77,3 @@ bool CComponentLibrary::fromXml(const CXmlElement& xmlElement, return true; } - diff --git a/parameter/ComponentLibrary.h b/parameter/ComponentLibrary.h index f1445c3..572b062 100644 --- a/parameter/ComponentLibrary.h +++ b/parameter/ComponentLibrary.h @@ -40,14 +40,12 @@ class CComponentType; class CComponentLibrary : public CElement { public: - CComponentLibrary(); - - const CComponentType* getComponentType(const std::string& strName) const; + const CComponentType *getComponentType(const std::string &strName) const; virtual std::string getKind() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); private: virtual bool childrenAreDynamic() const; diff --git a/parameter/ComponentType.cpp b/parameter/ComponentType.cpp index ee71596..76fb211 100644 --- a/parameter/ComponentType.cpp +++ b/parameter/ComponentType.cpp @@ -35,7 +35,7 @@ #define base CTypeElement -CComponentType::CComponentType(const std::string& strName) : base(strName), _pExtendsComponentType(NULL) +CComponentType::CComponentType(const std::string &strName) : base(strName) { } @@ -49,36 +49,33 @@ bool CComponentType::childrenAreDynamic() const return true; } -bool CComponentType::getMappingData(const std::string& strKey, const std::string*& pStrValue) const +bool CComponentType::getMappingData(const std::string &strKey, const std::string *&pStrValue) const { // Try myself first then extended component type - return base::getMappingData(strKey, pStrValue) || (_pExtendsComponentType && _pExtendsComponentType->getMappingData(strKey, pStrValue)); + return base::getMappingData(strKey, pStrValue) || + (_pExtendsComponentType && _pExtendsComponentType->getMappingData(strKey, pStrValue)); } bool CComponentType::hasMappingData() const { // Try myself first then extended component type - return base::hasMappingData() || (_pExtendsComponentType && _pExtendsComponentType->hasMappingData()); + return base::hasMappingData() || + (_pExtendsComponentType && _pExtendsComponentType->hasMappingData()); } std::string CComponentType::getFormattedMapping() const { - // Try myself first then associated component type - std::string strValue = base::getFormattedMapping(); - if (_pExtendsComponentType) { - - strValue += _pExtendsComponentType->getFormattedMapping(); - } - - return strValue; + return base::getFormattedMapping(_pExtendsComponentType); } -bool CComponentType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CComponentType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Context - CXmlParameterSerializingContext& parameterBuildContext = static_cast<CXmlParameterSerializingContext&>(serializingContext); + CXmlParameterSerializingContext ¶meterBuildContext = + static_cast<CXmlParameterSerializingContext &>(serializingContext); - const CComponentLibrary* pComponentLibrary = parameterBuildContext.getComponentLibrary(); + const CComponentLibrary *pComponentLibrary = parameterBuildContext.getComponentLibrary(); // Populate children if (!base::fromXml(xmlElement, serializingContext)) { @@ -89,20 +86,23 @@ bool CComponentType::fromXml(const CXmlElement& xmlElement, CXmlSerializingConte // Check for Extends attribute (extensions will be populated after and not before) if (xmlElement.hasAttribute("Extends")) { - std::string strExtendsType = xmlElement.getAttributeString("Extends"); + std::string strExtendsType; + xmlElement.getAttribute("Extends", strExtendsType); _pExtendsComponentType = pComponentLibrary->getComponentType(strExtendsType); if (!_pExtendsComponentType) { - serializingContext.setError("ComponentType " + strExtendsType + " referred to by " + xmlElement.getPath() + " not found!"); + serializingContext.setError("ComponentType " + strExtendsType + " referred to by " + + xmlElement.getPath() + " not found!"); return false; } if (_pExtendsComponentType == this) { - serializingContext.setError("Recursive ComponentType definition of " + xmlElement.getPath()); + serializingContext.setError("Recursive ComponentType definition of " + + xmlElement.getPath()); return false; } @@ -111,7 +111,7 @@ bool CComponentType::fromXml(const CXmlElement& xmlElement, CXmlSerializingConte return true; } -void CComponentType::populate(CElement* pElement) const +void CComponentType::populate(CElement *pElement) const { // Populate children base::populate(pElement); @@ -124,7 +124,7 @@ void CComponentType::populate(CElement* pElement) const } } -CInstanceConfigurableElement* CComponentType::doInstantiate() const +CInstanceConfigurableElement *CComponentType::doInstantiate() const { // Not supposed to be called directly (instantiation made through CComponentInstance object) assert(0); diff --git a/parameter/ComponentType.h b/parameter/ComponentType.h index 3a34c92..e8c7fff 100644 --- a/parameter/ComponentType.h +++ b/parameter/ComponentType.h @@ -38,13 +38,13 @@ class CInstanceConfigurableElement; class CComponentType : public CTypeElement { public: - CComponentType(const std::string& strName); + CComponentType(const std::string &strName); // Object creation - virtual void populate(CElement* pElement) const; + virtual void populate(CElement *pElement) const; // Mapping info - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const; + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const; virtual bool hasMappingData() const; /** * Returns the mapping associated to the current TypeElement instance @@ -54,15 +54,16 @@ public: virtual std::string getFormattedMapping() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // CElement virtual std::string getKind() const; + private: // CElement virtual bool childrenAreDynamic() const; // Component creation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Ref - const CComponentType* _pExtendsComponentType; + const CComponentType *_pExtendsComponentType{nullptr}; }; diff --git a/parameter/CompoundRule.cpp b/parameter/CompoundRule.cpp index addb31c..e69592b 100644 --- a/parameter/CompoundRule.cpp +++ b/parameter/CompoundRule.cpp @@ -35,14 +35,7 @@ using std::string; // Types -const char* CCompoundRule::_apcTypes[2] = { - "Any", - "All" -}; - -CCompoundRule::CCompoundRule() : _bTypeAll(false) -{ -} +const char *CCompoundRule::_apcTypes[2] = {"Any", "All"}; // Class kind string CCompoundRule::getKind() const @@ -57,26 +50,22 @@ bool CCompoundRule::childrenAreDynamic() const } // Content dumping -void CCompoundRule::logValue(string& strValue, CErrorContext& errorContext) const +string CCompoundRule::logValue(utility::ErrorContext & /*ctx*/) const { - (void)errorContext; - // Type - strValue = _apcTypes[_bTypeAll]; + return _apcTypes[_bTypeAll]; } // Parse -bool CCompoundRule::parse(CRuleParser& ruleParser, string& strError) +bool CCompoundRule::parse(CRuleParser &ruleParser, string &strError) { // Get rule type - uint32_t uiType; - - for (uiType = 0; uiType < 2; uiType++) { + for (size_t typeIndex = 0; typeIndex < 2; typeIndex++) { - if (ruleParser.getType() == _apcTypes[uiType]) { + if (ruleParser.getType() == _apcTypes[typeIndex]) { // Set type - _bTypeAll = uiType != 0; + _bTypeAll = typeIndex != 0; return true; } @@ -90,10 +79,9 @@ bool CCompoundRule::parse(CRuleParser& ruleParser, string& strError) } // Dump -void CCompoundRule::dump(string& strResult) const +string CCompoundRule::dump() const { - strResult += _apcTypes[_bTypeAll]; - strResult += "{"; + string output = string(_apcTypes[_bTypeAll]) + "{"; // Children size_t uiChild; @@ -104,18 +92,19 @@ void CCompoundRule::dump(string& strResult) const if (!bFirst) { - strResult += ", "; + output += ", "; } // Dump inner rule - const CRule* pRule = static_cast<const CRule*>(getChild(uiChild)); + const CRule *pRule = static_cast<const CRule *>(getChild(uiChild)); - pRule->dump(strResult); + output += pRule->dump(); bFirst = false; } - strResult += "}"; + output += "}"; + return output; } // Rule check @@ -126,7 +115,7 @@ bool CCompoundRule::matches() const for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CRule* pRule = static_cast<const CRule*>(getChild(uiChild)); + const CRule *pRule = static_cast<const CRule *>(getChild(uiChild)); if (pRule->matches() ^ _bTypeAll) { @@ -137,20 +126,23 @@ bool CCompoundRule::matches() const } // From IXmlSink -bool CCompoundRule::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CCompoundRule::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Get type - _bTypeAll = xmlElement.getAttributeBoolean("Type", _apcTypes[true]); + string strType; + xmlElement.getAttribute("Type", strType); + _bTypeAll = strType == _apcTypes[true]; // Base return base::fromXml(xmlElement, serializingContext); } // From IXmlSource -void CCompoundRule::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CCompoundRule::toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const { // Set type - xmlElement.setAttributeString("Type", _apcTypes[_bTypeAll]); + xmlElement.setAttribute("Type", _apcTypes[_bTypeAll]); // Base base::toXml(xmlElement, serializingContext); diff --git a/parameter/CompoundRule.h b/parameter/CompoundRule.h index 5cac53b..712ff70 100644 --- a/parameter/CompoundRule.h +++ b/parameter/CompoundRule.h @@ -36,35 +36,34 @@ class CCompoundRule : public CRule { public: - CCompoundRule(); - // Parse - virtual bool parse(CRuleParser& ruleParser, std::string& strError); + virtual bool parse(CRuleParser &ruleParser, std::string &strError); // Dump - virtual void dump(std::string& strResult) const; + std::string dump() const override; // Rule check virtual bool matches() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // Class kind virtual std::string getKind() const; -protected: - // Content dumping - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + private: + // Content dumping + std::string logValue(utility::ErrorContext &errorContext) const override; + // Returns true if children dynamic creation is to be dealt with virtual bool childrenAreDynamic() const; // Type - bool _bTypeAll; + bool _bTypeAll{false}; // Types - static const char* _apcTypes[]; + static const char *_apcTypes[]; }; diff --git a/parameter/ConfigurableDomain.cpp b/parameter/ConfigurableDomain.cpp index 346b1f9..2a74307 100644 --- a/parameter/ConfigurableDomain.cpp +++ b/parameter/ConfigurableDomain.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -34,18 +34,15 @@ #include "XmlDomainSerializingContext.h" #include "XmlDomainImportContext.h" #include "XmlDomainExportContext.h" -#include <assert.h> +#include "Utility.h" +#include "AlwaysAssert.hpp" +#include <cassert> -#define base CBinarySerializableElement +#define base CElement using std::string; -CConfigurableDomain::CConfigurableDomain() : - _bSequenceAware(false), _pLastAppliedConfiguration(NULL) -{ -} - -CConfigurableDomain::CConfigurableDomain(const string& strName) : base(strName), _bSequenceAware(false), _pLastAppliedConfiguration(NULL) +CConfigurableDomain::CConfigurableDomain(const string &strName) : base(strName) { } @@ -56,7 +53,7 @@ CConfigurableDomain::~CConfigurableDomain() for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - CConfigurableElement* pConfigurableElement = *it; + CConfigurableElement *pConfigurableElement = *it; // Remove from configurable element pConfigurableElement->removeAttachedConfigurableDomain(this); @@ -65,7 +62,8 @@ CConfigurableDomain::~CConfigurableDomain() // Remove all associated syncer sets ConfigurableElementToSyncerSetMapIterator mapIt; - for (mapIt = _configurableElementToSyncerSetMap.begin(); mapIt != _configurableElementToSyncerSetMap.end(); ++mapIt) { + for (mapIt = _configurableElementToSyncerSetMap.begin(); + mapIt != _configurableElementToSyncerSetMap.end(); ++mapIt) { delete mapIt->second; } @@ -82,21 +80,16 @@ bool CConfigurableDomain::childrenAreDynamic() const } // Content dumping -void CConfigurableDomain::logValue(string& strValue, CErrorContext& errorContext) const +string CConfigurableDomain::logValue(utility::ErrorContext & /*ctx*/) const { - (void)errorContext; + return string("{") + - strValue = "{"; - - // Sequence awareness - strValue += "Sequence aware: "; - strValue += _bSequenceAware ? "yes" : "no"; + "Sequence aware: " + (_bSequenceAware ? "yes" : "no") + - // Last applied configuration - strValue += ", Last applied configuration: "; - strValue += _pLastAppliedConfiguration ? _pLastAppliedConfiguration->getName() : "<none>"; + ", Last applied configuration: " + + (_pLastAppliedConfiguration ? _pLastAppliedConfiguration->getName() : "<none>") + - strValue += "}"; + "}"; } // Sequence awareness @@ -104,8 +97,6 @@ void CConfigurableDomain::setSequenceAwareness(bool bSequenceAware) { if (_bSequenceAware != bSequenceAware) { - log_info("Making domain \"%s\" sequence %s", getName().c_str(), bSequenceAware ? "aware" : "unaware"); - _bSequenceAware = bSequenceAware; } } @@ -116,16 +107,17 @@ bool CConfigurableDomain::getSequenceAwareness() const } // From IXmlSource -void CConfigurableDomain::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CConfigurableDomain::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { base::toXml(xmlElement, serializingContext); // Sequence awareness - xmlElement.setAttributeBoolean("SequenceAware", _bSequenceAware); + xmlElement.setAttribute("SequenceAware", _bSequenceAware); } -void CConfigurableDomain::childrenToXml(CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) const +void CConfigurableDomain::childrenToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Configurations composeDomainConfigurations(xmlElement, serializingContext); @@ -134,11 +126,12 @@ void CConfigurableDomain::childrenToXml(CXmlElement& xmlElement, composeConfigurableElements(xmlElement); // Settings - composeSettings(xmlElement, serializingContext); + composeSettings(xmlElement, static_cast<CXmlDomainExportContext &>(serializingContext)); } // XML composing -void CConfigurableDomain::composeDomainConfigurations(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CConfigurableDomain::composeDomainConfigurations( + CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const { // Create Configurations element CXmlElement xmlConfigurationsElement; @@ -149,7 +142,7 @@ void CConfigurableDomain::composeDomainConfigurations(CXmlElement& xmlElement, C base::childrenToXml(xmlConfigurationsElement, serializingContext); } -void CConfigurableDomain::composeConfigurableElements(CXmlElement& xmlElement) const +void CConfigurableDomain::composeConfigurableElements(CXmlElement &xmlElement) const { // Create ConfigurableElements element CXmlElement xmlConfigurableElementsElement; @@ -161,25 +154,23 @@ void CConfigurableDomain::composeConfigurableElements(CXmlElement& xmlElement) c for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; // Create corresponding XML child element CXmlElement xmlChildConfigurableElement; - xmlConfigurableElementsElement.createChild(xmlChildConfigurableElement, "ConfigurableElement"); + xmlConfigurableElementsElement.createChild(xmlChildConfigurableElement, + "ConfigurableElement"); // Set Path attribute - xmlChildConfigurableElement.setAttributeString("Path", pConfigurableElement->getPath()); + xmlChildConfigurableElement.setAttribute("Path", pConfigurableElement->getPath()); } } -void CConfigurableDomain::composeSettings(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CConfigurableDomain::composeSettings(CXmlElement &xmlElement, + CXmlDomainExportContext &context) const { - // Context - const CXmlDomainExportContext& xmlDomainExportContext = - static_cast<const CXmlDomainExportContext&>(serializingContext); - - if (!xmlDomainExportContext.withSettings()) { + if (!context.withSettings()) { return; } @@ -193,34 +184,40 @@ void CConfigurableDomain::composeSettings(CXmlElement& xmlElement, CXmlSerializi size_t uiNbConfigurations = getNbChildren(); size_t uiChildConfiguration; - for (uiChildConfiguration = 0; uiChildConfiguration < uiNbConfigurations; uiChildConfiguration++) { + for (uiChildConfiguration = 0; uiChildConfiguration < uiNbConfigurations; + uiChildConfiguration++) { - const CDomainConfiguration* pDomainConfiguration = static_cast<const CDomainConfiguration*>(getChild(uiChildConfiguration)); + const CDomainConfiguration *pDomainConfiguration = + static_cast<const CDomainConfiguration *>(getChild(uiChildConfiguration)); // Create child xml element for that configuration CXmlElement xmlConfigurationSettingsElement; - xmlSettingsElement.createChild(xmlConfigurationSettingsElement, pDomainConfiguration->getKind()); + xmlSettingsElement.createChild(xmlConfigurationSettingsElement, + pDomainConfiguration->getXmlElementName()); // Set its name attribute xmlConfigurationSettingsElement.setNameAttribute(pDomainConfiguration->getName()); // Serialize out configuration settings - pDomainConfiguration->composeSettings(xmlConfigurationSettingsElement, serializingContext); + pDomainConfiguration->composeSettings(xmlConfigurationSettingsElement, context); } } // From IXmlSink -bool CConfigurableDomain::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CConfigurableDomain::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Context - CXmlDomainImportContext& xmlDomainImportContext = - static_cast<CXmlDomainImportContext&>(serializingContext); + CXmlDomainImportContext &xmlDomainImportContext = + static_cast<CXmlDomainImportContext &>(serializingContext); // Sequence awareness (optional) - _bSequenceAware = xmlElement.hasAttribute("SequenceAware") && xmlElement.getAttributeBoolean("SequenceAware"); + xmlElement.getAttribute("SequenceAware", _bSequenceAware); - setName(xmlElement.getAttributeString("Name")); + std::string name; + xmlElement.getAttribute("Name", name); + setName(name); // Local parsing. Do not dig if (!parseDomainConfigurations(xmlElement, xmlDomainImportContext) || @@ -231,7 +228,8 @@ bool CConfigurableDomain::fromXml(const CXmlElement& xmlElement, CXmlSerializing } // All provided configurations are parsed - // Attempt validation on areas of non provided configurations for all configurable elements if required + // Attempt validation on areas of non provided configurations for all configurable elements if + // required if (xmlDomainImportContext.autoValidationRequired()) { autoValidateAll(); @@ -241,8 +239,8 @@ bool CConfigurableDomain::fromXml(const CXmlElement& xmlElement, CXmlSerializing } // XML parsing -bool CConfigurableDomain::parseDomainConfigurations(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext) +bool CConfigurableDomain::parseDomainConfigurations(const CXmlElement &xmlElement, + CXmlDomainImportContext &serializingContext) { // We're supposedly clean assert(_configurableElementList.empty()); @@ -257,10 +255,10 @@ bool CConfigurableDomain::parseDomainConfigurations(const CXmlElement& xmlElemen } // Parse configurable elements -bool CConfigurableDomain::parseConfigurableElements(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext) +bool CConfigurableDomain::parseConfigurableElements(const CXmlElement &xmlElement, + CXmlDomainImportContext &serializingContext) { - CSystemClass& systemClass = serializingContext.getSystemClass(); + CSystemClass &systemClass = serializingContext.getSystemClass(); // Get ConfigurableElements element CXmlElement xmlConfigurableElementsElement; @@ -274,7 +272,8 @@ bool CConfigurableDomain::parseConfigurableElements(const CXmlElement& xmlElemen while (it.next(xmlConfigurableElementElement)) { // Locate configurable element - string strConfigurableElementPath = xmlConfigurableElementElement.getAttributeString("Path"); + string strConfigurableElementPath; + xmlConfigurableElementElement.getAttribute("Path", strConfigurableElementPath); CPathNavigator pathNavigator(strConfigurableElementPath); string strError; @@ -282,23 +281,29 @@ bool CConfigurableDomain::parseConfigurableElements(const CXmlElement& xmlElemen // Is there an element and does it match system class name? if (!pathNavigator.navigateThrough(systemClass.getName(), strError)) { - serializingContext.setError("Could not find configurable element of path " + strConfigurableElementPath + " from ConfigurableDomain description " + getName() + " (" + strError + ")"); + serializingContext.setError( + "Could not find configurable element of path " + strConfigurableElementPath + + " from ConfigurableDomain description " + getName() + " (" + strError + ")"); return false; } // Browse system class for configurable element - CConfigurableElement* pConfigurableElement = - static_cast<CConfigurableElement*>(systemClass.findDescendant(pathNavigator)); + CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(systemClass.findDescendant(pathNavigator)); if (!pConfigurableElement) { - serializingContext.setError("Could not find configurable element of path " + strConfigurableElementPath + " from ConfigurableDomain description " + getName()); + serializingContext.setError("Could not find configurable element of path " + + strConfigurableElementPath + + " from ConfigurableDomain description " + getName()); return false; } // Add found element to domain - if (!addConfigurableElement(pConfigurableElement, NULL, strError)) { + core::Results infos; + if (!addConfigurableElement(pConfigurableElement, NULL, infos)) { + strError = utility::asString(infos); serializingContext.setError(strError); return false; @@ -309,8 +314,8 @@ bool CConfigurableDomain::parseConfigurableElements(const CXmlElement& xmlElemen } // Parse settings -bool CConfigurableDomain::parseSettings(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext) +bool CConfigurableDomain::parseSettings(const CXmlElement &xmlElement, + CXmlDomainImportContext &serializingContext) { // Check we actually need to parse configuration settings if (!serializingContext.withSettings()) { @@ -334,12 +339,14 @@ bool CConfigurableDomain::parseSettings(const CXmlElement& xmlElement, while (it.next(xmlConfigurationSettingsElement)) { // Get domain configuration - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(findChild(xmlConfigurationSettingsElement.getNameAttribute())); + CDomainConfiguration *pDomainConfiguration = static_cast<CDomainConfiguration *>( + findChild(xmlConfigurationSettingsElement.getNameAttribute())); if (!pDomainConfiguration) { serializingContext.setError("Could not find domain configuration referred to by" - " configurable domain \"" + getName() + "\"."); + " configurable domain \"" + + getName() + "\"."); return false; } @@ -354,12 +361,15 @@ bool CConfigurableDomain::parseSettings(const CXmlElement& xmlElement, return true; } // Configurable elements association -bool CConfigurableDomain::addConfigurableElement(CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomain::addConfigurableElement(CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard, + core::Results &infos) { // Already associated? if (containsConfigurableElement(pConfigurableElement)) { - strError = "Configurable element " + pConfigurableElement->getPath() + " already associated to configuration domain " + getName(); + infos.push_back("Configurable element " + pConfigurableElement->getPath() + + " already associated to configuration domain " + getName()); return false; } @@ -367,27 +377,29 @@ bool CConfigurableDomain::addConfigurableElement(CConfigurableElement* pConfigur // Already owned? if (pConfigurableElement->belongsTo(this)) { - strError = "Configurable element " + pConfigurableElement->getPath() + " already owned by configuration domain " + getName(); + infos.push_back("Configurable element " + pConfigurableElement->getPath() + + " already owned by configuration domain " + getName()); return false; } // Do add - doAddConfigurableElement(pConfigurableElement, pMainBlackboard); + doAddConfigurableElement(pConfigurableElement, infos, pMainBlackboard); return true; } -bool CConfigurableDomain::removeConfigurableElement(CConfigurableElement* pConfigurableElement, string& strError) +bool CConfigurableDomain::removeConfigurableElement(CConfigurableElement *pConfigurableElement, + string &strError) { // Not associated? if (!containsConfigurableElement(pConfigurableElement)) { - strError = "Configurable element " + pConfigurableElement->getPath() + " not associated to configuration domain " + getName(); + strError = "Configurable element " + pConfigurableElement->getPath() + + " not associated to configuration domain " + getName(); return false; } - log_info("Removing configurable element \"%s\" from domain \"%s\"", pConfigurableElement->getPath().c_str(), getName().c_str()); // Do remove doRemoveConfigurableElement(pConfigurableElement, true); @@ -407,21 +419,21 @@ bool CConfigurableDomain::removeConfigurableElement(CConfigurableElement* pConfi * @param[in] strConfiguration Name of the Configuration. * @param[in] pCandidateDescendantConfigurableElement Pointer to a CConfigurableElement that * belongs to the Domain. -* @param[out] uiBaseOffset The base offset of the CConfigurableElement. +* @param[out] baseOffset The base offset of the CConfigurableElement. * @param[out] bIsLastApplied Boolean indicating that the Configuration is * the last one applied of the Domain. * @param[out] strError Error message * * return Pointer to the Blackboard of the Configuration. */ -CParameterBlackboard* CConfigurableDomain::findConfigurationBlackboard(const string& strConfiguration, - const CConfigurableElement* pCandidateDescendantConfigurableElement, - uint32_t& uiBaseOffset, - bool& bIsLastApplied, - string& strError) const +CParameterBlackboard *CConfigurableDomain::findConfigurationBlackboard( + const string &strConfiguration, + const CConfigurableElement *pCandidateDescendantConfigurableElement, size_t &baseOffset, + bool &bIsLastApplied, string &strError) const { // Find Configuration - const CDomainConfiguration* pDomainConfiguration = static_cast<const CDomainConfiguration*>(findChild(strConfiguration)); + const CDomainConfiguration *pDomainConfiguration = + static_cast<const CDomainConfiguration *>(findChild(strConfiguration)); if (!pDomainConfiguration) { @@ -435,13 +447,14 @@ CParameterBlackboard* CConfigurableDomain::findConfigurationBlackboard(const str for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - const CConfigurableElement* pAssociatedConfigurableElement = *it; + const CConfigurableElement *pAssociatedConfigurableElement = *it; // Check if the the associated element is the configurable element or one of its ancestors if ((pCandidateDescendantConfigurableElement == pAssociatedConfigurableElement) || - (pCandidateDescendantConfigurableElement->isDescendantOf(pAssociatedConfigurableElement))) { + (pCandidateDescendantConfigurableElement->isDescendantOf( + pAssociatedConfigurableElement))) { - uiBaseOffset = pAssociatedConfigurableElement->getOffset(); + baseOffset = pAssociatedConfigurableElement->getOffset(); bIsLastApplied = (pDomainConfiguration == _pLastAppliedConfiguration); return pDomainConfiguration->getBlackboard(pAssociatedConfigurableElement); @@ -454,62 +467,69 @@ CParameterBlackboard* CConfigurableDomain::findConfigurationBlackboard(const str } // Domain splitting -bool CConfigurableDomain::split(CConfigurableElement* pConfigurableElement, string& strError) +bool CConfigurableDomain::split(CConfigurableElement *pConfigurableElement, core::Results &infos) { // Not associated? if (!containsConfigurableElement(pConfigurableElement)) { - strError = "Configurable element " + pConfigurableElement->getPath() + " not associated to configuration domain " + getName(); + std::string strError = "Configurable element " + pConfigurableElement->getPath() + + " not associated to configuration domain " + getName(); + infos.push_back(strError); return false; } - log_info("Splitting configurable element \"%s\" domain \"%s\"", pConfigurableElement->getPath().c_str(), getName().c_str()); // Create sub domain areas for all configurable element's children size_t uiNbConfigurableElementChildren = pConfigurableElement->getNbChildren(); if (!uiNbConfigurableElementChildren) { - strError = "Configurable element " + pConfigurableElement->getPath() + " has no children to split configurable domain to"; + std::string strError = "Configurable element " + pConfigurableElement->getPath() + + " has no children to split configurable domain to"; + infos.push_back(strError); return false; } - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbConfigurableElementChildren; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurableElementChildren; uiChild++) { - CConfigurableElement* pChildConfigurableElement = static_cast<CConfigurableElement*>(pConfigurableElement->getChild(uiChild)); + CConfigurableElement *pChildConfigurableElement = + static_cast<CConfigurableElement *>(pConfigurableElement->getChild(uiChild)); - doAddConfigurableElement(pChildConfigurableElement); + doAddConfigurableElement(pChildConfigurableElement, infos); } // Delegate to configurations size_t uiNbConfigurations = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); pDomainConfiguration->split(pConfigurableElement); } // Remove given configurable element from this domain - // Note: we shouldn't need to recompute the sync set in that case, as the splitted element should include the syncers of its children elements + // Note: we shouldn't need to recompute the sync set in that case, as the splitted element + // should include the syncers of its children elements doRemoveConfigurableElement(pConfigurableElement, false); return true; } -// Check if there is a pending configuration for this domain: i.e. an applicable configuration different from the last applied configuration -const CDomainConfiguration* CConfigurableDomain::getPendingConfiguration() const +// Check if there is a pending configuration for this domain: i.e. an applicable configuration +// different from the last applied configuration +const CDomainConfiguration *CConfigurableDomain::getPendingConfiguration() const { - const CDomainConfiguration* pApplicableDomainConfiguration = findApplicableDomainConfiguration(); + const CDomainConfiguration *pApplicableDomainConfiguration = + findApplicableDomainConfiguration(); if (pApplicableDomainConfiguration) { // Check not the last one before applying - if (!_pLastAppliedConfiguration || (_pLastAppliedConfiguration != pApplicableDomainConfiguration)) { + if (!_pLastAppliedConfiguration || + (_pLastAppliedConfiguration != pApplicableDomainConfiguration)) { return pApplicableDomainConfiguration; } @@ -519,11 +539,12 @@ const CDomainConfiguration* CConfigurableDomain::getPendingConfiguration() const } // Configuration application if required -void CConfigurableDomain::apply(CParameterBlackboard* pParameterBlackboard, CSyncerSet* pSyncerSet, bool bForce) const +void CConfigurableDomain::apply(CParameterBlackboard *pParameterBlackboard, CSyncerSet *pSyncerSet, + bool bForce, std::string &strInfo) const { // Apply configuration only if the blackboard will // be synchronized either now or by syncerSet. - if(!pSyncerSet ^ _bSequenceAware) { + if (!pSyncerSet ^ _bSequenceAware) { // The configuration can not be syncronised return; } @@ -532,16 +553,17 @@ void CConfigurableDomain::apply(CParameterBlackboard* pParameterBlackboard, CSyn // Force a configuration restore by forgetting about last applied configuration _pLastAppliedConfiguration = NULL; } - const CDomainConfiguration* pApplicableDomainConfiguration = findApplicableDomainConfiguration(); + const CDomainConfiguration *pApplicableDomainConfiguration = + findApplicableDomainConfiguration(); if (pApplicableDomainConfiguration) { // Check not the last one before applying - if (!_pLastAppliedConfiguration || _pLastAppliedConfiguration != pApplicableDomainConfiguration) { + if (!_pLastAppliedConfiguration || + _pLastAppliedConfiguration != pApplicableDomainConfiguration) { - log_info("Applying configuration \"%s\" from domain \"%s\"", - pApplicableDomainConfiguration->getName().c_str(), - getName().c_str()); + strInfo = "Applying configuration '" + pApplicableDomainConfiguration->getName() + + "' from domain '" + getName() + "'"; // Check if we need to synchronize during restore bool bSync = !pSyncerSet && _bSequenceAware; @@ -563,11 +585,14 @@ void CConfigurableDomain::apply(CParameterBlackboard* pParameterBlackboard, CSyn } // Return applicable configuration validity for given configurable element -bool CConfigurableDomain::isApplicableConfigurationValid(const CConfigurableElement* pConfigurableElement) const +bool CConfigurableDomain::isApplicableConfigurationValid( + const CConfigurableElement *pConfigurableElement) const { - const CDomainConfiguration* pApplicableDomainConfiguration = findApplicableDomainConfiguration(); + const CDomainConfiguration *pApplicableDomainConfiguration = + findApplicableDomainConfiguration(); - return pApplicableDomainConfiguration && pApplicableDomainConfiguration->isValid(pConfigurableElement); + return pApplicableDomainConfiguration && + pApplicableDomainConfiguration->isValid(pConfigurableElement); } // In case configurable element was removed @@ -579,16 +604,19 @@ void CConfigurableDomain::computeSyncSet() // Add syncer sets for all associated configurable elements ConfigurableElementToSyncerSetMapIterator mapIt; - for (mapIt = _configurableElementToSyncerSetMap.begin(); mapIt != _configurableElementToSyncerSetMap.end(); ++mapIt) { + for (mapIt = _configurableElementToSyncerSetMap.begin(); + mapIt != _configurableElementToSyncerSetMap.end(); ++mapIt) { - const CSyncerSet* pSyncerSet = mapIt->second; + const CSyncerSet *pSyncerSet = mapIt->second; _syncerSet += *pSyncerSet; } } // Configuration Management -bool CConfigurableDomain::createConfiguration(const string& strName, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomain::createConfiguration(const string &strName, + const CParameterBlackboard *pMainBlackboard, + string &strError) { // Already exists? if (findChild(strName)) { @@ -597,20 +625,20 @@ bool CConfigurableDomain::createConfiguration(const string& strName, const CPara return false; } - log_info("Creating domain configuration \"%s\" into domain \"%s\"", strName.c_str(), getName().c_str()); // Creation - CDomainConfiguration* pDomainConfiguration = new CDomainConfiguration(strName); + CDomainConfiguration *pDomainConfiguration = new CDomainConfiguration(strName); // Configurable elements association ConfigurableElementListIterator it; for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it;; + const CConfigurableElement *pConfigurableElement = *it; + ; // Retrieve associated syncer set - CSyncerSet* pSyncerSet = getSyncerSet(pConfigurableElement); + CSyncerSet *pSyncerSet = getSyncerSet(pConfigurableElement); // Associate to configuration pDomainConfiguration->addConfigurableElement(pConfigurableElement, pSyncerSet); @@ -623,24 +651,23 @@ bool CConfigurableDomain::createConfiguration(const string& strName, const CPara // Attempt auto validation, so that the user gets his/her own settings by defaults if (!autoValidateConfiguration(pDomainConfiguration)) { - // No valid configuration found to copy in from, validate againt main blackboard (will concerned remaining invalid parts) + // No valid configuration found to copy in from, validate againt main blackboard (will + // concerned remaining invalid parts) pDomainConfiguration->validate(pMainBlackboard); } return true; } -bool CConfigurableDomain::deleteConfiguration(const string& strName, string& strError) +bool CConfigurableDomain::deleteConfiguration(const string &strName, string &strError) { - CDomainConfiguration* pDomainConfiguration = findConfiguration(strName, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strName, strError); if (!pDomainConfiguration) { return false; } - log_info("Deleting configuration \"%s\" from domain \"%s\"", strName.c_str(), getName().c_str()); - // Was the last applied? if (pDomainConfiguration == _pLastAppliedConfiguration) { @@ -657,72 +684,72 @@ bool CConfigurableDomain::deleteConfiguration(const string& strName, string& str return true; } -void CConfigurableDomain::listAssociatedToElements(string& strResult) const +void CConfigurableDomain::listAssociatedToElements(string &strResult) const { - strResult = "\n"; - ConfigurableElementListIterator it; // Browse all configurable elements for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; strResult += pConfigurableElement->getPath() + "\n"; } } -bool CConfigurableDomain::renameConfiguration(const string& strName, const string& strNewName, string& strError) +bool CConfigurableDomain::renameConfiguration(const string &strName, const string &strNewName, + string &strError) { - CDomainConfiguration* pDomainConfiguration = findConfiguration(strName, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strName, strError); if (!pDomainConfiguration) { return false; } - log_info("Renaming domain \"%s\"'s configuration \"%s\" to \"%s\"", getName().c_str(), strName.c_str(), strNewName.c_str()); // Rename return pDomainConfiguration->rename(strNewName, strError); } -bool CConfigurableDomain::restoreConfiguration(const string& strName, CParameterBlackboard* pMainBlackboard, bool bAutoSync, std::list<string>& lstrError) const +bool CConfigurableDomain::restoreConfiguration(const string &configurationName, + CParameterBlackboard *mainBlackboard, bool autoSync, + core::Results &errors) const { - string strError; + string error; - const CDomainConfiguration* pDomainConfiguration = findConfiguration(strName, strError); + const CDomainConfiguration *configuration = findConfiguration(configurationName, error); - if (!pDomainConfiguration) { + if (configuration == NULL) { - lstrError.push_back(strError); + errors.push_back(error); return false; } - log_info("Restoring domain \"%s\"'s configuration \"%s\" to parameter blackboard", getName().c_str(), pDomainConfiguration->getName().c_str()); // Delegate - bool bSuccess = pDomainConfiguration->restore(pMainBlackboard, bAutoSync && _bSequenceAware, &lstrError); + bool bSuccess = configuration->restore(mainBlackboard, autoSync && _bSequenceAware, &errors); // Record last applied configuration - _pLastAppliedConfiguration = pDomainConfiguration; + _pLastAppliedConfiguration = configuration; // Synchronize - if (bAutoSync && !_bSequenceAware) { + if (autoSync && !_bSequenceAware) { - bSuccess &= _syncerSet.sync(*pMainBlackboard, false, &lstrError); + bSuccess &= _syncerSet.sync(*mainBlackboard, false, &errors); } return bSuccess; } -bool CConfigurableDomain::saveConfiguration(const string& strName, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomain::saveConfiguration(const string &strName, + const CParameterBlackboard *pMainBlackboard, + string &strError) { // Find Domain configuration - CDomainConfiguration* pDomainConfiguration = findConfiguration(strName, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strName, strError); if (!pDomainConfiguration) { return false; } - log_info("Saving domain \"%s\"'s configuration \"%s\" from parameter blackboard", getName().c_str(), pDomainConfiguration->getName().c_str()); // Delegate pDomainConfiguration->save(pMainBlackboard); @@ -730,10 +757,12 @@ bool CConfigurableDomain::saveConfiguration(const string& strName, const CParame return true; } -bool CConfigurableDomain::setElementSequence(const string& strConfiguration, const std::vector<string>& astrNewElementSequence, string& strError) +bool CConfigurableDomain::setElementSequence(const string &strConfiguration, + const std::vector<string> &astrNewElementSequence, + string &strError) { // Find Domain configuration - CDomainConfiguration* pDomainConfiguration = findConfiguration(strConfiguration, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strConfiguration, strError); if (!pDomainConfiguration) { @@ -744,10 +773,12 @@ bool CConfigurableDomain::setElementSequence(const string& strConfiguration, con return pDomainConfiguration->setElementSequence(astrNewElementSequence, strError); } -bool CConfigurableDomain::getElementSequence(const string& strConfiguration, string& strResult) const +bool CConfigurableDomain::getElementSequence(const string &strConfiguration, + string &strResult) const { // Find Domain configuration - const CDomainConfiguration* pDomainConfiguration = findConfiguration(strConfiguration, strResult); + const CDomainConfiguration *pDomainConfiguration = + findConfiguration(strConfiguration, strResult); if (!pDomainConfiguration) { @@ -760,10 +791,12 @@ bool CConfigurableDomain::getElementSequence(const string& strConfiguration, str return true; } -bool CConfigurableDomain::setApplicationRule(const string& strConfiguration, const string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, string& strError) +bool CConfigurableDomain::setApplicationRule( + const string &strConfiguration, const string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, string &strError) { // Find Domain configuration - CDomainConfiguration* pDomainConfiguration = findConfiguration(strConfiguration, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strConfiguration, strError); if (!pDomainConfiguration) { @@ -771,13 +804,14 @@ bool CConfigurableDomain::setApplicationRule(const string& strConfiguration, con } // Delegate to configuration - return pDomainConfiguration->setApplicationRule(strApplicationRule, pSelectionCriteriaDefinition, strError); + return pDomainConfiguration->setApplicationRule(strApplicationRule, + pSelectionCriteriaDefinition, strError); } -bool CConfigurableDomain::clearApplicationRule(const string& strConfiguration, string& strError) +bool CConfigurableDomain::clearApplicationRule(const string &strConfiguration, string &strError) { // Find Domain configuration - CDomainConfiguration* pDomainConfiguration = findConfiguration(strConfiguration, strError); + CDomainConfiguration *pDomainConfiguration = findConfiguration(strConfiguration, strError); if (!pDomainConfiguration) { @@ -790,10 +824,12 @@ bool CConfigurableDomain::clearApplicationRule(const string& strConfiguration, s return true; } -bool CConfigurableDomain::getApplicationRule(const string& strConfiguration, string& strResult) const +bool CConfigurableDomain::getApplicationRule(const string &strConfiguration, + string &strResult) const { // Find Domain configuration - const CDomainConfiguration* pDomainConfiguration = findConfiguration(strConfiguration, strResult); + const CDomainConfiguration *pDomainConfiguration = + findConfiguration(strConfiguration, strResult); if (!pDomainConfiguration) { @@ -801,7 +837,7 @@ bool CConfigurableDomain::getApplicationRule(const string& strConfiguration, str } // Delegate to configuration - pDomainConfiguration->getApplicationRule(strResult); + strResult = pDomainConfiguration->getApplicationRule(); return true; } @@ -819,49 +855,61 @@ string CConfigurableDomain::getLastAppliedConfigurationName() const // Pending configuration string CConfigurableDomain::getPendingConfigurationName() const { - const CDomainConfiguration* pPendingConfiguration = getPendingConfiguration(); + const CDomainConfiguration *pApplicableDomainConfiguration = + findApplicableDomainConfiguration(); - if (pPendingConfiguration) { + if (!pApplicableDomainConfiguration) { - return pPendingConfiguration->getName(); + // No configuration is pending + return "<none>"; + } + + // Check it will be applied + if (pApplicableDomainConfiguration != _pLastAppliedConfiguration) { + + // Found config will get applied + return pApplicableDomainConfiguration->getName(); + } else { + + // Same configuration as current + return ""; } - return "<none>"; } // Ensure validity on whole domain from main blackboard -void CConfigurableDomain::validate(const CParameterBlackboard* pMainBlackboard) +void CConfigurableDomain::validate(const CParameterBlackboard *pMainBlackboard) { // Propagate size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); pDomainConfiguration->validate(pMainBlackboard); } } // Ensure validity on areas related to configurable element -void CConfigurableDomain::validateAreas(const CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard) +void CConfigurableDomain::validateAreas(const CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard) { - log_info("Validating domain \"%s\" against main blackboard for configurable element \"%s\"", getName().c_str(), pConfigurableElement->getPath().c_str()); - // Propagate size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); pDomainConfiguration->validate(pConfigurableElement, pMainBlackboard); } } -// Attempt validation for all configurable element's areas, relying on already existing valid configuration inside domain +// Attempt validation for all configurable element's areas, relying on already existing valid +// configuration inside domain void CConfigurableDomain::autoValidateAll() { // Validate @@ -870,18 +918,20 @@ void CConfigurableDomain::autoValidateAll() // Browse all configurable elements for configuration validation for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; // Auto validate element autoValidateAreas(pConfigurableElement); } } -// Attempt validation for configurable element's areas, relying on already existing valid configuration inside domain -void CConfigurableDomain::autoValidateAreas(const CConfigurableElement* pConfigurableElement) +// Attempt validation for configurable element's areas, relying on already existing valid +// configuration inside domain +void CConfigurableDomain::autoValidateAreas(const CConfigurableElement *pConfigurableElement) { // Find first valid configuration for given configurable element - const CDomainConfiguration* pValidDomainConfiguration = findValidDomainConfiguration(pConfigurableElement); + const CDomainConfiguration *pValidDomainConfiguration = + findValidDomainConfiguration(pConfigurableElement); // No valid configuration found, give up if (!pValidDomainConfiguration) { @@ -891,29 +941,31 @@ void CConfigurableDomain::autoValidateAreas(const CConfigurableElement* pConfigu // Validate all other configurations against found one, if any size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); - if (pDomainConfiguration != pValidDomainConfiguration && !pDomainConfiguration->isValid(pConfigurableElement)) { + if (pDomainConfiguration != pValidDomainConfiguration && + !pDomainConfiguration->isValid(pConfigurableElement)) { // Validate pDomainConfiguration->validateAgainst(pValidDomainConfiguration, pConfigurableElement); } } } -// Attempt configuration validation for all configurable elements' areas, relying on already existing valid configuration inside domain -bool CConfigurableDomain::autoValidateConfiguration(CDomainConfiguration* pDomainConfiguration) +// Attempt configuration validation for all configurable elements' areas, relying on already +// existing valid configuration inside domain +bool CConfigurableDomain::autoValidateConfiguration(CDomainConfiguration *pDomainConfiguration) { // Find another configuration than this one, that ought to be valid! size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - const CDomainConfiguration* pPotententialValidDomainConfiguration = static_cast<const CDomainConfiguration*>(getChild(uiChild)); + const CDomainConfiguration *pPotententialValidDomainConfiguration = + static_cast<const CDomainConfiguration *>(getChild(uiChild)); if (pPotententialValidDomainConfiguration != pDomainConfiguration) { @@ -927,14 +979,15 @@ bool CConfigurableDomain::autoValidateConfiguration(CDomainConfiguration* pDomai } // Search for a valid configuration for given configurable element -const CDomainConfiguration* CConfigurableDomain::findValidDomainConfiguration(const CConfigurableElement* pConfigurableElement) const +const CDomainConfiguration *CConfigurableDomain::findValidDomainConfiguration( + const CConfigurableElement *pConfigurableElement) const { size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - const CDomainConfiguration* pDomainConfiguration = static_cast<const CDomainConfiguration*>(getChild(uiChild)); + const CDomainConfiguration *pDomainConfiguration = + static_cast<const CDomainConfiguration *>(getChild(uiChild)); if (pDomainConfiguration->isValid(pConfigurableElement)) { @@ -945,14 +998,14 @@ const CDomainConfiguration* CConfigurableDomain::findValidDomainConfiguration(co } // Search for an applicable configuration -const CDomainConfiguration* CConfigurableDomain::findApplicableDomainConfiguration() const +const CDomainConfiguration *CConfigurableDomain::findApplicableDomainConfiguration() const { size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - const CDomainConfiguration* pDomainConfiguration = static_cast<const CDomainConfiguration*>(getChild(uiChild)); + const CDomainConfiguration *pDomainConfiguration = + static_cast<const CDomainConfiguration *>(getChild(uiChild)); if (pDomainConfiguration->isApplicable()) { @@ -963,14 +1016,16 @@ const CDomainConfiguration* CConfigurableDomain::findApplicableDomainConfigurati } // Gather set of configurable elements -void CConfigurableDomain::gatherConfigurableElements(std::set<const CConfigurableElement*>& configurableElementSet) const +void CConfigurableDomain::gatherConfigurableElements( + std::set<const CConfigurableElement *> &configurableElementSet) const { // Insert all configurable elements configurableElementSet.insert(_configurableElementList.begin(), _configurableElementList.end()); } // Check configurable element already attached -bool CConfigurableDomain::containsConfigurableElement(const CConfigurableElement* pConfigurableCandidateElement) const +bool CConfigurableDomain::containsConfigurableElement( + const CConfigurableElement *pConfigurableCandidateElement) const { ConfigurableElementListIterator it; @@ -986,23 +1041,27 @@ bool CConfigurableDomain::containsConfigurableElement(const CConfigurableElement } // Merge any descended configurable element to this one with this one -void CConfigurableDomain::mergeAlreadyAssociatedDescendantConfigurableElements(CConfigurableElement* pNewConfigurableElement) +void CConfigurableDomain::mergeAlreadyAssociatedDescendantConfigurableElements( + CConfigurableElement *newElement, core::Results &infos) { - std::list<CConfigurableElement*> mergedConfigurableElementList; + std::list<CConfigurableElement *> mergedConfigurableElementList; ConfigurableElementListIterator it; // Browse all configurable elements (new one not yet in the list!) for (it = _configurableElementList.begin(); it != _configurableElementList.end(); ++it) { - CConfigurableElement* pConfigurablePotentialDescendantElement = *it; + CConfigurableElement *pConfigurablePotentialDescendantElement = *it; - if (pConfigurablePotentialDescendantElement->isDescendantOf(pNewConfigurableElement)) { + if (pConfigurablePotentialDescendantElement->isDescendantOf(newElement)) { - log_info("In domain \"%s\", merging descendant configurable element's configurations \"%s\" into its ascendant \"%s\" ones", getName().c_str(), pConfigurablePotentialDescendantElement->getName().c_str(), pNewConfigurableElement->getName().c_str()); + infos.push_back("In domain '" + getName() + + "', merging descendant configurable element's configurations '" + + pConfigurablePotentialDescendantElement->getName() + + "' into its ascendant '" + newElement->getName() + "' ones"); // Merge configuration data - mergeConfigurations(pNewConfigurableElement, pConfigurablePotentialDescendantElement); + mergeConfigurations(newElement, pConfigurablePotentialDescendantElement); // Keep track for removal mergedConfigurableElementList.push_back(pConfigurablePotentialDescendantElement); @@ -1010,25 +1069,28 @@ void CConfigurableDomain::mergeAlreadyAssociatedDescendantConfigurableElements(C } // Remove all merged elements (new one not yet in the list!) - for (it = mergedConfigurableElementList.begin(); it != mergedConfigurableElementList.end(); ++it) { + for (it = mergedConfigurableElementList.begin(); it != mergedConfigurableElementList.end(); + ++it) { - CConfigurableElement* pMergedConfigurableElement = *it; + CConfigurableElement *pMergedConfigurableElement = *it; // Remove merged from configurable element from internal tracking list - // Note: we shouldn't need to recompute the sync set in that case, as the merged to element should include the syncers of merged from elements + // Note: we shouldn't need to recompute the sync set in that case, as the merged to element + // should include the syncers of merged from elements doRemoveConfigurableElement(pMergedConfigurableElement, false); } } -void CConfigurableDomain::mergeConfigurations(CConfigurableElement* pToConfigurableElement, CConfigurableElement* pFromConfigurableElement) +void CConfigurableDomain::mergeConfigurations(CConfigurableElement *pToConfigurableElement, + CConfigurableElement *pFromConfigurableElement) { // Propagate to domain configurations size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); // Do the merge. pDomainConfiguration->merge(pToConfigurableElement, pFromConfigurableElement); @@ -1036,13 +1098,15 @@ void CConfigurableDomain::mergeConfigurations(CConfigurableElement* pToConfigura } // Configurable elements association -void CConfigurableDomain::doAddConfigurableElement(CConfigurableElement* pConfigurableElement, const CParameterBlackboard *pMainBlackboard) +void CConfigurableDomain::doAddConfigurableElement(CConfigurableElement *pConfigurableElement, + core::Results &infos, + const CParameterBlackboard *pMainBlackboard) { // Inform configurable element pConfigurableElement->addAttachedConfigurableDomain(this); // Create associated syncer set - CSyncerSet* pSyncerSet = new CSyncerSet; + CSyncerSet *pSyncerSet = new CSyncerSet; // Add to sync set the configurable element one pConfigurableElement->fillSyncerSet(*pSyncerSet); @@ -1055,11 +1119,11 @@ void CConfigurableDomain::doAddConfigurableElement(CConfigurableElement* pConfig // Inform configurations size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); pDomainConfiguration->addConfigurableElement(pConfigurableElement, pSyncerSet); } @@ -1067,24 +1131,28 @@ void CConfigurableDomain::doAddConfigurableElement(CConfigurableElement* pConfig // Ensure area validity for that configurable element (if main blackboard provided) if (pMainBlackboard) { + infos.push_back("Validating domain '" + getName() + + "' against main blackboard for configurable element '" + + pConfigurableElement->getPath() + "'"); // Need to validate against main blackboard validateAreas(pConfigurableElement, pMainBlackboard); } // Already associated descendend configurable elements need a merge of their configuration data - mergeAlreadyAssociatedDescendantConfigurableElements(pConfigurableElement); + mergeAlreadyAssociatedDescendantConfigurableElements(pConfigurableElement, infos); // Add to list _configurableElementList.push_back(pConfigurableElement); } -void CConfigurableDomain::doRemoveConfigurableElement(CConfigurableElement* pConfigurableElement, bool bRecomputeSyncSet) +void CConfigurableDomain::doRemoveConfigurableElement(CConfigurableElement *pConfigurableElement, + bool bRecomputeSyncSet) { // Remove from list _configurableElementList.remove(pConfigurableElement); // Remove associated syncer set - CSyncerSet* pSyncerSet = getSyncerSet(pConfigurableElement); + CSyncerSet *pSyncerSet = getSyncerSet(pConfigurableElement); _configurableElementToSyncerSetMap.erase(pConfigurableElement); @@ -1095,11 +1163,11 @@ void CConfigurableDomain::doRemoveConfigurableElement(CConfigurableElement* pCon // Inform configurations size_t uiNbConfigurations = getNbChildren(); - size_t uiChild; - for (uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { + for (size_t uiChild = 0; uiChild < uiNbConfigurations; uiChild++) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(getChild(uiChild)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(getChild(uiChild)); pDomainConfiguration->removeConfigurableElement(pConfigurableElement); } @@ -1111,19 +1179,24 @@ void CConfigurableDomain::doRemoveConfigurableElement(CConfigurableElement* pCon } // Syncer set retrieval from configurable element -CSyncerSet* CConfigurableDomain::getSyncerSet(const CConfigurableElement* pConfigurableElement) const +CSyncerSet *CConfigurableDomain::getSyncerSet( + const CConfigurableElement *pConfigurableElement) const { - ConfigurableElementToSyncerSetMapIterator mapIt = _configurableElementToSyncerSetMap.find(pConfigurableElement); + ConfigurableElementToSyncerSetMapIterator mapIt = + _configurableElementToSyncerSetMap.find(pConfigurableElement); - assert(mapIt != _configurableElementToSyncerSetMap.end()); + ALWAYS_ASSERT(mapIt != _configurableElementToSyncerSetMap.end(), + "Could not find syncer set for " << getName() << " configurable domain"); return mapIt->second; } // Configuration retrieval -CDomainConfiguration* CConfigurableDomain::findConfiguration(const string& strConfiguration, string& strError) +CDomainConfiguration *CConfigurableDomain::findConfiguration(const string &strConfiguration, + string &strError) { - CDomainConfiguration* pDomainConfiguration = static_cast<CDomainConfiguration*>(findChild(strConfiguration)); + CDomainConfiguration *pDomainConfiguration = + static_cast<CDomainConfiguration *>(findChild(strConfiguration)); if (!pDomainConfiguration) { @@ -1134,9 +1207,11 @@ CDomainConfiguration* CConfigurableDomain::findConfiguration(const string& strCo return pDomainConfiguration; } -const CDomainConfiguration* CConfigurableDomain::findConfiguration(const string& strConfiguration, string& strError) const +const CDomainConfiguration *CConfigurableDomain::findConfiguration(const string &strConfiguration, + string &strError) const { - const CDomainConfiguration* pDomainConfiguration = static_cast<const CDomainConfiguration*>(findChild(strConfiguration)); + const CDomainConfiguration *pDomainConfiguration = + static_cast<const CDomainConfiguration *>(findChild(strConfiguration)); if (!pDomainConfiguration) { diff --git a/parameter/ConfigurableDomain.h b/parameter/ConfigurableDomain.h index a29c1ba..256e602 100644 --- a/parameter/ConfigurableDomain.h +++ b/parameter/ConfigurableDomain.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,10 +29,11 @@ */ #pragma once -#include "BinarySerializableElement.h" #include "XmlSerializingContext.h" #include "XmlDomainImportContext.h" +#include "XmlDomainExportContext.h" #include "SyncerSet.h" +#include "Results.h" #include <list> #include <set> #include <map> @@ -43,13 +44,15 @@ class CDomainConfiguration; class CParameterBlackboard; class CSelectionCriteriaDefinition; -class CConfigurableDomain : public CBinarySerializableElement +class CConfigurableDomain : public CElement { - typedef std::list<CConfigurableElement*>::const_iterator ConfigurableElementListIterator; - typedef std::map<const CConfigurableElement*, CSyncerSet*>::const_iterator ConfigurableElementToSyncerSetMapIterator; + typedef std::list<CConfigurableElement *>::const_iterator ConfigurableElementListIterator; + typedef std::map<const CConfigurableElement *, CSyncerSet *>::const_iterator + ConfigurableElementToSyncerSetMapIterator; + public: - CConfigurableDomain(); - CConfigurableDomain(const std::string& strName); + CConfigurableDomain() = default; + CConfigurableDomain(const std::string &strName); virtual ~CConfigurableDomain(); // Sequence awareness @@ -57,16 +60,36 @@ public: bool getSequenceAwareness() const; // Configuration Management - bool createConfiguration(const std::string& strName, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool deleteConfiguration(const std::string& strName, std::string& strError); - bool renameConfiguration(const std::string& strName, const std::string& strNewName, std::string& strError); - bool restoreConfiguration(const std::string& strName, CParameterBlackboard* pMainBlackboard, bool bAutoSync, std::list<std::string>& strError) const; - bool saveConfiguration(const std::string& strName, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool setElementSequence(const std::string& strConfiguration, const std::vector<std::string>& astrNewElementSequence, std::string& strError); - bool getElementSequence(const std::string& strConfiguration, std::string& strResult) const; - bool setApplicationRule(const std::string& strConfiguration, const std::string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, std::string& strError); - bool clearApplicationRule(const std::string& strConfiguration, std::string& strError); - bool getApplicationRule(const std::string& strConfiguration, std::string& strResult) const; + bool createConfiguration(const std::string &strName, + const CParameterBlackboard *pMainBlackboard, std::string &strError); + bool deleteConfiguration(const std::string &strName, std::string &strError); + bool renameConfiguration(const std::string &strName, const std::string &strNewName, + std::string &strError); + + /** Restore a configuration + * + * @param[in] configurationName the configuration name + * @param[in] mainBlackboard the application main blackboard + * @param[in] autoSync boolean which indicates if auto sync mechanism is on + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool restoreConfiguration(const std::string &configurationName, + CParameterBlackboard *mainBlackboard, bool autoSync, + core::Results &errors) const; + + bool saveConfiguration(const std::string &strName, const CParameterBlackboard *pMainBlackboard, + std::string &strError); + bool setElementSequence(const std::string &strConfiguration, + const std::vector<std::string> &astrNewElementSequence, + std::string &strError); + bool getElementSequence(const std::string &strConfiguration, std::string &strResult) const; + bool setApplicationRule(const std::string &strConfiguration, + const std::string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, + std::string &strError); + bool clearApplicationRule(const std::string &strConfiguration, std::string &strError); + bool getApplicationRule(const std::string &strConfiguration, std::string &strResult) const; // Last applied configuration name std::string getLastAppliedConfigurationName() const; @@ -75,86 +98,130 @@ public: std::string getPendingConfigurationName() const; // Associated Configurable elements - void gatherConfigurableElements(std::set<const CConfigurableElement*>& configurableElementSet) const; - void listAssociatedToElements(std::string& strResult) const; + void gatherConfigurableElements( + std::set<const CConfigurableElement *> &configurableElementSet) const; + void listAssociatedToElements(std::string &strResult) const; + + /** Add a configurable element to the domain + * + * @param[in] pConfigurableElement pointer to the element to add + * @param[in] pMainBlackboard pointer to the application main blackboard + * @param[out] infos useful information we can provide to client + * @return true if succeed false otherwise + */ + bool addConfigurableElement(CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard, core::Results &infos); - // Configurable elements association - bool addConfigurableElement(CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool removeConfigurableElement(CConfigurableElement* pConfigurableElement, std::string& strError); + bool removeConfigurableElement(CConfigurableElement *pConfigurableElement, + std::string &strError); // Blackboard Configuration and Base Offset retrieval - CParameterBlackboard* findConfigurationBlackboard(const std::string& strConfiguration, - const CConfigurableElement* pConfigurableElement, - uint32_t& uiBaseOffset, - bool& bIsLastApplied, - std::string& strError) const; + CParameterBlackboard *findConfigurationBlackboard( + const std::string &strConfiguration, const CConfigurableElement *pConfigurableElement, + size_t &baseOffset, bool &bIsLastApplied, std::string &strError) const; - // Domain splitting - bool split(CConfigurableElement* pConfigurableElement, std::string& strError); + /** Split the domain in two. + * Remove an element of a domain and create a new domain which owns the element. + * + * @param[in] pConfigurableElement pointer to the element to remove + * @param[out] infos useful information we can provide to client + * @return true if succeed false otherwise + */ + bool split(CConfigurableElement *pConfigurableElement, core::Results &infos); // Ensure validity on whole domain from main blackboard - void validate(const CParameterBlackboard* pMainBlackboard); + void validate(const CParameterBlackboard *pMainBlackboard); - // Configuration application if required - void apply(CParameterBlackboard* pParameterBlackboard, CSyncerSet* pSyncerSet, bool bForced) const; + /** Apply the configuration if required + * + * @param[in] pParameterBlackboard the blackboard to synchronize + * @param[in] pSyncerSet pointer to the set containing application syncers + * @param[in] bForced boolean used to force configuration application + * @param[out] info string containing useful information we can provide to client + */ + void apply(CParameterBlackboard *pParameterBlackboard, CSyncerSet *pSyncerSet, bool bForced, + std::string &info) const; // Return applicable configuration validity for given configurable element - bool isApplicableConfigurationValid(const CConfigurableElement* pConfigurableElement) const; + bool isApplicableConfigurationValid(const CConfigurableElement *pConfigurableElement) const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; - virtual void childrenToXml(CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; + virtual void childrenToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const; // Class kind virtual std::string getKind() const; protected: // Content dumping - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + std::string logValue(utility::ErrorContext &errorContext) const override; private: // Get pending configuration - const CDomainConfiguration* getPendingConfiguration() const; + const CDomainConfiguration *getPendingConfiguration() const; // Search for an applicable configuration - const CDomainConfiguration* findApplicableDomainConfiguration() const; + const CDomainConfiguration *findApplicableDomainConfiguration() const; - // Returns true if children dynamic creation is to be dealt with (here, will allow child deletion upon clean) + // Returns true if children dynamic creation is to be dealt with (here, will allow child + // deletion upon clean) virtual bool childrenAreDynamic() const; // Ensure validity on areas related to configurable element - void validateAreas(const CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard); + void validateAreas(const CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard); - // Attempt validation for all configurable element's areas, relying on already existing valid configuration inside domain + // Attempt validation for all configurable element's areas, relying on already existing valid + // configuration inside domain void autoValidateAll(); - // Attempt validation for one configurable element's areas, relying on already existing valid configuration inside domain - void autoValidateAreas(const CConfigurableElement* pConfigurableElement); + // Attempt validation for one configurable element's areas, relying on already existing valid + // configuration inside domain + void autoValidateAreas(const CConfigurableElement *pConfigurableElement); - // Attempt configuration validation for all configurable elements' areas, relying on already existing valid configuration inside domain - bool autoValidateConfiguration(CDomainConfiguration* pDomainConfiguration); + // Attempt configuration validation for all configurable elements' areas, relying on already + // existing valid configuration inside domain + bool autoValidateConfiguration(CDomainConfiguration *pDomainConfiguration); // Search for a valid configuration for given configurable element - const CDomainConfiguration* findValidDomainConfiguration(const CConfigurableElement* pConfigurableElement) const; - + const CDomainConfiguration *findValidDomainConfiguration( + const CConfigurableElement *pConfigurableElement) const; // In case configurable element was removed void computeSyncSet(); // Check configurable element already attached - bool containsConfigurableElement(const CConfigurableElement* pConfigurableCandidateElement) const; + bool containsConfigurableElement( + const CConfigurableElement *pConfigurableCandidateElement) const; - // Merge any descended configurable element to this one - void mergeAlreadyAssociatedDescendantConfigurableElements(CConfigurableElement* pNewConfigurableElement); - void mergeConfigurations(CConfigurableElement* pToConfigurableElement, CConfigurableElement* pFromConfigurableElement); + /** Merge any descended configurable element to this one + * + * @param[in] newElement pointer to element which has potential descendants which can be merged + * @param[out] infos useful information we can provide to client + */ + void mergeAlreadyAssociatedDescendantConfigurableElements(CConfigurableElement *newElement, + core::Results &infos); - // Configurable elements association - void doAddConfigurableElement(CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard = NULL); - void doRemoveConfigurableElement(CConfigurableElement* pConfigurableElement, bool bRecomputeSyncSet); + void mergeConfigurations(CConfigurableElement *pToConfigurableElement, + CConfigurableElement *pFromConfigurableElement); + + /** Actually realize the association between the domain and a configurable element + * + * @param[in] pConfigurableElement pointer to the element to add + * @param[out] infos useful information we can provide to client + * @param[in] (optional) pMainBlackboard, pointer to the application main blackboard + * Default value is NULL, when provided, blackboard area concerning the configurable + * element are validated. + */ + void doAddConfigurableElement(CConfigurableElement *pConfigurableElement, core::Results &infos, + const CParameterBlackboard *pMainBlackboard = NULL); + + void doRemoveConfigurableElement(CConfigurableElement *pConfigurableElement, + bool bRecomputeSyncSet); // XML parsing /** @@ -166,8 +233,8 @@ private: * * @return false if an error occurs, true otherwise. */ - bool parseDomainConfigurations(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext); + bool parseDomainConfigurations(const CXmlElement &xmlElement, + CXmlDomainImportContext &serializingContext); /** * Deserialize domain elements from an Xml document and add them to * the domain. @@ -177,8 +244,8 @@ private: * * @return false if an error occurs, true otherwise. */ - bool parseConfigurableElements(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext); + bool parseConfigurableElements(const CXmlElement &xmlElement, + CXmlDomainImportContext &serializingContext); /** * Deserialize settings from an Xml document and add them to * the domain. @@ -188,34 +255,35 @@ private: * * @return false if an error occurs, true otherwise. */ - bool parseSettings(const CXmlElement& xmlElement, - CXmlDomainImportContext& serializingContext); + bool parseSettings(const CXmlElement &xmlElement, CXmlDomainImportContext &serializingContext); // XML composing - void composeDomainConfigurations(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; - void composeConfigurableElements(CXmlElement& xmlElement) const; - void composeSettings(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + void composeDomainConfigurations(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const; + void composeConfigurableElements(CXmlElement &xmlElement) const; + void composeSettings(CXmlElement &xmlElement, CXmlDomainExportContext &context) const; // Syncer set retrieval from configurable element - CSyncerSet* getSyncerSet(const CConfigurableElement* pConfigurableElement) const; + CSyncerSet *getSyncerSet(const CConfigurableElement *pConfigurableElement) const; // Configuration retrieval - CDomainConfiguration* findConfiguration(const std::string& strConfiguration, std::string& strError); - const CDomainConfiguration* findConfiguration(const std::string& strConfiguration, std::string& strError) const; + CDomainConfiguration *findConfiguration(const std::string &strConfiguration, + std::string &strError); + const CDomainConfiguration *findConfiguration(const std::string &strConfiguration, + std::string &strError) const; // Configurable elements - std::list<CConfigurableElement*> _configurableElementList; + std::list<CConfigurableElement *> _configurableElementList; // Associated syncer sets - std::map<const CConfigurableElement*, CSyncerSet*> _configurableElementToSyncerSetMap; + std::map<const CConfigurableElement *, CSyncerSet *> _configurableElementToSyncerSetMap; // Sequence awareness - bool _bSequenceAware; + bool _bSequenceAware{false}; // Syncer set used to ensure propoer synchronization of restored configurable elements CSyncerSet _syncerSet; // Last applied configuration - mutable const CDomainConfiguration* _pLastAppliedConfiguration; + mutable const CDomainConfiguration *_pLastAppliedConfiguration{nullptr}; }; - diff --git a/parameter/ConfigurableDomains.cpp b/parameter/ConfigurableDomains.cpp index bfa9271..7c51083 100644 --- a/parameter/ConfigurableDomains.cpp +++ b/parameter/ConfigurableDomains.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,17 +31,11 @@ #include "ConfigurableDomains.h" #include "ConfigurableDomain.h" #include "ConfigurableElement.h" -#include "BinaryStream.h" -#include "AutoLog.h" -#define base CBinarySerializableElement +#define base CElement using std::string; -CConfigurableDomains::CConfigurableDomains() -{ -} - string CConfigurableDomains::getKind() const { return "ConfigurableDomains"; @@ -53,63 +47,73 @@ bool CConfigurableDomains::childrenAreDynamic() const } // Ensure validity on whole domains from main blackboard -void CConfigurableDomains::validate(const CParameterBlackboard* pMainBlackboard) +void CConfigurableDomains::validate(const CParameterBlackboard *pMainBlackboard) { // Delegate to domains - size_t uiChild; size_t uiNbConfigurableDomains = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - CConfigurableDomain* pChildConfigurableDomain = static_cast<CConfigurableDomain*>(getChild(uiChild)); + CConfigurableDomain *pChildConfigurableDomain = + static_cast<CConfigurableDomain *>(getChild(child)); pChildConfigurableDomain->validate(pMainBlackboard); } } // Configuration application if required -void CConfigurableDomains::apply(CParameterBlackboard* pParameterBlackboard, CSyncerSet& syncerSet, bool bForce) const +void CConfigurableDomains::apply(CParameterBlackboard *pParameterBlackboard, CSyncerSet &syncerSet, + bool bForce, core::Results &infos) const { - CAutoLog autoLog(this, "Applying configurations"); - /// Delegate to domains // Start with domains that can be synchronized all at once (with passed syncer set) - size_t uiChild; size_t uiNbConfigurableDomains = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - const CConfigurableDomain* pChildConfigurableDomain = static_cast<const CConfigurableDomain*>(getChild(uiChild)); + const CConfigurableDomain *pChildConfigurableDomain = + static_cast<const CConfigurableDomain *>(getChild(child)); + std::string info; // Apply and collect syncers when relevant - pChildConfigurableDomain->apply(pParameterBlackboard, &syncerSet, bForce); + pChildConfigurableDomain->apply(pParameterBlackboard, &syncerSet, bForce, info); + + if (!info.empty()) { + infos.push_back(info); + } } // Synchronize those collected syncers syncerSet.sync(*pParameterBlackboard, false, NULL); // Then deal with domains that need to synchronize along apply - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - const CConfigurableDomain* pChildConfigurableDomain = static_cast<const CConfigurableDomain*>(getChild(uiChild)); + const CConfigurableDomain *pChildConfigurableDomain = + static_cast<const CConfigurableDomain *>(getChild(child)); + std::string info; // Apply and synchronize when relevant - pChildConfigurableDomain->apply(pParameterBlackboard, NULL, bForce); + pChildConfigurableDomain->apply(pParameterBlackboard, NULL, bForce, info); + if (!info.empty()) { + infos.push_back(info); + } } } // From IXmlSource -void CConfigurableDomains::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CConfigurableDomains::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Set attribute - xmlElement.setAttributeString("SystemClassName", getName()); + xmlElement.setAttribute("SystemClassName", getName()); base::childrenToXml(xmlElement, serializingContext); } // Configuration/Domains handling /// Domains -bool CConfigurableDomains::createDomain(const string& strName, string& strError) +bool CConfigurableDomains::createDomain(const string &strName, string &strError) { // Already exists? if (findChild(strName)) { @@ -119,51 +123,44 @@ bool CConfigurableDomains::createDomain(const string& strName, string& strError) return false; } - log_info("Creating configurable domain \"%s\"", strName.c_str()); - // Creation/Hierarchy addChild(new CConfigurableDomain(strName)); return true; } -bool CConfigurableDomains::addDomain(CConfigurableDomain& domain, bool bOverwrite, - string& strError) +bool CConfigurableDomains::addDomain(CConfigurableDomain &domain, bool bOverwrite, string &strError) { string strErrorDrop; string strDomainName(domain.getName()); - CConfigurableDomain* pExistingDomain = findConfigurableDomain(strDomainName, strErrorDrop); + CConfigurableDomain *pExistingDomain = findConfigurableDomain(strDomainName, strErrorDrop); if (pExistingDomain) { if (!bOverwrite) { strError = "Can't add domain \"" + strDomainName + - "\" because it already exists and overwrite was not requested."; + "\" because it already exists and overwrite was not requested."; return false; } deleteDomain(*pExistingDomain); } - log_info("Adding configurable domain \"%s\"", strDomainName.c_str()); - addChild(&domain); return true; } -void CConfigurableDomains::deleteDomain(CConfigurableDomain& configurableDomain) +void CConfigurableDomains::deleteDomain(CConfigurableDomain &configurableDomain) { - log_info("Deleting configurable domain \"%s\"", configurableDomain.getName().c_str() ); - removeChild(&configurableDomain); delete &configurableDomain; } -bool CConfigurableDomains::deleteDomain(const string& strName, string& strError) +bool CConfigurableDomains::deleteDomain(const string &strName, string &strError) { - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strName, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strName, strError); if (pConfigurableDomain) { deleteDomain(*pConfigurableDomain); @@ -175,30 +172,28 @@ bool CConfigurableDomains::deleteDomain(const string& strName, string& strError) void CConfigurableDomains::deleteAllDomains() { - log_info("Deleting all configurable domains"); - - //remove Children + // remove Children clean(); } -bool CConfigurableDomains::renameDomain(const string& strName, const string& strNewName, string& strError) +bool CConfigurableDomains::renameDomain(const string &strName, const string &strNewName, + string &strError) { - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strName, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strName, strError); if (!pConfigurableDomain) { return false; } - log_info("Renaming configurable domain \"%s\" to \"%s\"", strName.c_str(), strNewName.c_str()); - // Rename return pConfigurableDomain->rename(strNewName, strError); } -bool CConfigurableDomains::setSequenceAwareness(const string& strDomain, bool bSequenceAware, string& strError) +bool CConfigurableDomains::setSequenceAwareness(const string &strDomain, bool bSequenceAware, + string &strError) { - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -210,9 +205,10 @@ bool CConfigurableDomains::setSequenceAwareness(const string& strDomain, bool bS return true; } -bool CConfigurableDomains::getSequenceAwareness(const string& strDomain, bool& bSequenceAware, string& strError) const +bool CConfigurableDomains::getSequenceAwareness(const string &strDomain, bool &bSequenceAware, + string &strError) const { - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -225,9 +221,9 @@ bool CConfigurableDomains::getSequenceAwareness(const string& strDomain, bool& b } /// Configurations -bool CConfigurableDomains::listConfigurations(const string& strDomain, string& strResult) const +bool CConfigurableDomains::listConfigurations(const string &strDomain, string &strResult) const { - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strResult); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strResult); if (!pConfigurableDomain) { @@ -239,10 +235,13 @@ bool CConfigurableDomains::listConfigurations(const string& strDomain, string& s return true; } -bool CConfigurableDomains::createConfiguration(const string& strDomain, const string& strConfiguration, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomains::createConfiguration(const string &strDomain, + const string &strConfiguration, + const CParameterBlackboard *pMainBlackboard, + string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -252,10 +251,11 @@ bool CConfigurableDomains::createConfiguration(const string& strDomain, const st return pConfigurableDomain->createConfiguration(strConfiguration, pMainBlackboard, strError); } -bool CConfigurableDomains::deleteConfiguration(const string& strDomain, const string& strConfiguration, string& strError) +bool CConfigurableDomains::deleteConfiguration(const string &strDomain, + const string &strConfiguration, string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -265,23 +265,27 @@ bool CConfigurableDomains::deleteConfiguration(const string& strDomain, const st return pConfigurableDomain->deleteConfiguration(strConfiguration, strError); } -bool CConfigurableDomains::renameConfiguration(const string& strDomain, const string& strConfigurationName, const string& strNewConfigurationName, string& strError) +bool CConfigurableDomains::renameConfiguration(const string &strDomain, + const string &strConfigurationName, + const string &strNewConfigurationName, + string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { return false; } // Delegate - return pConfigurableDomain->renameConfiguration(strConfigurationName, strNewConfigurationName, strError); + return pConfigurableDomain->renameConfiguration(strConfigurationName, strNewConfigurationName, + strError); } -bool CConfigurableDomains::listDomainElements(const string& strDomain, string& strResult) const +bool CConfigurableDomains::listDomainElements(const string &strDomain, string &strResult) const { // Find domain - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strResult); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strResult); if (!pConfigurableDomain) { @@ -293,36 +297,37 @@ bool CConfigurableDomains::listDomainElements(const string& strDomain, string& s return true; } -bool CConfigurableDomains::split(const string& strDomain, CConfigurableElement* pConfigurableElement, string& strError) +bool CConfigurableDomains::split(const string &domainName, CConfigurableElement *element, + core::Results &infos) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + std::string error; + CConfigurableDomain *domain = findConfigurableDomain(domainName, error); - if (!pConfigurableDomain) { + if (domain == NULL) { + infos.push_back(error); return false; } // Delegate - pConfigurableDomain->split(pConfigurableElement, strError); + domain->split(element, infos); return true; } -void CConfigurableDomains::listAssociatedElements(string& strResult) const +void CConfigurableDomains::listAssociatedElements(string &strResult) const { - strResult = "\n"; - - std::set<const CConfigurableElement*> configurableElementSet; + std::set<const CConfigurableElement *> configurableElementSet; // Get all owned configurable elements gatherAllOwnedConfigurableElements(configurableElementSet); // Fill result - std::set<const CConfigurableElement*>::const_iterator it; + std::set<const CConfigurableElement *>::const_iterator it; for (it = configurableElementSet.begin(); it != configurableElementSet.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; string strAssociatedDomainList; @@ -332,21 +337,19 @@ void CConfigurableDomains::listAssociatedElements(string& strResult) const } } -void CConfigurableDomains::listConflictingElements(string& strResult) const +void CConfigurableDomains::listConflictingElements(string &strResult) const { - strResult = "\n"; - - std::set<const CConfigurableElement*> configurableElementSet; + std::set<const CConfigurableElement *> configurableElementSet; // Get all owned configurable elements gatherAllOwnedConfigurableElements(configurableElementSet); // Fill result - std::set<const CConfigurableElement*>::const_iterator it; + std::set<const CConfigurableElement *>::const_iterator it; for (it = configurableElementSet.begin(); it != configurableElementSet.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; if (pConfigurableElement->getBelongingDomainCount() > 1) { @@ -354,22 +357,21 @@ void CConfigurableDomains::listConflictingElements(string& strResult) const pConfigurableElement->listBelongingDomains(strBelongingDomainList, false); - strResult += pConfigurableElement->getPath() + " contained in multiple domains: " + strBelongingDomainList + "\n"; + strResult += pConfigurableElement->getPath() + " contained in multiple domains: " + + strBelongingDomainList + "\n"; } } } -void CConfigurableDomains::listDomains(string& strResult) const +void CConfigurableDomains::listDomains(string &strResult) const { - strResult = "\n"; - // List domains - size_t uiChild; size_t uiNbConfigurableDomains = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - const CConfigurableDomain* pChildConfigurableDomain = static_cast<const CConfigurableDomain*>(getChild(uiChild)); + const CConfigurableDomain *pChildConfigurableDomain = + static_cast<const CConfigurableDomain *>(getChild(child)); // Name strResult += pChildConfigurableDomain->getName(); @@ -384,41 +386,48 @@ void CConfigurableDomains::listDomains(string& strResult) const } // Gather configurable elements owned by any domain -void CConfigurableDomains::gatherAllOwnedConfigurableElements(std::set<const CConfigurableElement*>& configurableElementSet) const +void CConfigurableDomains::gatherAllOwnedConfigurableElements( + std::set<const CConfigurableElement *> &configurableElementSet) const { // Delegate to domains - size_t uiChild; size_t uiNbConfigurableDomains = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - const CConfigurableDomain* pChildConfigurableDomain = static_cast<const CConfigurableDomain*>(getChild(uiChild)); + const CConfigurableDomain *pChildConfigurableDomain = + static_cast<const CConfigurableDomain *>(getChild(child)); pChildConfigurableDomain->gatherConfigurableElements(configurableElementSet); } } // Config restore -bool CConfigurableDomains::restoreConfiguration(const string& strDomain, const string& strConfiguration, CParameterBlackboard* pMainBlackboard, bool bAutoSync, std::list<string>& lstrError) const +bool CConfigurableDomains::restoreConfiguration(const string &domainName, + const string &configurationName, + CParameterBlackboard *mainBlackboard, bool autoSync, + core::Results &errors) const { - string strError; + string error; // Find domain - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + const CConfigurableDomain *domain = findConfigurableDomain(domainName, error); - if (!pConfigurableDomain) { + if (domain == NULL) { - lstrError.push_back(strError); + errors.push_back(error); return false; } // Delegate - return pConfigurableDomain->restoreConfiguration(strConfiguration, pMainBlackboard, bAutoSync, lstrError); + return domain->restoreConfiguration(configurationName, mainBlackboard, autoSync, errors); } // Config save -bool CConfigurableDomains::saveConfiguration(const string& strDomain, const string& strConfiguration, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomains::saveConfiguration(const string &strDomain, + const string &strConfiguration, + const CParameterBlackboard *pMainBlackboard, + string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -428,10 +437,13 @@ bool CConfigurableDomains::saveConfiguration(const string& strDomain, const stri return pConfigurableDomain->saveConfiguration(strConfiguration, pMainBlackboard, strError); } -bool CConfigurableDomains::setElementSequence(const string& strDomain, const string& strConfiguration, const std::vector<string>& astrNewElementSequence, string& strError) +bool CConfigurableDomains::setElementSequence(const string &strDomain, + const string &strConfiguration, + const std::vector<string> &astrNewElementSequence, + string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -439,13 +451,16 @@ bool CConfigurableDomains::setElementSequence(const string& strDomain, const str } // Delegate to domain - return pConfigurableDomain->setElementSequence(strConfiguration, astrNewElementSequence, strError); + return pConfigurableDomain->setElementSequence(strConfiguration, astrNewElementSequence, + strError); } -bool CConfigurableDomains::getElementSequence(const string& strDomain, const string& strConfiguration, string& strResult) const +bool CConfigurableDomains::getElementSequence(const string &strDomain, + const string &strConfiguration, + string &strResult) const { // Find domain - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strResult); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strResult); if (!pConfigurableDomain) { @@ -455,9 +470,11 @@ bool CConfigurableDomains::getElementSequence(const string& strDomain, const str return pConfigurableDomain->getElementSequence(strConfiguration, strResult); } -bool CConfigurableDomains::setApplicationRule(const string& strDomain, const string& strConfiguration, const string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, string& strError) +bool CConfigurableDomains::setApplicationRule( + const string &strDomain, const string &strConfiguration, const string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, string &strError) { - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -465,12 +482,14 @@ bool CConfigurableDomains::setApplicationRule(const string& strDomain, const str } // Delegate to domain - return pConfigurableDomain->setApplicationRule(strConfiguration, strApplicationRule, pSelectionCriteriaDefinition, strError); + return pConfigurableDomain->setApplicationRule(strConfiguration, strApplicationRule, + pSelectionCriteriaDefinition, strError); } -bool CConfigurableDomains::clearApplicationRule(const string& strDomain, const string& strConfiguration, string& strError) +bool CConfigurableDomains::clearApplicationRule(const string &strDomain, + const string &strConfiguration, string &strError) { - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -481,9 +500,11 @@ bool CConfigurableDomains::clearApplicationRule(const string& strDomain, const s return pConfigurableDomain->clearApplicationRule(strConfiguration, strError); } -bool CConfigurableDomains::getApplicationRule(const string& strDomain, const string& strConfiguration, string& strResult) const +bool CConfigurableDomains::getApplicationRule(const string &strDomain, + const string &strConfiguration, + string &strResult) const { - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strResult); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strResult); if (!pConfigurableDomain) { @@ -495,38 +516,45 @@ bool CConfigurableDomains::getApplicationRule(const string& strDomain, const str } // Last applied configurations -void CConfigurableDomains::listLastAppliedConfigurations(string& strResult) const +void CConfigurableDomains::listLastAppliedConfigurations(string &strResult) const { // Browse domains - size_t uiChild; size_t uiNbConfigurableDomains = getNbChildren(); - for (uiChild = 0; uiChild < uiNbConfigurableDomains; uiChild++) { + for (size_t child = 0; child < uiNbConfigurableDomains; child++) { - const CConfigurableDomain* pChildConfigurableDomain = static_cast<const CConfigurableDomain*>(getChild(uiChild)); + const CConfigurableDomain *pChildConfigurableDomain = + static_cast<const CConfigurableDomain *>(getChild(child)); - strResult += pChildConfigurableDomain->getName() + ": " + pChildConfigurableDomain->getLastAppliedConfigurationName() + " [" + pChildConfigurableDomain->getPendingConfigurationName() + "]\n"; + strResult += pChildConfigurableDomain->getName() + ": " + + pChildConfigurableDomain->getLastAppliedConfigurationName() + " [" + + pChildConfigurableDomain->getPendingConfigurationName() + "]\n"; } } // Configurable element - domain association -bool CConfigurableDomains::addConfigurableElementToDomain(const string& strDomain, CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard, string& strError) +bool CConfigurableDomains::addConfigurableElementToDomain( + const string &domainName, CConfigurableElement *element, + const CParameterBlackboard *mainBlackboard, core::Results &infos) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + std::string error; + CConfigurableDomain *domain = findConfigurableDomain(domainName, error); - if (!pConfigurableDomain) { + if (domain == NULL) { + infos.push_back(error); return false; } // Delegate - return pConfigurableDomain->addConfigurableElement(pConfigurableElement, pMainBlackboard, strError); + return domain->addConfigurableElement(element, mainBlackboard, infos); } -bool CConfigurableDomains::removeConfigurableElementFromDomain(const string& strDomain, CConfigurableElement* pConfigurableElement, string& strError) +bool CConfigurableDomains::removeConfigurableElementFromDomain( + const string &strDomain, CConfigurableElement *pConfigurableElement, string &strError) { // Find domain - CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -536,18 +564,13 @@ bool CConfigurableDomains::removeConfigurableElementFromDomain(const string& str return pConfigurableDomain->removeConfigurableElement(pConfigurableElement, strError); } -CParameterBlackboard* CConfigurableDomains::findConfigurationBlackboard(const string& strDomain, - const string& strConfiguration, - const CConfigurableElement* pConfigurableElement, - uint32_t& uiBaseOffset, - bool& bIsLastApplied, - string& strError) const +CParameterBlackboard *CConfigurableDomains::findConfigurationBlackboard( + const string &strDomain, const string &strConfiguration, + const CConfigurableElement *pConfigurableElement, size_t &baseOffset, bool &bIsLastApplied, + string &strError) const { - log_info("Find configuration blackboard for Domain:%s, Configuration:%s, Element:%s", - strDomain.c_str(), strConfiguration.c_str(), pConfigurableElement->getPath().c_str()); - // Find domain - const CConfigurableDomain* pConfigurableDomain = findConfigurableDomain(strDomain, strError); + const CConfigurableDomain *pConfigurableDomain = findConfigurableDomain(strDomain, strError); if (!pConfigurableDomain) { @@ -557,51 +580,33 @@ CParameterBlackboard* CConfigurableDomains::findConfigurationBlackboard(const st // Check that element belongs to the domain if (!pConfigurableElement->belongsTo(pConfigurableDomain)) { - strError = "Element \"" + pConfigurableElement->getPath() + "\" does not belong to domain \"" + strDomain + "\""; + strError = "Element \"" + pConfigurableElement->getPath() + + "\" does not belong to domain \"" + strDomain + "\""; return NULL; } // Find Configuration Blackboard and Base Offset - return pConfigurableDomain->findConfigurationBlackboard(strConfiguration, pConfigurableElement, uiBaseOffset, bIsLastApplied, strError); -} - -// Binary settings load/store -bool CConfigurableDomains::serializeSettings(const string& strBinarySettingsFilePath, bool bOut, uint8_t uiStructureChecksum, string& strError) -{ - // Instantiate byte stream - CBinaryStream binarySettingsStream(strBinarySettingsFilePath, bOut, getDataSize(), uiStructureChecksum); - - // Open file - if (!binarySettingsStream.open(strError)) { - - strError = "Unable to open binary settings file " + strBinarySettingsFilePath + ": " + strError; - - return false; - } - - // Serialize - binarySerialize(binarySettingsStream); - - // Close stream - binarySettingsStream.close(); - - return true; + return pConfigurableDomain->findConfigurationBlackboard(strConfiguration, pConfigurableElement, + baseOffset, bIsLastApplied, strError); } // Domain retrieval -CConfigurableDomain* CConfigurableDomains::findConfigurableDomain(const string& strDomain, string& strError) +CConfigurableDomain *CConfigurableDomains::findConfigurableDomain(const string &strDomain, + string &strError) { // Call the const equivalent - return const_cast<CConfigurableDomain*>( - static_cast<const CConfigurableDomains*>(this)->findConfigurableDomain(strDomain, strError) - ); + return const_cast<CConfigurableDomain *>( + static_cast<const CConfigurableDomains *>(this)->findConfigurableDomain(strDomain, + strError)); } -const CConfigurableDomain* CConfigurableDomains::findConfigurableDomain(const string& strDomain, string& strError) const +const CConfigurableDomain *CConfigurableDomains::findConfigurableDomain(const string &strDomain, + string &strError) const { // Find domain - const CConfigurableDomain* pConfigurableDomain = static_cast<const CConfigurableDomain*>(findChild(strDomain)); + const CConfigurableDomain *pConfigurableDomain = + static_cast<const CConfigurableDomain *>(findChild(strDomain)); if (!pConfigurableDomain) { diff --git a/parameter/ConfigurableDomains.h b/parameter/ConfigurableDomains.h index 3cc16df..70e943b 100644 --- a/parameter/ConfigurableDomains.h +++ b/parameter/ConfigurableDomains.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,26 +29,23 @@ */ #pragma once -#include "BinarySerializableElement.h" +#include "Element.h" +#include "Results.h" #include <set> -#include <list> #include <string> - class CParameterBlackboard; class CConfigurableElement; class CSyncerSet; class CConfigurableDomain; class CSelectionCriteriaDefinition; -class CConfigurableDomains : public CBinarySerializableElement +class CConfigurableDomains : public CElement { public: - CConfigurableDomains(); - // Configuration/Domains handling /// Domains - bool createDomain(const std::string& strName, std::string& strError); + bool createDomain(const std::string &strName, std::string &strError); /* * Adds a domain object to configurable domains. The ConfigurableDomains @@ -62,7 +59,7 @@ public: * * @returns true if the domain was successfully added */ - bool addDomain(CConfigurableDomain& domain, bool bOverwrite, std::string& strError); + bool addDomain(CConfigurableDomain &domain, bool bOverwrite, std::string &strError); /** * Delete a domain by name @@ -73,61 +70,115 @@ public: * @returns true of the domain was sucessfully deleted, false otherwise (i.e. * the domain didn't exist). */ - bool deleteDomain(const std::string& strName, std::string& strError); + bool deleteDomain(const std::string &strName, std::string &strError); void deleteAllDomains(); - bool renameDomain(const std::string& strName, const std::string& strNewName, std::string& strError); - bool setSequenceAwareness(const std::string& strDomain, bool bSequenceAware, std::string& strError); - bool getSequenceAwareness(const std::string& strDomain, bool& bSequenceAware, std::string& strError) const; - bool listDomainElements(const std::string& strDomain, std::string& strResult) const; - bool split(const std::string& strDomain, CConfigurableElement* pConfigurableElement, std::string& strError); - void listAssociatedElements(std::string& strResult) const; - void listConflictingElements(std::string& strResult) const; - void listDomains(std::string& strResult) const; + bool renameDomain(const std::string &strName, const std::string &strNewName, + std::string &strError); + bool setSequenceAwareness(const std::string &strDomain, bool bSequenceAware, + std::string &strError); + bool getSequenceAwareness(const std::string &strDomain, bool &bSequenceAware, + std::string &strError) const; + bool listDomainElements(const std::string &strDomain, std::string &strResult) const; + + /** Split a domain in two. + * Remove an element of a domain and create a new domain which owns the element. + * + * @param[in] domainName the domain name + * @param[in] element pointer to the element to remove + * @param[out] infos useful information we can provide to client + * @return true if succeed false otherwise + */ + bool split(const std::string &domainName, CConfigurableElement *element, core::Results &infos); + + void listAssociatedElements(std::string &strResult) const; + void listConflictingElements(std::string &strResult) const; + void listDomains(std::string &strResult) const; /// Configurations - bool listConfigurations(const std::string& strDomain, std::string& strResult) const; - bool createConfiguration(const std::string& strDomain, const std::string& strConfiguration, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool deleteConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool renameConfiguration(const std::string& strDomain, const std::string& strConfigurationName, const std::string& strNewConfigurationName, std::string& strError); - bool restoreConfiguration(const std::string& strDomain, const std::string& strConfiguration, CParameterBlackboard* pMainBlackboard, bool bAutoSync, std::list<std::string>& lstrError) const; - bool saveConfiguration(const std::string& strDomain, const std::string& strConfiguration, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool setElementSequence(const std::string& strDomain, const std::string& strConfiguration, const std::vector<std::string>& astrNewElementSequence, std::string& strError); - bool getElementSequence(const std::string& strDomain, const std::string& strConfiguration, std::string& strResult) const; - bool setApplicationRule(const std::string& strDomain, const std::string& strConfiguration, const std::string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, std::string& strError); - bool clearApplicationRule(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool getApplicationRule(const std::string& strDomain, const std::string& strConfiguration, std::string& strResult) const; + bool listConfigurations(const std::string &strDomain, std::string &strResult) const; + bool createConfiguration(const std::string &strDomain, const std::string &strConfiguration, + const CParameterBlackboard *pMainBlackboard, std::string &strError); + bool deleteConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool renameConfiguration(const std::string &strDomain, const std::string &strConfigurationName, + const std::string &strNewConfigurationName, std::string &strError); + + /** Restore a configuration + * + * @param[in] strDomain the domain name + * @param[in] strConfiguration the configuration name + * @param[in] pMainBlackboard the application main blackboard + * @param[in] bAutoSync boolean which indicates if auto sync mechanism is on + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool restoreConfiguration(const std::string &strDomain, const std::string &strConfiguration, + CParameterBlackboard *pMainBlackboard, bool bAutoSync, + core::Results &errors) const; + + bool saveConfiguration(const std::string &strDomain, const std::string &strConfiguration, + const CParameterBlackboard *pMainBlackboard, std::string &strError); + bool setElementSequence(const std::string &strDomain, const std::string &strConfiguration, + const std::vector<std::string> &astrNewElementSequence, + std::string &strError); + bool getElementSequence(const std::string &strDomain, const std::string &strConfiguration, + std::string &strResult) const; + bool setApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, + std::string &strError); + bool clearApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool getApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strResult) const; // Last applied configurations - void listLastAppliedConfigurations(std::string& strResult) const; + void listLastAppliedConfigurations(std::string &strResult) const; - // Configurable element - domain association - bool addConfigurableElementToDomain(const std::string& strDomain, CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard, std::string& strError); - bool removeConfigurableElementFromDomain(const std::string& strDomain, CConfigurableElement* pConfigurableElement, std::string& strError); + /** Associate a configurable element to a domain + * + * @param[in] domainName the domain name + * @param[in] element pointer to the element to add + * @param[in] mainBlackboard pointer to the application main blackboard + * @param[out] infos useful information we can provide to client + * @return true if succeed false otherwise + */ + bool addConfigurableElementToDomain(const std::string &domainName, + CConfigurableElement *element, + const CParameterBlackboard *mainBlackboard, + core::Results &infos); - // Configuration Blackboard for element - CParameterBlackboard* findConfigurationBlackboard(const std::string& strDomain, - const std::string& strConfiguration, - const CConfigurableElement* pConfigurableElement, - uint32_t& uiBaseOffset, - bool& bIsLastApplied, - std::string& strError) const; + bool removeConfigurableElementFromDomain(const std::string &strDomain, + CConfigurableElement *pConfigurableElement, + std::string &strError); - const CConfigurableDomain* findConfigurableDomain(const std::string& strDomain, - std::string& strError) const; + // Configuration Blackboard for element + CParameterBlackboard *findConfigurationBlackboard( + const std::string &strDomain, const std::string &strConfiguration, + const CConfigurableElement *pConfigurableElement, size_t &baseOffset, bool &bIsLastApplied, + std::string &strError) const; - // Binary settings load/store - bool serializeSettings(const std::string& strBinarySettingsFilePath, bool bOut, uint8_t uiStructureChecksum, std::string& strError); + const CConfigurableDomain *findConfigurableDomain(const std::string &strDomain, + std::string &strError) const; // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // Ensure validity on whole domains from main blackboard - void validate(const CParameterBlackboard* pMainBlackboard); + void validate(const CParameterBlackboard *pMainBlackboard); - // Configuration application if required - void apply(CParameterBlackboard* pParameterBlackboard, CSyncerSet& syncerSet, bool bForce) const; + /** Apply the configuration if required + * + * @param[in] pParameterBlackboard the blackboard to synchronize + * @param[in] syncerSet the set containing application syncers + * @param[in] bForce boolean used to force configuration application + * @param[out] infos useful information we can provide to client + */ + void apply(CParameterBlackboard *pParameterBlackboard, CSyncerSet &syncerSet, bool bForce, + core::Results &infos) const; // Class kind virtual std::string getKind() const; + private: /** Delete a domain * @@ -136,12 +187,13 @@ private: * @returns true of the domain was sucessfully deleted, false otherwise (i.e. * the domain didn't exist). */ - void deleteDomain(CConfigurableDomain& configurableDomain); + void deleteDomain(CConfigurableDomain &configurableDomain); // Returns true if children dynamic creation is to be dealt with virtual bool childrenAreDynamic() const; // Gather owned configurable elements owned by any domain - void gatherAllOwnedConfigurableElements(std::set<const CConfigurableElement*>& configurableElementSet) const; + void gatherAllOwnedConfigurableElements( + std::set<const CConfigurableElement *> &configurableElementSet) const; // Domain retrieval - CConfigurableDomain* findConfigurableDomain(const std::string& strDomain, std::string& strError); + CConfigurableDomain *findConfigurableDomain(const std::string &strDomain, + std::string &strError); }; - diff --git a/parameter/ConfigurableElement.cpp b/parameter/ConfigurableElement.cpp index 08a0122..615d72b 100644 --- a/parameter/ConfigurableElement.cpp +++ b/parameter/ConfigurableElement.cpp @@ -34,23 +34,53 @@ #include "ConfigurationAccessContext.h" #include "ConfigurableElementAggregator.h" #include "AreaConfiguration.h" +#include "Iterator.hpp" #include "Utility.h" +#include "XmlParameterSerializingContext.h" #include <assert.h> #define base CElement -CConfigurableElement::CConfigurableElement(const std::string& strName) : base(strName), _uiOffset(0) +CConfigurableElement::CConfigurableElement(const std::string &strName) : base(strName) { } -CConfigurableElement::~CConfigurableElement() +bool CConfigurableElement::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { + auto &context = static_cast<CXmlParameterSerializingContext &>(serializingContext); + auto &accessContext = context.getAccessContext(); + + if (accessContext.serializeSettings()) { + // As serialization and deserialisation are handled through the *same* function + // the (de)serialize object can not be const in `serializeXmlSettings` signature. + // As a result a const_cast is unavoidable :(. + // Fixme: split serializeXmlSettings in two functions (in and out) to avoid the `const_cast` + return serializeXmlSettings(const_cast<CXmlElement &>(xmlElement), + static_cast<CConfigurationAccessContext &>(accessContext)); + } + return structureFromXml(xmlElement, serializingContext); +} + +void CConfigurableElement::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const +{ + auto &context = static_cast<CXmlParameterSerializingContext &>(serializingContext); + auto &accessContext = context.getAccessContext(); + if (accessContext.serializeSettings()) { + + serializeXmlSettings(xmlElement, static_cast<CConfigurationAccessContext &>(accessContext)); + } else { + + structureToXml(xmlElement, serializingContext); + } } // XML configuration settings parsing -bool CConfigurableElement::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const +bool CConfigurableElement::serializeXmlSettings( + CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const { - size_t uiIndex; size_t uiNbChildren = getNbChildren(); if (!configurationAccessContext.serializeOut()) { @@ -60,39 +90,68 @@ bool CConfigurableElement::serializeXmlSettings(CXmlElement& xmlConfigurationSet CXmlElement xmlChildConfigurableElementSettingsElement; // Propagate to children - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { // Get child - const CConfigurableElement* pChildConfigurableElement = static_cast<const CConfigurableElement*>(getChild(uiIndex)); + const CConfigurableElement *pChildConfigurableElement = + static_cast<const CConfigurableElement *>(getChild(index)); if (!it.next(xmlChildConfigurableElementSettingsElement)) { // Structure error - configurationAccessContext.setError("Configuration settings parsing: Settings don't conform to structure of configurable element " + getName()); + configurationAccessContext.setError( + "Configuration settings parsing: missing child node " + + pChildConfigurableElement->getXmlElementName() + " (name:" + + pChildConfigurableElement->getName() + ") in " + getName()); return false; } // Check element type matches in type - if (xmlChildConfigurableElementSettingsElement.getType() != pChildConfigurableElement->getKind()) { - - // Type error - configurationAccessContext.setError("Configuration settings parsing: Settings for configurable element " + pChildConfigurableElement->getName() + " does not match expected type: " + xmlChildConfigurableElementSettingsElement.getType() + " instead of " + pChildConfigurableElement->getKind()); - - return false; + if (xmlChildConfigurableElementSettingsElement.getType() != + pChildConfigurableElement->getXmlElementName()) { + + // "Component" tag has been renamed to "ParameterBlock", but retro-compatibility + // shall be ensured. + // + // So checking if this case occurs, i.e. element name is "ParameterBlock" + // but xml setting name is "Component". + bool compatibilityCase = + (pChildConfigurableElement->getXmlElementName() == "ParameterBlock") && + (xmlChildConfigurableElementSettingsElement.getType() == "Component"); + + // Error if the compatibility case does not occur. + if (!compatibilityCase) { + + // Type error + configurationAccessContext.setError( + "Configuration settings parsing: Settings " + "for configurable element " + + pChildConfigurableElement->getQualifiedPath() + + " does not match expected type: " + + xmlChildConfigurableElementSettingsElement.getType() + " instead of " + + pChildConfigurableElement->getKind()); + return false; + } } // Check element type matches in name - if (xmlChildConfigurableElementSettingsElement.getNameAttribute() != pChildConfigurableElement->getName()) { + if (xmlChildConfigurableElementSettingsElement.getNameAttribute() != + pChildConfigurableElement->getName()) { // Name error - configurationAccessContext.setError("Configuration settings parsing: Under configurable elememnt " + getName() + ", expected element name " + pChildConfigurableElement->getName() + " but found " + xmlChildConfigurableElementSettingsElement.getNameAttribute() + " instead"); + configurationAccessContext.setError( + "Configuration settings parsing: Under configurable element " + + getQualifiedPath() + ", expected element name " + + pChildConfigurableElement->getName() + " but found " + + xmlChildConfigurableElementSettingsElement.getNameAttribute() + " instead"); return false; } // Parse child configurable element's settings - if (!pChildConfigurableElement->serializeXmlSettings(xmlChildConfigurableElementSettingsElement, configurationAccessContext)) { + if (!pChildConfigurableElement->serializeXmlSettings( + xmlChildConfigurableElementSettingsElement, configurationAccessContext)) { return false; } @@ -101,26 +160,32 @@ bool CConfigurableElement::serializeXmlSettings(CXmlElement& xmlConfigurationSet if (it.next(xmlChildConfigurableElementSettingsElement)) { // Structure error - configurationAccessContext.setError("Configuration settings parsing: Settings don't conform to structure of configurable element " + getName()); + configurationAccessContext.setError( + "Configuration settings parsing: Unexpected xml element node " + + xmlChildConfigurableElementSettingsElement.getType() + " in " + getQualifiedPath()); return false; } } else { + // Handle element name attribute + xmlConfigurationSettingsElementContent.setNameAttribute(getName()); + // Propagate to children - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - const CConfigurableElement* pChildConfigurableElement = static_cast<const CConfigurableElement*>(getChild(uiIndex)); + const CConfigurableElement *pChildConfigurableElement = + static_cast<const CConfigurableElement *>(getChild(index)); // Create corresponding child element CXmlElement xmlChildConfigurableElementSettingsElement; - xmlConfigurationSettingsElementContent.createChild(xmlChildConfigurableElementSettingsElement, pChildConfigurableElement->getKind()); - - // Handle element name attribute - xmlChildConfigurableElementSettingsElement.setNameAttribute(pChildConfigurableElement->getName()); + xmlConfigurationSettingsElementContent.createChild( + xmlChildConfigurableElementSettingsElement, + pChildConfigurableElement->getXmlElementName()); // Propagate - pChildConfigurableElement->serializeXmlSettings(xmlChildConfigurableElementSettingsElement, configurationAccessContext); + pChildConfigurableElement->serializeXmlSettings( + xmlChildConfigurableElementSettingsElement, configurationAccessContext); } } // Done @@ -128,24 +193,30 @@ bool CConfigurableElement::serializeXmlSettings(CXmlElement& xmlConfigurationSet } // AreaConfiguration creation -CAreaConfiguration* CConfigurableElement::createAreaConfiguration(const CSyncerSet* pSyncerSet) const +CAreaConfiguration *CConfigurableElement::createAreaConfiguration( + const CSyncerSet *pSyncerSet) const { return new CAreaConfiguration(this, pSyncerSet); } // Parameter access -bool CConfigurableElement::accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CConfigurableElement::accessValue(CPathNavigator &pathNavigator, std::string &strValue, + bool bSet, + CParameterAccessContext ¶meterAccessContext) const { - std::string* pStrChildName = pathNavigator.next(); + std::string *pStrChildName = pathNavigator.next(); if (!pStrChildName) { - parameterAccessContext.setError((bSet ? "Can't set " : "Can't get ") + pathNavigator.getCurrentPath() + " because it is not a parameter"); + parameterAccessContext.setError((bSet ? "Can't set " : "Can't get ") + + pathNavigator.getCurrentPath() + + " because it is not a parameter"); return false; } - const CConfigurableElement* pChild = static_cast<const CConfigurableElement*>(findChild(*pStrChildName)); + const CConfigurableElement *pChild = + static_cast<const CConfigurableElement *>(findChild(*pStrChildName)); if (!pChild) { @@ -157,78 +228,139 @@ bool CConfigurableElement::accessValue(CPathNavigator& pathNavigator, std::strin return pChild->accessValue(pathNavigator, strValue, bSet, parameterAccessContext); } -void CConfigurableElement::getListOfElementsWithMapping( - std::list<const CConfigurableElement*>& configurableElementPath) const +// Whole element access +void CConfigurableElement::getSettingsAsBytes(std::vector<uint8_t> &bytes, + CParameterAccessContext ¶meterAccessContext) const { - // Check parent - const CElement* pParent = getParent(); - if (isOfConfigurableElementType(pParent)) { + bytes.resize(getFootPrint()); + + parameterAccessContext.getParameterBlackboard()->readBytes( + bytes, getOffset() - parameterAccessContext.getBaseOffset()); +} + +bool CConfigurableElement::setSettingsAsBytes(const std::vector<uint8_t> &bytes, + CParameterAccessContext ¶meterAccessContext) const +{ + CParameterBlackboard *pParameterBlackboard = parameterAccessContext.getParameterBlackboard(); + + // Size + size_t size = getFootPrint(); + + // Check sizes match + if (size != bytes.size()) { - const CConfigurableElement* pConfigurableElement = - static_cast<const CConfigurableElement*>(pParent); + parameterAccessContext.setError(std::string("Wrong size: Expected: ") + + std::to_string(size) + " Provided: " + + std::to_string(bytes.size())); - pConfigurableElement->getListOfElementsWithMapping(configurableElementPath); + return false; } + + // Write bytes + pParameterBlackboard->writeBytes(bytes, getOffset() - parameterAccessContext.getBaseOffset()); + + if (not parameterAccessContext.getAutoSync()) { + // Auto sync is not activated, sync will be defered until an explicit request + return true; + } + + CSyncerSet syncerSet; + fillSyncerSet(syncerSet); + core::Results res; + if (not syncerSet.sync(*parameterAccessContext.getParameterBlackboard(), false, &res)) { + + parameterAccessContext.setError(utility::asString(res)); + return false; + } + return true; +} + +std::list<const CConfigurableElement *> CConfigurableElement::getConfigurableElementContext() const +{ + std::list<const CConfigurableElement *> configurableElementPath; + + const CElement *element = this; + while (element != nullptr and isOfConfigurableElementType(element)) { + auto configurableElement = static_cast<const CConfigurableElement *>(element); + + configurableElementPath.push_back(configurableElement); + element = element->getParent(); + } + + return configurableElementPath; } // Used for simulation and virtual subsystems -void CConfigurableElement::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CConfigurableElement::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { // Propagate to children - size_t uiIndex; size_t uiNbChildren = getNbChildren(); - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(getChild(uiIndex)); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(getChild(index)); pConfigurableElement->setDefaultValues(parameterAccessContext); } } // Element properties -void CConfigurableElement::showProperties(std::string& strResult) const +void CConfigurableElement::showProperties(std::string &strResult) const { base::showProperties(strResult); strResult += "Total size: " + getFootprintAsString() + "\n"; } +std::string CConfigurableElement::logValue(utility::ErrorContext &context) const +{ + return logValue(static_cast<CParameterAccessContext &>(context)); +} + +std::string CConfigurableElement::logValue(CParameterAccessContext & /*ctx*/) const +{ + // By default, an element does not have a value. Only leaf elements have + // one. This method could be pure virtual but then, several derived classes + // would need to implement it in order to simply return an empty string. + return ""; +} + // Offset -void CConfigurableElement::setOffset(uint32_t uiOffset) +void CConfigurableElement::setOffset(size_t offset) { // Assign offset locally - _uiOffset = uiOffset; + _offset = offset; // Propagate to children - size_t uiIndex; size_t uiNbChildren = getNbChildren(); - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - CConfigurableElement* pConfigurableElement = static_cast<CConfigurableElement*>(getChild(uiIndex)); + CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(getChild(index)); - pConfigurableElement->setOffset(uiOffset); + pConfigurableElement->setOffset(offset); - uiOffset += pConfigurableElement->getFootPrint(); + offset += pConfigurableElement->getFootPrint(); } } -uint32_t CConfigurableElement::getOffset() const +size_t CConfigurableElement::getOffset() const { - return _uiOffset; + return _offset; } // Memory -uint32_t CConfigurableElement::getFootPrint() const +size_t CConfigurableElement::getFootPrint() const { - uint32_t uiSize = 0; - size_t uiIndex; + size_t uiSize = 0; size_t uiNbChildren = getNbChildren(); - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(getChild(uiIndex)); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(getChild(index)); uiSize += pConfigurableElement->getFootPrint(); } @@ -237,23 +369,23 @@ uint32_t CConfigurableElement::getFootPrint() const } // Browse parent path to find syncer -ISyncer* CConfigurableElement::getSyncer() const +ISyncer *CConfigurableElement::getSyncer() const { // Check parent - const CElement* pParent = getParent(); + const CElement *pParent = getParent(); if (isOfConfigurableElementType(pParent)) { - return static_cast<const CConfigurableElement*>(pParent)->getSyncer(); + return static_cast<const CConfigurableElement *>(pParent)->getSyncer(); } return NULL; } // Syncer set (me, ascendant or descendant ones) -void CConfigurableElement::fillSyncerSet(CSyncerSet& syncerSet) const +void CConfigurableElement::fillSyncerSet(CSyncerSet &syncerSet) const { // Try me or ascendants - ISyncer* pMineOrAscendantSyncer = getSyncer(); + ISyncer *pMineOrAscendantSyncer = getSyncer(); if (pMineOrAscendantSyncer) { @@ -268,33 +400,35 @@ void CConfigurableElement::fillSyncerSet(CSyncerSet& syncerSet) const } // Syncer set (descendant) -void CConfigurableElement::fillSyncerSetFromDescendant(CSyncerSet& syncerSet) const +void CConfigurableElement::fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const { // Dig - size_t uiIndex; size_t uiNbChildren = getNbChildren(); - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(getChild(uiIndex)); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(getChild(index)); pConfigurableElement->fillSyncerSetFromDescendant(syncerSet); } } // Configurable domain association -void CConfigurableElement::addAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain) +void CConfigurableElement::addAttachedConfigurableDomain( + const CConfigurableDomain *pConfigurableDomain) { _configurableDomainList.push_back(pConfigurableDomain); } -void CConfigurableElement::removeAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain) +void CConfigurableElement::removeAttachedConfigurableDomain( + const CConfigurableDomain *pConfigurableDomain) { _configurableDomainList.remove(pConfigurableDomain); } // Belonging domain -bool CConfigurableElement::belongsTo(const CConfigurableDomain* pConfigurableDomain) const +bool CConfigurableElement::belongsTo(const CConfigurableDomain *pConfigurableDomain) const { if (containsConfigurableDomain(pConfigurableDomain)) { @@ -304,23 +438,26 @@ bool CConfigurableElement::belongsTo(const CConfigurableDomain* pConfigurableDom } // Belonging domains -void CConfigurableElement::getBelongingDomains(std::list<const CConfigurableDomain*>& configurableDomainList) const +void CConfigurableElement::getBelongingDomains( + std::list<const CConfigurableDomain *> &configurableDomainList) const { - configurableDomainList.insert(configurableDomainList.end(), _configurableDomainList.begin(), _configurableDomainList.end()); + configurableDomainList.insert(configurableDomainList.end(), _configurableDomainList.begin(), + _configurableDomainList.end()); // Check parent - const CElement* pParent = getParent(); + const CElement *pParent = getParent(); if (isOfConfigurableElementType(pParent)) { - static_cast<const CConfigurableElement*>(pParent)->getBelongingDomains(configurableDomainList); + static_cast<const CConfigurableElement *>(pParent)->getBelongingDomains( + configurableDomainList); } } -void CConfigurableElement::listBelongingDomains(std::string& strResult, bool bVertical) const +void CConfigurableElement::listBelongingDomains(std::string &strResult, bool bVertical) const { // Get belonging domain list - std::list<const CConfigurableDomain*> configurableDomainList; + std::list<const CConfigurableDomain *> configurableDomainList; getBelongingDomains(configurableDomainList); @@ -329,39 +466,52 @@ void CConfigurableElement::listBelongingDomains(std::string& strResult, bool bVe } // Elements with no domains -void CConfigurableElement::listRogueElements(std::string& strResult) const +void CConfigurableElement::listRogueElements(std::string &strResult) const { - strResult = "\n"; - // Get rogue element aggregate list (no associated domain) - std::list<const CConfigurableElement*> rogueElementList; + std::list<const CConfigurableElement *> rogueElementList; - CConfigurableElementAggregator configurableElementAggregator(rogueElementList, &CConfigurableElement::hasNoDomainAssociated); + CConfigurableElementAggregator configurableElementAggregator( + rogueElementList, &CConfigurableElement::hasNoDomainAssociated); configurableElementAggregator.aggegate(this); // Build list as std::string - std::list<const CConfigurableElement*>::const_iterator it; + std::list<const CConfigurableElement *>::const_iterator it; for (it = rogueElementList.begin(); it != rogueElementList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; strResult += pConfigurableElement->getPath() + "\n"; } } -// Belonging to no domains bool CConfigurableElement::isRogue() const { - return !getBelongingDomainCount(); + // Check not belonging to any domin from current level and towards ascendents + if (getBelongingDomainCount() != 0) { + + return false; + } + + // Get a list of elements (current + descendants) with no domains associated + std::list<const CConfigurableElement *> rogueElementList; + + CConfigurableElementAggregator agregator(rogueElementList, + &CConfigurableElement::hasNoDomainAssociated); + + agregator.aggegate(this); + + // Check only one element found which ought to be current one + return (rogueElementList.size() == 1) && (rogueElementList.front() == this); } // Footprint as string std::string CConfigurableElement::getFootprintAsString() const { // Get size as string - return CUtility::toString(getFootPrint()) + " byte(s)"; + return std::to_string(getFootPrint()) + " byte(s)"; } // Matching check for no domain association @@ -384,7 +534,7 @@ bool CConfigurableElement::hasNoValidDomainAssociated() const // Browse all configurable domains for validity checking for (it = _configurableDomainList.begin(); it != _configurableDomainList.end(); ++it) { - const CConfigurableDomain* pConfigurableDomain = *it; + const CConfigurableDomain *pConfigurableDomain = *it; if (pConfigurableDomain->isApplicableConfigurationValid(this)) { @@ -396,7 +546,7 @@ bool CConfigurableElement::hasNoValidDomainAssociated() const } // Owning domains -void CConfigurableElement::listAssociatedDomains(std::string& strResult, bool bVertical) const +void CConfigurableElement::listAssociatedDomains(std::string &strResult, bool bVertical) const { // Fill list listDomains(_configurableDomainList, strResult, bVertical); @@ -405,20 +555,17 @@ void CConfigurableElement::listAssociatedDomains(std::string& strResult, bool bV size_t CConfigurableElement::getBelongingDomainCount() const { // Get belonging domain list - std::list<const CConfigurableDomain*> configurableDomainList; + std::list<const CConfigurableDomain *> configurableDomainList; getBelongingDomains(configurableDomainList); return configurableDomainList.size(); } -void CConfigurableElement::listDomains(const std::list<const CConfigurableDomain*>& configurableDomainList, std::string& strResult, bool bVertical) const +void CConfigurableElement::listDomains( + const std::list<const CConfigurableDomain *> &configurableDomainList, std::string &strResult, + bool bVertical) const { - if (bVertical && configurableDomainList.empty()) { - - strResult = "\n"; - } - // Fill list ConfigurableDomainListConstIterator it; bool bFirst = true; @@ -426,7 +573,7 @@ void CConfigurableElement::listDomains(const std::list<const CConfigurableDomain // Browse all configurable domains for comparison for (it = configurableDomainList.begin(); it != configurableDomainList.end(); ++it) { - const CConfigurableDomain* pConfigurableDomain = *it; + const CConfigurableDomain *pConfigurableDomain = *it; if (!bVertical && !bFirst) { @@ -445,7 +592,8 @@ void CConfigurableElement::listDomains(const std::list<const CConfigurableDomain } } -bool CConfigurableElement::containsConfigurableDomain(const CConfigurableDomain* pConfigurableDomain) const +bool CConfigurableElement::containsConfigurableDomain( + const CConfigurableDomain *pConfigurableDomain) const { ConfigurableDomainListConstIterator it; @@ -461,22 +609,23 @@ bool CConfigurableElement::containsConfigurableDomain(const CConfigurableDomain* } // Belonging domain ascending search -bool CConfigurableElement::belongsToDomainAscending(const CConfigurableDomain* pConfigurableDomain) const +bool CConfigurableElement::belongsToDomainAscending( + const CConfigurableDomain *pConfigurableDomain) const { // Check parent - const CElement* pParent = getParent(); + const CElement *pParent = getParent(); if (isOfConfigurableElementType(pParent)) { - return static_cast<const CConfigurableElement*>(pParent)->belongsTo(pConfigurableDomain); + return static_cast<const CConfigurableElement *>(pParent)->belongsTo(pConfigurableDomain); } return false; } // Belonging subsystem -const CSubsystem* CConfigurableElement::getBelongingSubsystem() const +const CSubsystem *CConfigurableElement::getBelongingSubsystem() const { - const CElement* pParent = getParent(); + const CElement *pParent = getParent(); // Stop at system class if (!pParent->getParent()) { @@ -484,7 +633,7 @@ const CSubsystem* CConfigurableElement::getBelongingSubsystem() const return NULL; } - return static_cast<const CConfigurableElement*>(pParent)->getBelongingSubsystem(); + return static_cast<const CConfigurableElement *>(pParent)->getBelongingSubsystem(); } // Check element is a parameter @@ -493,9 +642,8 @@ bool CConfigurableElement::isParameter() const return false; } - // Check parent is still of current type (by structure knowledge) -bool CConfigurableElement::isOfConfigurableElementType(const CElement* pParent) const +bool CConfigurableElement::isOfConfigurableElementType(const CElement *pParent) const { assert(pParent); diff --git a/parameter/ConfigurableElement.h b/parameter/ConfigurableElement.h index 18256cf..e511447 100644 --- a/parameter/ConfigurableElement.h +++ b/parameter/ConfigurableElement.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,9 +29,12 @@ */ #pragma once +#include "parameter_export.h" + #include "Element.h" #include <list> +#include <vector> class CConfigurableDomain; class CSyncerSet; @@ -41,30 +44,32 @@ class CConfigurationAccessContext; class CParameterAccessContext; class CAreaConfiguration; -class CConfigurableElement : public CElement +class PARAMETER_EXPORT CConfigurableElement : public CElement { friend class CConfigurableDomain; friend class CDomainConfiguration; - typedef std::list<const CConfigurableDomain*>::const_iterator ConfigurableDomainListConstIterator; + typedef std::list<const CConfigurableDomain *>::const_iterator + ConfigurableDomainListConstIterator; + public: - CConfigurableElement(const std::string& strName = ""); - virtual ~CConfigurableElement(); + CConfigurableElement(const std::string &strName = ""); + virtual ~CConfigurableElement() = default; // Offset in main blackboard - void setOffset(uint32_t uiOffset); - uint32_t getOffset() const; + void setOffset(size_t offset); + size_t getOffset() const; // Allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; // Syncer set (me, ascendant or descendant ones) - void fillSyncerSet(CSyncerSet& syncerSet) const; + void fillSyncerSet(CSyncerSet &syncerSet) const; // Belonging domain - bool belongsTo(const CConfigurableDomain* pConfigurableDomain) const; + bool belongsTo(const CConfigurableDomain *pConfigurableDomain) const; // Belonging domains - void listBelongingDomains(std::string& strResult, bool bVertical = true) const; + void listBelongingDomains(std::string &strResult, bool bVertical = true) const; // Matching check for domain association bool hasNoDomainAssociated() const; @@ -73,81 +78,159 @@ public: bool hasNoValidDomainAssociated() const; // Owning domains - void listAssociatedDomains(std::string& strResult, bool bVertical = true) const; + void listAssociatedDomains(std::string &strResult, bool bVertical = true) const; size_t getBelongingDomainCount() const; // Elements with no domains - void listRogueElements(std::string& strResult) const; + void listRogueElements(std::string &strResult) const; - // Belonging to no domains + /** @return true if element is rogue, false otherwise + * + * An element is rogue if it is disjoint with all domains. + * + * Ie: An element is rogue if neither its descendants, ascendants + * nor itself are associated with any domain. + * + * Ie: An element is *not* rogue if any of its descendants, ascendants + * or itself are associated with at least one domain. + */ bool isRogue() const; // Footprint as string std::string getFootprintAsString() const; // Belonging subsystem - virtual const CSubsystem* getBelongingSubsystem() const; + virtual const CSubsystem *getBelongingSubsystem() const; // Check element is a parameter virtual bool isParameter() const; // AreaConfiguration creation - virtual CAreaConfiguration* createAreaConfiguration(const CSyncerSet* pSyncerSet) const; + virtual CAreaConfiguration *createAreaConfiguration(const CSyncerSet *pSyncerSet) const; // Parameter access - virtual bool accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + virtual bool accessValue(CPathNavigator &pathNavigator, std::string &strValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const; - /** - * Get the list of all the ancestors that have a mapping. + /** Gets the element as an array of bytes. + * + * This is like having a direct access to the blackboard. * - * The mapping is represented as a std::string of all the mapping data (key:value) defined in the - * context of the element. - * In this class, the method is generic and calls its parent getListOfElementsWithMappings(...) - * method. + * @param[out] bytes Where to store the result. + * @param[in] parameterAccessContext Context containing the blackboard to + * read from. + */ + void getSettingsAsBytes(std::vector<uint8_t> &bytes, + CParameterAccessContext ¶meterAccessContext) const; + /** Sets the element as if it was an array of bytes. * - * @param[in:out] configurableElementPath List of all the ConfigurableElements found - * that have a mapping. Elements are added at the end of the list, so the root Element will be - * the last one. + * This is like having a direct access to the blackboard. + * + * @param[out] bytes The content to be set. + * @param[in] parameterAccessContext Context containing the blackboard to + * write to. + */ + bool setSettingsAsBytes(const std::vector<uint8_t> &bytes, + CParameterAccessContext ¶meterAccessContext) const; + + /** @return List of all ConfigurableElements that have a mapping relevant in this context. + * Ie: return self and CConfigurableElement ancestor of this node. * */ - virtual void getListOfElementsWithMapping(std::list<const CConfigurableElement*>& - configurableElementPath) const; + std::list<const CConfigurableElement *> getConfigurableElementContext() const; // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; + + /** + * Get the value associated to a mapping key in the object's mapping + * + * @param[in] strKey the mapping key + * @param[out] pStrValue the associated value + * + * @return true if @p strKey is found in the object's mapping, false if not + */ + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const = 0; + /** Get the string representation of the mapping + * + * If applicable, amend values are applied to the leaf element. + */ + virtual std::string getFormattedMapping() const = 0; // XML configuration settings parsing - virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const; + virtual bool serializeXmlSettings( + CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const; + + bool fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) override final; + + void toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const override final; + + /** Deserialize the structure from xml. */ + virtual bool structureFromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) + { + // Forward to Element::fromXml. + // This is unfortunate as Element::fromXml will call back + // fromXml on each children. + // Thus on each non leaf node of the tree, the code will test if + // the setting or the structure are to be serialized. + // This test could be avoided by several ways including: + // - split 2 roles fromXml in two function + // 1) construct the elements + // 2) recursive call on children + // - dispatch in with a virtual method. This would not not remove + // the branching rather hide it behind a virtual method override. + return CElement::fromXml(xmlElement, serializingContext); + } + + /** Serialize the structure to xml. */ + virtual void structureToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const + { + // See structureFromXml implementation comment. + CElement::toXml(xmlElement, serializingContext); + } + protected: // Syncer (me or ascendant) - virtual ISyncer* getSyncer() const; + virtual ISyncer *getSyncer() const; // Syncer set (descendant) - virtual void fillSyncerSetFromDescendant(CSyncerSet& syncerSet) const; + virtual void fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const; // Configuration Domain local search - bool containsConfigurableDomain(const CConfigurableDomain* pConfigurableDomain) const; + bool containsConfigurableDomain(const CConfigurableDomain *pConfigurableDomain) const; private: + // Content dumping. Override and stop further deriving: Configurable + // Elements should be called with the overloaded version taking a + // "Parameter Access Context" (The name is misleading as it is actually + // used to access any Configurable Element). + std::string logValue(utility::ErrorContext &errorContext) const override final; + virtual std::string logValue(CParameterAccessContext &context) const; + // Configurable domain association - void addAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain); - void removeAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain); + void addAttachedConfigurableDomain(const CConfigurableDomain *pConfigurableDomain); + void removeAttachedConfigurableDomain(const CConfigurableDomain *pConfigurableDomain); // Belonging domain ascending search - bool belongsToDomainAscending(const CConfigurableDomain* pConfigurableDomain) const; + bool belongsToDomainAscending(const CConfigurableDomain *pConfigurableDomain) const; // Belonging domains - void getBelongingDomains(std::list<const CConfigurableDomain*>& configurableDomainList) const; - void listDomains(const std::list<const CConfigurableDomain*>& configurableDomainList, std::string& strResult, bool bVertical) const; + void getBelongingDomains(std::list<const CConfigurableDomain *> &configurableDomainList) const; + void listDomains(const std::list<const CConfigurableDomain *> &configurableDomainList, + std::string &strResult, bool bVertical) const; // Check parent is still of current type (by structure knowledge) - bool isOfConfigurableElementType(const CElement* pParent) const; + bool isOfConfigurableElementType(const CElement *pParent) const; // Offset in main blackboard - uint32_t _uiOffset; + size_t _offset{0}; // Associated configurable domains - std::list<const CConfigurableDomain*> _configurableDomainList; + std::list<const CConfigurableDomain *> _configurableDomainList; }; - diff --git a/parameter/ConfigurableElementAggregator.cpp b/parameter/ConfigurableElementAggregator.cpp index 75bce4b..a893f1a 100644 --- a/parameter/ConfigurableElementAggregator.cpp +++ b/parameter/ConfigurableElementAggregator.cpp @@ -30,19 +30,23 @@ #include "ConfigurableElementAggregator.h" #include "ConfigurableElement.h" -CConfigurableElementAggregator::CConfigurableElementAggregator(std::list<const CConfigurableElement*>& aggregateList, MatchesAggregationCriterion pfnMatchesAggregationCriterion) +CConfigurableElementAggregator::CConfigurableElementAggregator( + std::list<const CConfigurableElement *> &aggregateList, + MatchesAggregationCriterion pfnMatchesAggregationCriterion) : _aggregateList(aggregateList), _pfnMatchesAggregationCriterion(pfnMatchesAggregationCriterion) { } // Aggregate -void CConfigurableElementAggregator::aggegate(const CConfigurableElement* pConfigurableElement) +void CConfigurableElementAggregator::aggegate(const CConfigurableElement *pConfigurableElement) { doAggregate(pConfigurableElement, _aggregateList); } // Recursive aggregate -bool CConfigurableElementAggregator::doAggregate(const CConfigurableElement* pConfigurableElement, std::list<const CConfigurableElement*>& aggregateList) +bool CConfigurableElementAggregator::doAggregate( + const CConfigurableElement *pConfigurableElement, + std::list<const CConfigurableElement *> &aggregateList) { if (!(pConfigurableElement->*_pfnMatchesAggregationCriterion)()) { @@ -50,15 +54,15 @@ bool CConfigurableElementAggregator::doAggregate(const CConfigurableElement* pCo return false; } // Check children - std::list<const CConfigurableElement*> childAggregateElementList; + std::list<const CConfigurableElement *> childAggregateElementList; - size_t uiIndex; size_t uiNbChildren = pConfigurableElement->getNbChildren(); size_t uiNbMatchingChildren = 0; - for (uiIndex = 0; uiIndex < uiNbChildren; uiIndex++) { + for (size_t index = 0; index < uiNbChildren; index++) { - const CConfigurableElement* pChildConfigurableElement = static_cast<const CConfigurableElement*>(pConfigurableElement->getChild(uiIndex)); + const CConfigurableElement *pChildConfigurableElement = + static_cast<const CConfigurableElement *>(pConfigurableElement->getChild(index)); uiNbMatchingChildren += doAggregate(pChildConfigurableElement, childAggregateElementList); } @@ -71,7 +75,8 @@ bool CConfigurableElementAggregator::doAggregate(const CConfigurableElement* pCo return true; } else { // Add children if any - aggregateList.insert(aggregateList.end(), childAggregateElementList.begin(), childAggregateElementList.end()); + aggregateList.insert(aggregateList.end(), childAggregateElementList.begin(), + childAggregateElementList.end()); return false; } diff --git a/parameter/ConfigurableElementAggregator.h b/parameter/ConfigurableElementAggregator.h index 4c1119b..79dfc23 100644 --- a/parameter/ConfigurableElementAggregator.h +++ b/parameter/ConfigurableElementAggregator.h @@ -30,30 +30,32 @@ #pragma once #include "ConfigurableElement.h" +#include "NonCopyable.hpp" + #include <list> #include <string> - -class CConfigurableElementAggregator +class CConfigurableElementAggregator : private utility::NonCopyable { public: // Matching check method type typedef bool (CConfigurableElement::*MatchesAggregationCriterion)() const; // Constructor - CConfigurableElementAggregator(std::list<const CConfigurableElement*>& aggregateList, MatchesAggregationCriterion pfnMatchesAggregationCriterion); + CConfigurableElementAggregator(std::list<const CConfigurableElement *> &aggregateList, + MatchesAggregationCriterion pfnMatchesAggregationCriterion); // Aggregate - void aggegate(const CConfigurableElement* pConfigurableElement); + void aggegate(const CConfigurableElement *pConfigurableElement); private: // Recursive aggregate - bool doAggregate(const CConfigurableElement* pConfigurableElement, std::list<const CConfigurableElement*>& aggregateList); + bool doAggregate(const CConfigurableElement *pConfigurableElement, + std::list<const CConfigurableElement *> &aggregateList); // Aggegate list - std::list<const CConfigurableElement*>& _aggregateList; + std::list<const CConfigurableElement *> &_aggregateList; // Matching check method MatchesAggregationCriterion _pfnMatchesAggregationCriterion; }; - diff --git a/parameter/ConfigurationAccessContext.cpp b/parameter/ConfigurationAccessContext.cpp index f2f9042..5c09692 100644 --- a/parameter/ConfigurationAccessContext.cpp +++ b/parameter/ConfigurationAccessContext.cpp @@ -33,9 +33,18 @@ using std::string; -CConfigurationAccessContext::CConfigurationAccessContext(string& strError, bool bSerializeOut) : - base(strError), - _bSerializeOut(bSerializeOut) +CConfigurationAccessContext::CConfigurationAccessContext(std::string &strError, + CParameterBlackboard *pParameterBlackboard, + bool bValueSpaceIsRaw, + bool bOutputRawFormatIsHex, + bool bSerializeOut) + : base(strError, pParameterBlackboard, bValueSpaceIsRaw, bOutputRawFormatIsHex), + _bSerializeOut(bSerializeOut) +{ +} + +CConfigurationAccessContext::CConfigurationAccessContext(string &strError, bool bSerializeOut) + : base(strError), _bSerializeOut(bSerializeOut) { } diff --git a/parameter/ConfigurationAccessContext.h b/parameter/ConfigurationAccessContext.h index ef0ce31..10ffd4f 100644 --- a/parameter/ConfigurationAccessContext.h +++ b/parameter/ConfigurationAccessContext.h @@ -36,13 +36,18 @@ class CConfigurationAccessContext : public CParameterAccessContext { public: - CConfigurationAccessContext(std::string& strError, bool bSerializeOut); + CConfigurationAccessContext(std::string &strError, CParameterBlackboard *pParameterBlackboard, + bool bValueSpaceIsRaw, bool bOutputRawFormatIsHex, + bool bSerializeOut); + + CConfigurationAccessContext(std::string &strError, bool bSerializeOut); // Serialization direction bool serializeOut() const; + bool serializeSettings() const override final { return true; } + private: // Serialization direction bool _bSerializeOut; }; - diff --git a/parameter/DefaultElementLibrary.h b/parameter/DefaultElementLibrary.h index b6966c2..9223021 100644 --- a/parameter/DefaultElementLibrary.h +++ b/parameter/DefaultElementLibrary.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -34,6 +34,8 @@ #include <map> #include <string> +#include <memory> +#include <utility> /** Factory that creates an element given an xml element. If no matching builder is found, it uses * the default builder. @@ -41,24 +43,22 @@ * @tparam CDefaultElementBuilder is the class of the element builder to use if no corresponding * builder is found for a given xml element. */ -template<class CDefaultElementBuilder> -class CDefaultElementLibrary: public CElementLibrary +template <class CDefaultElementBuilder> +class CDefaultElementLibrary : public CElementLibrary { public: + virtual ~CDefaultElementLibrary() = default; - explicit CDefaultElementLibrary(bool bEnableDefaultMechanism = true); - virtual ~CDefaultElementLibrary() {} - - /** Enable the default builder fallback mechanism. + /** Set the default builder used in fallback mechanism. * @see createElement() for more detail on this mechanism. * - * @param[in] bEnable if true/false, activate/deactivate the default builder mechanism. + * @param[in] defaultBuilder if NULL default builder mechanism, else provided builder is used. */ - void enableDefaultMechanism(bool bEnable) { - _bEnableDefaultMechanism = bEnable; + void setDefaultBuilder(std::unique_ptr<CDefaultElementBuilder> defaultBuilder) + { + _defaultBuilder = std::move(defaultBuilder); } - /** Create and return an element instanciated depending on an xmlElement. * * @param[in] xmlElement: The xml element used to find a matching builder @@ -69,34 +69,28 @@ public: * create the elemen with the default element builder. * otherwise, return NULL. */ - CElement* createElement(const CXmlElement& xmlElement) const; + CElement *createElement(const CXmlElement &xmlElement) const; private: - bool _bEnableDefaultMechanism; - CDefaultElementBuilder _DefaultElementBuilder; + std::unique_ptr<CDefaultElementBuilder> _defaultBuilder; }; -template<class CDefaultElementBuilder> -CDefaultElementLibrary<CDefaultElementBuilder>::CDefaultElementLibrary(bool bEnableDefaultMechanism) : - _bEnableDefaultMechanism(bEnableDefaultMechanism), - _DefaultElementBuilder() {} - -template<class CDefaultElementBuilder> -CElement* CDefaultElementLibrary<CDefaultElementBuilder>::createElement(const CXmlElement& xmlElement) const +template <class CDefaultElementBuilder> +CElement *CDefaultElementLibrary<CDefaultElementBuilder>::createElement( + const CXmlElement &xmlElement) const { - CElement* builtElement = CElementLibrary::createElement(xmlElement); + CElement *builtElement = CElementLibrary::createElement(xmlElement); if (builtElement != NULL) { // The element was created, return it return builtElement; } - if (!_bEnableDefaultMechanism) { + if (_defaultBuilder == nullptr) { // The default builder mechanism is not enabled return NULL; } // Use the default builder - return _DefaultElementBuilder.createElement(xmlElement); + return _defaultBuilder->createElement(xmlElement); } - diff --git a/parameter/DomainConfiguration.cpp b/parameter/DomainConfiguration.cpp index ebf3056..a272c14 100644 --- a/parameter/DomainConfiguration.cpp +++ b/parameter/DomainConfiguration.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -28,7 +28,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DomainConfiguration.h" -#include "AreaConfiguration.h" #include "ConfigurableElement.h" #include "CompoundRule.h" #include "Subsystem.h" @@ -36,27 +35,21 @@ #include "XmlDomainImportContext.h" #include "XmlDomainExportContext.h" #include "ConfigurationAccessContext.h" +#include "AlwaysAssert.hpp" #include <assert.h> +#include <cstdlib> +#include <algorithm> +#include <numeric> #include "RuleParser.h" -#define base CBinarySerializableElement +#define base CElement using std::string; -CDomainConfiguration::CDomainConfiguration(const string& strName) : base(strName) +CDomainConfiguration::CDomainConfiguration(const string &strName) : base(strName) { } -CDomainConfiguration::~CDomainConfiguration() -{ - AreaConfigurationListIterator it; - - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - delete *it; - } -} - // Class kind string CDomainConfiguration::getKind() const { @@ -70,225 +63,213 @@ bool CDomainConfiguration::childrenAreDynamic() const } // XML configuration settings parsing -bool CDomainConfiguration::parseSettings(CXmlElement& xmlConfigurationSettingsElement, CXmlSerializingContext& serializingContext) +bool CDomainConfiguration::parseSettings(CXmlElement &xmlConfigurationSettingsElement, + CXmlDomainImportContext &context) { - // Actual XML context - CXmlDomainImportContext& xmlDomainImportContext = static_cast<CXmlDomainImportContext&>(serializingContext); - - // Take care of configurable elements / area configurations ranks - std::list<CAreaConfiguration*> areaConfigurationList; - // Parse configurable element's configuration settings CXmlElement::CChildIterator it(xmlConfigurationSettingsElement); CXmlElement xmlConfigurableElementSettingsElement; + auto insertLocation = begin(mAreaConfigurationList); while (it.next(xmlConfigurableElementSettingsElement)) { // Retrieve area configuration - string strConfigurableElementPath = xmlConfigurableElementSettingsElement.getAttributeString("Path"); - - CAreaConfiguration* pAreaConfiguration = findAreaConfiguration(strConfigurableElementPath); + string configurableElementPath; + xmlConfigurableElementSettingsElement.getAttribute("Path", configurableElementPath); - if (!pAreaConfiguration) { + auto areaConfiguration = findAreaConfigurationByPath(configurableElementPath); + if (areaConfiguration == end(mAreaConfigurationList)) { - xmlDomainImportContext.setError("Configurable Element " + strConfigurableElementPath + " referred to by Configuration " + getPath() + " not associated to Domain"); + context.setError("Configurable Element " + configurableElementPath + + " referred to by Configuration " + getPath() + + " not associated to Domain"); return false; } - // Ranks - areaConfigurationList.push_back(pAreaConfiguration); - // Parse - if (!serializeConfigurableElementSettings(pAreaConfiguration, xmlConfigurableElementSettingsElement, xmlDomainImportContext, false)) { + if (!importOneConfigurableElementSettings(areaConfiguration->get(), + xmlConfigurableElementSettingsElement, context)) { return false; } + // Take into account the new configuration order by moving the configuration associated to + // the element to the n-th position of the configuration list. + // It will result in prepending to the configuration list wit the configuration of all + // elements found in XML, keeping the order of the processing of the XML file. + mAreaConfigurationList.splice(insertLocation, mAreaConfigurationList, areaConfiguration); + // areaConfiguration is still valid, but now refer to the reorderer list + insertLocation = std::next(areaConfiguration); } - - // Reorder area configurations according to XML content - reorderAreaConfigurations(areaConfigurationList); - return true; } // XML configuration settings composing -void CDomainConfiguration::composeSettings(CXmlElement& xmlConfigurationSettingsElement, CXmlSerializingContext& serializingContext) const +void CDomainConfiguration::composeSettings(CXmlElement &xmlConfigurationSettingsElement, + CXmlDomainExportContext &context) const { // Go through all are configurations - AreaConfigurationListIterator it; - - for (it = _orderedAreaConfigurationList.begin(); it != _orderedAreaConfigurationList.end(); ++it) { - - const CAreaConfiguration* pAreaConfiguration = *it; + for (auto &areaConfiguration : mAreaConfigurationList) { // Retrieve configurable element - const CConfigurableElement* pConfigurableElement = pAreaConfiguration->getConfigurableElement(); + const CConfigurableElement *pConfigurableElement = + areaConfiguration->getConfigurableElement(); // Create configurable element child element CXmlElement xmlConfigurableElementSettingsElement; - xmlConfigurationSettingsElement.createChild(xmlConfigurableElementSettingsElement, "ConfigurableElement"); + xmlConfigurationSettingsElement.createChild(xmlConfigurableElementSettingsElement, + "ConfigurableElement"); // Set Path attribute - xmlConfigurableElementSettingsElement.setAttributeString("Path", pConfigurableElement->getPath()); + xmlConfigurableElementSettingsElement.setAttribute("Path", pConfigurableElement->getPath()); // Delegate composing to area configuration - ((CDomainConfiguration&)(*this)).serializeConfigurableElementSettings((CAreaConfiguration*)pAreaConfiguration, xmlConfigurableElementSettingsElement, serializingContext, true); + exportOneConfigurableElementSettings(areaConfiguration.get(), + xmlConfigurableElementSettingsElement, context); } } // Serialize one configuration for one configurable element -bool CDomainConfiguration::serializeConfigurableElementSettings(CAreaConfiguration* pAreaConfiguration, CXmlElement& xmlConfigurableElementSettingsElement, CXmlSerializingContext& serializingContext, bool bSerializeOut) +bool CDomainConfiguration::importOneConfigurableElementSettings( + CAreaConfiguration *areaConfiguration, CXmlElement &xmlConfigurableElementSettingsElement, + CXmlDomainImportContext &context) { - // Actual XML context - CXmlDomainExportContext& xmlDomainExportContext = - static_cast<CXmlDomainExportContext&>(serializingContext); - - // Configurable Element - const CConfigurableElement* pConfigurableElement = pAreaConfiguration->getConfigurableElement(); - - // Element content - CXmlElement xmlConfigurableElementSettingsElementContent; - - // Deal with element itself - if (!bSerializeOut) { + const CConfigurableElement *destination = areaConfiguration->getConfigurableElement(); - // Check structure - if (xmlConfigurableElementSettingsElement.getNbChildElements() != 1) { + // Check structure + if (xmlConfigurableElementSettingsElement.getNbChildElements() != 1) { - // Structure error - serializingContext.setError("Struture error encountered while parsing settings of " + pConfigurableElement->getKind() + " " + pConfigurableElement->getName() + " in Configuration " + getPath()); - - return false; - } + // Structure error + context.setError("Struture error encountered while parsing settings of " + + destination->getKind() + " " + destination->getName() + + " in Configuration " + getPath()); - // Check name and kind - if (!xmlConfigurableElementSettingsElement.getChildElement(pConfigurableElement->getKind(), pConfigurableElement->getName(), xmlConfigurableElementSettingsElementContent)) { + return false; + } - serializingContext.setError("Couldn't find settings for " + pConfigurableElement->getKind() + " " + pConfigurableElement->getName() + " for Configuration " + getPath()); + // Element content + CXmlElement xmlConfigurableElementSettingsElementContent; + // Check name and kind + if (!xmlConfigurableElementSettingsElement.getChildElement( + destination->getXmlElementName(), destination->getName(), + xmlConfigurableElementSettingsElementContent)) { + + // "Component" tag has been renamed to "ParameterBlock", but retro-compatibility shall + // be ensured. + // + // So checking if this case occurs, i.e. element name is "ParameterBlock" + // but found xml setting name is "Component". + bool compatibilityCase = + (destination->getXmlElementName() == "ParameterBlock") && + xmlConfigurableElementSettingsElement.getChildElement( + "Component", destination->getName(), xmlConfigurableElementSettingsElementContent); + + // Error if the compatibility case does not occur. + if (!compatibilityCase) { + context.setError("Couldn't find settings for " + destination->getXmlElementName() + + " " + destination->getName() + " for Configuration " + getPath()); return false; } - } else { - - // Create child XML element - xmlConfigurableElementSettingsElement.createChild(xmlConfigurableElementSettingsElementContent, pConfigurableElement->getKind()); - - // Set Name - xmlConfigurableElementSettingsElementContent.setNameAttribute(pConfigurableElement->getName()); } - // Change context type to parameter settings access - string strError; - // Create configuration access context - CConfigurationAccessContext configurationAccessContext(strError, bSerializeOut); - - // Provide current value space - configurationAccessContext.setValueSpaceRaw(xmlDomainExportContext.valueSpaceIsRaw()); + string error; + CConfigurationAccessContext configurationAccessContext(error, false); - // Provide current output raw format - configurationAccessContext.setOutputRawFormat(xmlDomainExportContext.outputRawFormatIsHex()); + // Have domain configuration parse settings for configurable element + bool success = areaConfiguration->serializeXmlSettings( + xmlConfigurableElementSettingsElementContent, configurationAccessContext); - // Get subsystem - const CSubsystem* pSubsystem = pConfigurableElement->getBelongingSubsystem(); + context.appendToError(error); + return success; +} - if (pSubsystem && pSubsystem != pConfigurableElement) { +bool CDomainConfiguration::exportOneConfigurableElementSettings( + CAreaConfiguration *areaConfiguration, CXmlElement &xmlConfigurableElementSettingsElement, + CXmlDomainExportContext &context) const +{ + const CConfigurableElement *source = areaConfiguration->getConfigurableElement(); - // Element is a descendant of subsystem + // Create child XML element + CXmlElement xmlConfigurableElementSettingsElementContent; + xmlConfigurableElementSettingsElement.createChild(xmlConfigurableElementSettingsElementContent, + source->getXmlElementName()); - // Deal with Endianness - configurationAccessContext.setBigEndianSubsystem(pSubsystem->isBigEndian()); - } + // Create configuration access context + string error; + CConfigurationAccessContext configurationAccessContext(error, true); + configurationAccessContext.setValueSpaceRaw(context.valueSpaceIsRaw()); + configurationAccessContext.setOutputRawFormat(context.outputRawFormatIsHex()); // Have domain configuration parse settings for configurable element - if (!pAreaConfiguration->serializeXmlSettings(xmlConfigurableElementSettingsElementContent, configurationAccessContext)) { - - // Forward error - xmlDomainExportContext.setError(strError); + bool success = areaConfiguration->serializeXmlSettings( + xmlConfigurableElementSettingsElementContent, configurationAccessContext); - return false; - } - return true; + context.appendToError(error); + return success; } -// Configurable Elements association -void CDomainConfiguration::addConfigurableElement(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet) +void CDomainConfiguration::addConfigurableElement(const CConfigurableElement *configurableElement, + const CSyncerSet *syncerSet) { - CAreaConfiguration* pAreaConfiguration = pConfigurableElement->createAreaConfiguration(pSyncerSet); - - _areaConfigurationList.push_back(pAreaConfiguration); - _orderedAreaConfigurationList.push_back(pAreaConfiguration); + mAreaConfigurationList.emplace_back(configurableElement->createAreaConfiguration(syncerSet)); } -void CDomainConfiguration::removeConfigurableElement(const CConfigurableElement* pConfigurableElement) +void CDomainConfiguration::removeConfigurableElement( + const CConfigurableElement *pConfigurableElement) { - CAreaConfiguration* pAreaConfigurationToRemove = getAreaConfiguration(pConfigurableElement); - - _areaConfigurationList.remove(pAreaConfigurationToRemove); - _orderedAreaConfigurationList.remove(pAreaConfigurationToRemove); + auto &areaConfigurationToRemove = getAreaConfiguration(pConfigurableElement); - delete pAreaConfigurationToRemove; + mAreaConfigurationList.remove(areaConfigurationToRemove); } -// Sequence management -bool CDomainConfiguration::setElementSequence(const std::vector<string>& astrNewElementSequence, string& strError) +bool CDomainConfiguration::setElementSequence(const std::vector<string> &newElementSequence, + string &error) { - // Build a new list of AreaConfiguration objects - std::list<CAreaConfiguration*> areaConfigurationList; + std::vector<string> elementSequenceSet; + auto insertLocation = begin(mAreaConfigurationList); - uint32_t uiConfigurableElement; + for (const std::string &elementPath : newElementSequence) { - for (uiConfigurableElement = 0; uiConfigurableElement < astrNewElementSequence.size(); uiConfigurableElement++) { + auto areaConfiguration = findAreaConfigurationByPath(elementPath); + if (areaConfiguration == end(mAreaConfigurationList)) { - string strConfigurableElementPath = astrNewElementSequence[uiConfigurableElement]; - - CAreaConfiguration* pAreaConfiguration = findAreaConfiguration(strConfigurableElementPath); - - if (!pAreaConfiguration) { - - strError = "Element " + strConfigurableElementPath + " not found in domain"; + error = "Element " + elementPath + " not found in domain"; return false; } - // Check not already present in the list - if (findAreaConfiguration(strConfigurableElementPath, areaConfigurationList)) { - - strError = "Element " + strConfigurableElementPath + " provided more than once"; - + auto it = find(begin(elementSequenceSet), end(elementSequenceSet), elementPath); + if (it != end(elementSequenceSet)) { + error = "Element " + elementPath + " provided more than once"; return false; } - - // Store new ordered area configuration - areaConfigurationList.push_back(pAreaConfiguration); + elementSequenceSet.push_back(elementPath); + // Take into account the new configuration order by moving the configuration associated to + // the element to the n-th position of the configuration list. + // It will result in prepending to the configuration list wit the configuration of all + // elements found in XML, keeping the order of the processing of the XML file. + mAreaConfigurationList.splice(insertLocation, mAreaConfigurationList, areaConfiguration); + // areaConfiguration is still valid, but now refer to the reorderer list + insertLocation = std::next(areaConfiguration); } - - // Reorder area configurations according to given path list - reorderAreaConfigurations(areaConfigurationList); - return true; } -void CDomainConfiguration::getElementSequence(string& strResult) const +void CDomainConfiguration::getElementSequence(string &strResult) const { - strResult = "\n"; - - AreaConfigurationListIterator it; - // List configurable element paths out of ordered area configuration list - for (it = _orderedAreaConfigurationList.begin(); it != _orderedAreaConfigurationList.end(); ++it) { - - const CAreaConfiguration* pAreaConfiguration = *it; - - const CConfigurableElement* pConfigurableElement = pAreaConfiguration->getConfigurableElement(); - - strResult += pConfigurableElement->getPath() + "\n"; - } + strResult = accumulate(begin(mAreaConfigurationList), end(mAreaConfigurationList), string("\n"), + [](const string &a, const AreaConfiguration &conf) { + return a + conf->getConfigurableElement()->getPath() + "\n"; + }); } // Application rule -bool CDomainConfiguration::setApplicationRule(const string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, string& strError) +bool CDomainConfiguration::setApplicationRule( + const string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, string &strError) { // Parser CRuleParser ruleParser(strApplicationRule, pSelectionCriteriaDefinition); @@ -310,22 +291,10 @@ void CDomainConfiguration::clearApplicationRule() setRule(NULL); } -void CDomainConfiguration::getApplicationRule(string& strResult) const +string CDomainConfiguration::getApplicationRule() const { - // Rule - const CCompoundRule* pRule = getRule(); - - if (pRule) { - // Start clear - strResult.clear(); - - // Dump rule - pRule->dump(strResult); - - } else { - - strResult = "<none>"; - } + const CCompoundRule *pRule = getRule(); + return pRule ? pRule->dump() : "<none>"; } /** @@ -340,141 +309,126 @@ void CDomainConfiguration::getApplicationRule(string& strResult) const * * return Pointer to the Blackboard of the Configuration. */ -CParameterBlackboard* CDomainConfiguration::getBlackboard(const CConfigurableElement* pConfigurableElement) const +CParameterBlackboard *CDomainConfiguration::getBlackboard( + const CConfigurableElement *pConfigurableElement) const { - AreaConfigurationListIterator it; - - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - // Check if the Element is associated with the Domain - if (pAreaConfiguration->getConfigurableElement() == pConfigurableElement) { - - return &pAreaConfiguration->getBlackboard(); - } - } - - assert(0); - return NULL; + const auto &it = find_if(begin(mAreaConfigurationList), end(mAreaConfigurationList), + [&](const AreaConfiguration &conf) { + return conf != nullptr && + conf->getConfigurableElement() == pConfigurableElement; + }); + ALWAYS_ASSERT(it != end(mAreaConfigurationList), "Configurable Element " + << pConfigurableElement->getName() + << " not found in any area Configuration"); + return &(*it)->getBlackboard(); } // Save data from current -void CDomainConfiguration::save(const CParameterBlackboard* pMainBlackboard) +void CDomainConfiguration::save(const CParameterBlackboard *pMainBlackboard) { - AreaConfigurationListIterator it; - // Just propagate to areas - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - pAreaConfiguration->save(pMainBlackboard); + for (auto &areaConfiguration : mAreaConfigurationList) { + areaConfiguration->save(pMainBlackboard); } } // Apply data to current -bool CDomainConfiguration::restore(CParameterBlackboard* pMainBlackboard, bool bSync, std::list<string>* plstrError) const +bool CDomainConfiguration::restore(CParameterBlackboard *pMainBlackboard, bool bSync, + core::Results *errors) const { - bool bSuccess = true; - - AreaConfigurationListIterator it; - - // Just propagate to areas - for (it = _orderedAreaConfigurationList.begin(); it != _orderedAreaConfigurationList.end(); ++it) { - - const CAreaConfiguration* pAreaConfiguration = *it; - - bSuccess &= pAreaConfiguration->restore(pMainBlackboard, bSync, plstrError); - } - - return bSuccess; + return std::accumulate(begin(mAreaConfigurationList), end(mAreaConfigurationList), true, + [&](bool accumulator, const AreaConfiguration &conf) { + return conf->restore(pMainBlackboard, bSync, errors) && accumulator; + }); } // Ensure validity for configurable element area configuration -void CDomainConfiguration::validate(const CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard) +void CDomainConfiguration::validate(const CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard) { - CAreaConfiguration* pAreaConfigurationToValidate = getAreaConfiguration(pConfigurableElement); + auto &areaConfigurationToValidate = getAreaConfiguration(pConfigurableElement); // Delegate - pAreaConfigurationToValidate->validate(pMainBlackboard); + areaConfigurationToValidate->validate(pMainBlackboard); } // Ensure validity of all area configurations -void CDomainConfiguration::validate(const CParameterBlackboard* pMainBlackboard) +void CDomainConfiguration::validate(const CParameterBlackboard *pMainBlackboard) { - AreaConfigurationListIterator it; - - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - pAreaConfiguration->validate(pMainBlackboard); + for (auto &areaConfiguration : mAreaConfigurationList) { + areaConfiguration->validate(pMainBlackboard); } } // Return configuration validity for given configurable element -bool CDomainConfiguration::isValid(const CConfigurableElement* pConfigurableElement) const +bool CDomainConfiguration::isValid(const CConfigurableElement *pConfigurableElement) const { // Get child configurable elemnt's area configuration - CAreaConfiguration* pAreaConfiguration = getAreaConfiguration(pConfigurableElement); + auto &areaConfiguration = getAreaConfiguration(pConfigurableElement); - assert(pAreaConfiguration); + ALWAYS_ASSERT(areaConfiguration != nullptr, "Configurable Element " + << pConfigurableElement->getName() + << " not found in any area Configuration"); - return pAreaConfiguration->isValid(); + return areaConfiguration->isValid(); } // Ensure validity of configurable element's area configuration by copying in from a valid one -void CDomainConfiguration::validateAgainst(const CDomainConfiguration* pValidDomainConfiguration, const CConfigurableElement* pConfigurableElement) +void CDomainConfiguration::validateAgainst(const CDomainConfiguration *pValidDomainConfiguration, + const CConfigurableElement *pConfigurableElement) { // Retrieve related area configurations - CAreaConfiguration* pAreaConfigurationToValidate = getAreaConfiguration(pConfigurableElement); - const CAreaConfiguration* pAreaConfigurationToValidateAgainst = pValidDomainConfiguration->getAreaConfiguration(pConfigurableElement); + auto &areaConfigurationToValidate = getAreaConfiguration(pConfigurableElement); + const auto &areaConfigurationToValidateAgainst = + pValidDomainConfiguration->getAreaConfiguration(pConfigurableElement); // Delegate to area - pAreaConfigurationToValidate->validateAgainst(pAreaConfigurationToValidateAgainst); -} - -// Ensure validity of all configurable element's area configuration by copying in from a valid ones -void CDomainConfiguration::validateAgainst(const CDomainConfiguration* pValidDomainConfiguration) -{ - // Copy in configuration data from against domain - AreaConfigurationListIterator it, itAgainst; - - for (it = _areaConfigurationList.begin(), itAgainst = pValidDomainConfiguration->_areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it, ++itAgainst) { - - CAreaConfiguration* pAreaConfigurationToValidate = *it; - const CAreaConfiguration* pAreaConfigurationToValidateAgainst = *itAgainst; - + areaConfigurationToValidate->validateAgainst(areaConfigurationToValidateAgainst.get()); +} + +void CDomainConfiguration::validateAgainst(const CDomainConfiguration *validDomainConfiguration) +{ + ALWAYS_ASSERT(mAreaConfigurationList.size() == + validDomainConfiguration->mAreaConfigurationList.size(), + "Cannot validate domain configuration " + << getPath() << " since area configuration list does not have the same size" + "than the configuration list to check against"); + for (const auto &configurationToValidateAgainst : + validDomainConfiguration->mAreaConfigurationList) { + // Get the area configuration associated to the configurable element of the + // valid area configuration, it will assert if none found. + auto configurableElement = configurationToValidateAgainst->getConfigurableElement(); + auto &configurationToValidate = getAreaConfiguration(configurableElement); // Delegate to area - pAreaConfigurationToValidate->validateAgainst(pAreaConfigurationToValidateAgainst); + configurationToValidate->validateAgainst(configurationToValidateAgainst.get()); } } // Dynamic data application bool CDomainConfiguration::isApplicable() const { - const CCompoundRule* pRule = getRule(); + const CCompoundRule *pRule = getRule(); return pRule && pRule->matches(); } // Merge existing configurations to given configurable element ones -void CDomainConfiguration::merge(CConfigurableElement* pToConfigurableElement, CConfigurableElement* pFromConfigurableElement) +void CDomainConfiguration::merge(CConfigurableElement *pToConfigurableElement, + CConfigurableElement *pFromConfigurableElement) { // Retrieve related area configurations - CAreaConfiguration* pAreaConfigurationToMergeTo = getAreaConfiguration(pToConfigurableElement); - const CAreaConfiguration* pAreaConfigurationToMergeFrom = getAreaConfiguration(pFromConfigurableElement); + auto &areaConfigurationToMergeTo = getAreaConfiguration(pToConfigurableElement); + const auto &areaConfigurationToMergeFrom = getAreaConfiguration(pFromConfigurableElement); // Do the merge - pAreaConfigurationToMergeFrom->copyToOuter(pAreaConfigurationToMergeTo); + areaConfigurationToMergeFrom->copyToOuter(areaConfigurationToMergeTo.get()); } // Domain splitting -void CDomainConfiguration::split(CConfigurableElement* pFromConfigurableElement) +void CDomainConfiguration::split(CConfigurableElement *pFromConfigurableElement) { // Retrieve related area configuration - const CAreaConfiguration* pAreaConfigurationToSplitFrom = getAreaConfiguration(pFromConfigurableElement); + const auto &areaConfigurationToSplitFrom = getAreaConfiguration(pFromConfigurableElement); // Go through children areas to copy configuration data to them size_t uiNbConfigurableElementChildren = pFromConfigurableElement->getNbChildren(); @@ -482,140 +436,63 @@ void CDomainConfiguration::split(CConfigurableElement* pFromConfigurableElement) for (uiChild = 0; uiChild < uiNbConfigurableElementChildren; uiChild++) { - CConfigurableElement* pToChildConfigurableElement = static_cast<CConfigurableElement*>(pFromConfigurableElement->getChild(uiChild)); + CConfigurableElement *pToChildConfigurableElement = + static_cast<CConfigurableElement *>(pFromConfigurableElement->getChild(uiChild)); // Get child configurable elemnt's area configuration - CAreaConfiguration* pChildAreaConfiguration = getAreaConfiguration(pToChildConfigurableElement); + auto &childAreaConfiguration = getAreaConfiguration(pToChildConfigurableElement); // Do the copy - pChildAreaConfiguration->copyFromOuter(pAreaConfigurationToSplitFrom); + childAreaConfiguration->copyFromOuter(areaConfigurationToSplitFrom.get()); } } -// AreaConfiguration retrieval from configurable element -CAreaConfiguration* CDomainConfiguration::getAreaConfiguration(const CConfigurableElement* pConfigurableElement) const +const CDomainConfiguration::AreaConfiguration &CDomainConfiguration::getAreaConfiguration( + const CConfigurableElement *pConfigurableElement) const { - AreaConfigurationListIterator it; - - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - if (pAreaConfiguration->getConfigurableElement() == pConfigurableElement) { - - return pAreaConfiguration; - } - } - // Not found? - assert(0); - - return NULL; -} - -// AreaConfiguration retrieval from present area configurations -CAreaConfiguration* CDomainConfiguration::findAreaConfiguration(const string& strConfigurableElementPath) const -{ - return findAreaConfiguration(strConfigurableElementPath, _areaConfigurationList); -} - -// AreaConfiguration retrieval from given area configuration list -CAreaConfiguration* CDomainConfiguration::findAreaConfiguration(const string& strConfigurableElementPath, const std::list<CAreaConfiguration*>& areaConfigurationList) const -{ - AreaConfigurationListIterator it; - - for (it = areaConfigurationList.begin(); it != areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - if (pAreaConfiguration->getConfigurableElement()->getPath() == strConfigurableElementPath) { - - return pAreaConfiguration; - } - } - - // Not found - return NULL; + const auto &it = find_if(begin(mAreaConfigurationList), end(mAreaConfigurationList), + [&](const AreaConfiguration &conf) { + return conf->getConfigurableElement() == pConfigurableElement; + }); + ALWAYS_ASSERT(it != end(mAreaConfigurationList), + "Configurable Element " << pConfigurableElement->getName() + << " not found in Domain Configuration list"); + return *it; } -// Area configuration ordering -void CDomainConfiguration::reorderAreaConfigurations(const std::list<CAreaConfiguration*>& areaConfigurationList) +CDomainConfiguration::AreaConfigurations::iterator CDomainConfiguration:: + findAreaConfigurationByPath(const std::string &configurableElementPath) { - // Ensure elements in provided list appear first and ordered the same way in internal one - - // Remove all elements present in the provided list from the internal one - AreaConfigurationListIterator it; - - for (it = areaConfigurationList.begin(); it != areaConfigurationList.end(); ++it) { - - _orderedAreaConfigurationList.remove(*it); - } - - // Prepended provided elements into internal list - _orderedAreaConfigurationList.insert(_orderedAreaConfigurationList.begin(), areaConfigurationList.begin(), areaConfigurationList.end()); -} - -// Find area configuration rank from regular list: for ordered list maintainance -uint32_t CDomainConfiguration::getAreaConfigurationRank(const CAreaConfiguration* pAreaConfiguration) const -{ - uint32_t uiAreaConfigurationRank; - AreaConfigurationListIterator it; - - // Propagate request to areas - for (it = _areaConfigurationList.begin(), uiAreaConfigurationRank = 0; it != _areaConfigurationList.end(); ++it, ++uiAreaConfigurationRank) { - - if (*it == pAreaConfiguration) { - - return uiAreaConfigurationRank; - } - } - - assert(0); - - return 0; -} - -// Find area configuration from regular list based on rank: for ordered list maintainance -CAreaConfiguration* CDomainConfiguration::getAreaConfiguration(uint32_t uiAreaConfigurationRank) const -{ - AreaConfigurationListIterator it; - uint32_t uiCurrentAreaConfigurationRank; - - // Propagate request to areas - for (it = _areaConfigurationList.begin(), uiCurrentAreaConfigurationRank = 0; it != _areaConfigurationList.end(); ++it, ++uiCurrentAreaConfigurationRank) { - - if (uiCurrentAreaConfigurationRank == uiAreaConfigurationRank) { - - return *it; - } - } - - assert(0); - - return NULL; + auto areaConfiguration = + find_if(begin(mAreaConfigurationList), end(mAreaConfigurationList), + [&](const AreaConfiguration &conf) { + return conf->getConfigurableElement()->getPath() == configurableElementPath; + }); + return areaConfiguration; } // Rule -const CCompoundRule* CDomainConfiguration::getRule() const +const CCompoundRule *CDomainConfiguration::getRule() const { if (getNbChildren()) { // Rule created - return static_cast<const CCompoundRule*>(getChild(ECompoundRule)); + return static_cast<const CCompoundRule *>(getChild(ECompoundRule)); } return NULL; } -CCompoundRule* CDomainConfiguration::getRule() +CCompoundRule *CDomainConfiguration::getRule() { if (getNbChildren()) { // Rule created - return static_cast<CCompoundRule*>(getChild(ECompoundRule)); + return static_cast<CCompoundRule *>(getChild(ECompoundRule)); } return NULL; } -void CDomainConfiguration::setRule(CCompoundRule* pRule) +void CDomainConfiguration::setRule(CCompoundRule *pRule) { - CCompoundRule* pOldRule = getRule(); + CCompoundRule *pOldRule = getRule(); if (pOldRule) { // Remove previous rule @@ -630,66 +507,3 @@ void CDomainConfiguration::setRule(CCompoundRule* pRule) addChild(pRule); } } - -// Serialization -void CDomainConfiguration::binarySerialize(CBinaryStream& binaryStream) -{ - AreaConfigurationListIterator it; - - // Area configurations order - if (binaryStream.isOut()) { - - for (it = _orderedAreaConfigurationList.begin(); it != _orderedAreaConfigurationList.end(); ++it) { - - // Get rank - uint32_t uiAreaConfigurationRank = getAreaConfigurationRank(*it); - - // Store it - binaryStream.write((const uint8_t*)&uiAreaConfigurationRank, sizeof(uiAreaConfigurationRank)); - } - } else { - - // Empty ordered list first - _orderedAreaConfigurationList.resize(0); - - uint32_t uiAreaConfiguration; - - for (uiAreaConfiguration = 0; uiAreaConfiguration < _areaConfigurationList.size(); uiAreaConfiguration++) { - - // Get rank - uint32_t uiAreaConfigurationRank; - - binaryStream.read((uint8_t*)&uiAreaConfigurationRank, sizeof(uiAreaConfigurationRank)); - - _orderedAreaConfigurationList.push_back(getAreaConfiguration(uiAreaConfigurationRank)); - } - } - - // Propagate to areas - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - CAreaConfiguration* pAreaConfiguration = *it; - - pAreaConfiguration->serialize(binaryStream); - } -} - -// Data size -size_t CDomainConfiguration::getDataSize() const -{ - size_t uiDataSize; - - // Add necessary size to store area configurations order - uiDataSize = _areaConfigurationList.size() * sizeof(uint32_t); - - // Propagate request to areas - AreaConfigurationListIterator it; - - for (it = _areaConfigurationList.begin(); it != _areaConfigurationList.end(); ++it) { - - const CAreaConfiguration* pAreaConfiguration = *it; - - uiDataSize += pAreaConfiguration->getSize(); - } - return uiDataSize; -} diff --git a/parameter/DomainConfiguration.h b/parameter/DomainConfiguration.h index e8b41ef..f45c155 100644 --- a/parameter/DomainConfiguration.h +++ b/parameter/DomainConfiguration.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,102 +29,132 @@ */ #pragma once -#include "BinarySerializableElement.h" +#include "AreaConfiguration.h" +#include "XmlDomainImportContext.h" +#include "XmlDomainExportContext.h" +#include "Element.h" +#include "Results.h" #include <list> #include <string> +#include <memory> class CConfigurableElement; -class CAreaConfiguration; class CParameterBlackboard; class CConfigurationAccessContext; class CCompoundRule; class CSyncerSet; class CSelectionCriteriaDefinition; -class CDomainConfiguration : public CBinarySerializableElement +class CDomainConfiguration : public CElement { - enum ChildElementType { + enum ChildElementType + { ECompoundRule }; - typedef std::list<CAreaConfiguration*>::const_iterator AreaConfigurationListIterator; + public: - CDomainConfiguration(const std::string& strName); - virtual ~CDomainConfiguration(); + CDomainConfiguration(const std::string &strName); // Configurable Elements association - void addConfigurableElement(const CConfigurableElement* pConfigurableElement, const CSyncerSet* pSyncerSet); - void removeConfigurableElement(const CConfigurableElement* pConfigurableElement); + void addConfigurableElement(const CConfigurableElement *configurableElement, + const CSyncerSet *syncerSet); + void removeConfigurableElement(const CConfigurableElement *pConfigurableElement); - // Sequence management - bool setElementSequence(const std::vector<std::string>& astrNewElementSequence, std::string& strError); - void getElementSequence(std::string& strResult) const; + /** + * Sequence management: Prepend provided elements into internal list in the same order than + * they appear in the sequence of element path. + * @param[in] newElementSequence sequence of path of new element + * @param[out] error human readable error + * @return true if the new sequence has been taken into account, false otherwise and error is + * set accordingly. + */ + bool setElementSequence(const std::vector<std::string> &newElementSequence, std::string &error); + void getElementSequence(std::string &strResult) const; // Application rule - bool setApplicationRule(const std::string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition, std::string& strError); + bool setApplicationRule(const std::string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition, + std::string &strError); void clearApplicationRule(); - void getApplicationRule(std::string& strResult) const; + std::string getApplicationRule() const; // Get Blackboard for an element of the domain - CParameterBlackboard* getBlackboard(const CConfigurableElement* pConfigurableElement) const; + CParameterBlackboard *getBlackboard(const CConfigurableElement *pConfigurableElement) const; // Save data from current - void save(const CParameterBlackboard* pMainBlackboard); - // Apply data to current - bool restore(CParameterBlackboard* pMainBlackboard, bool bSync, std::list<std::string>* plstrError = NULL) const; + void save(const CParameterBlackboard *pMainBlackboard); + + /** Restore the configuration + * + * @param[in] pMainBlackboard the application main blackboard + * @param[in] bSync indicates if a synchronisation has to be done + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool restore(CParameterBlackboard *pMainBlackboard, bool bSync, + core::Results *errors = NULL) const; + // Ensure validity for configurable element area configuration - void validate(const CConfigurableElement* pConfigurableElement, const CParameterBlackboard* pMainBlackboard); + void validate(const CConfigurableElement *pConfigurableElement, + const CParameterBlackboard *pMainBlackboard); // Ensure validity of all area configurations - void validate(const CParameterBlackboard* pMainBlackboard); + void validate(const CParameterBlackboard *pMainBlackboard); // Return configuration validity for given configurable element - bool isValid(const CConfigurableElement* pConfigurableElement) const; + bool isValid(const CConfigurableElement *pConfigurableElement) const; // Ensure validity of configurable element's area configuration by copying in from a valid one - void validateAgainst(const CDomainConfiguration* pValidDomainConfiguration, const CConfigurableElement* pConfigurableElement); - // Ensure validity of all configurable element's area configuration by copying in from a valid ones - void validateAgainst(const CDomainConfiguration* pValidDomainConfiguration); + void validateAgainst(const CDomainConfiguration *pValidDomainConfiguration, + const CConfigurableElement *pConfigurableElement); + // Ensure validity of all configurable element's area configuration by copying in from a valid + // ones + void validateAgainst(const CDomainConfiguration *validDomainConfiguration); // Applicability checking bool isApplicable() const; // Merge existing configurations to given configurable element ones - void merge(CConfigurableElement* pToConfigurableElement, CConfigurableElement* pFromConfigurableElement); + void merge(CConfigurableElement *pToConfigurableElement, + CConfigurableElement *pFromConfigurableElement); // Domain splitting - void split(CConfigurableElement* pFromConfigurableElement); + void split(CConfigurableElement *pFromConfigurableElement); // XML configuration settings parsing/composing - bool parseSettings(CXmlElement& xmlConfigurationSettingsElement, CXmlSerializingContext& serializingContext); - void composeSettings(CXmlElement& xmlConfigurationSettingsElement, CXmlSerializingContext& serializingContext) const; - - // Serialization - virtual void binarySerialize(CBinaryStream& binaryStream); - - // Data size - virtual size_t getDataSize() const; + bool parseSettings(CXmlElement &xmlConfigurationSettingsElement, + CXmlDomainImportContext &context); + void composeSettings(CXmlElement &xmlConfigurationSettingsElement, + CXmlDomainExportContext &context) const; // Class kind virtual std::string getKind() const; private: - // Returns true if children dynamic creation is to be dealt with (here, will allow child deletion upon clean) + using AreaConfiguration = std::unique_ptr<CAreaConfiguration>; + using AreaConfigurations = std::list<AreaConfiguration>; + + // Returns true if children dynamic creation is to be dealt with (here, will allow child + // deletion upon clean) virtual bool childrenAreDynamic() const; // XML configuration settings serializing - bool serializeConfigurableElementSettings(CAreaConfiguration* pAreaConfiguration, CXmlElement& xmlConfigurableElementSettingsElement, CXmlSerializingContext& serializingContext, bool bSerializeOut); + bool importOneConfigurableElementSettings(CAreaConfiguration *areaConfiguration, + CXmlElement &xmlConfigurableElementSettingsElement, + CXmlDomainImportContext &context); + bool exportOneConfigurableElementSettings(CAreaConfiguration *areaConfiguration, + CXmlElement &xmlConfigurableElementSettingsElement, + CXmlDomainExportContext &context) const; // AreaConfiguration retrieval from configurable element - CAreaConfiguration* getAreaConfiguration(const CConfigurableElement* pConfigurableElement) const; - // AreaConfiguration retrieval from present area configurations - CAreaConfiguration* findAreaConfiguration(const std::string& strConfigurableElementPath) const; - // AreaConfiguration retrieval from given area configuration std::list - CAreaConfiguration* findAreaConfiguration(const std::string& strConfigurableElementPath, const std::list<CAreaConfiguration*>& areaConfigurationList) const; - // Area configuration ordering - void reorderAreaConfigurations(const std::list<CAreaConfiguration*>& areaConfigurationList); - // Find area configuration rank from regular std::list: for ordered std::list maintainance - uint32_t getAreaConfigurationRank(const CAreaConfiguration* pAreaConfiguration) const; - // Find area configuration from regular std::list based on rank: for ordered std::list maintainance - CAreaConfiguration* getAreaConfiguration(uint32_t uiAreaConfigurationRank) const; + const AreaConfiguration &getAreaConfiguration( + const CConfigurableElement *pConfigurableElement) const; + + /** + * Returns the AreaConfiguration iterator associated to the Element refered by its path + * @param[in] configurableElementPath to check if found in current list of areaconfigurations + * @return iterator on the configuration associated to the Element with the given path, + * last if not found + */ + AreaConfigurations::iterator findAreaConfigurationByPath( + const std::string &configurableElementPath); // Rule - const CCompoundRule* getRule() const; - CCompoundRule* getRule(); - void setRule(CCompoundRule* pRule); + const CCompoundRule *getRule() const; + CCompoundRule *getRule(); + void setRule(CCompoundRule *pRule); - // AreaConfigurations - std::list<CAreaConfiguration*> _areaConfigurationList; - std::list<CAreaConfiguration*> _orderedAreaConfigurationList; + AreaConfigurations mAreaConfigurationList; }; diff --git a/parameter/Element.cpp b/parameter/Element.cpp index afd1f33..77dfd9d 100644 --- a/parameter/Element.cpp +++ b/parameter/Element.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -30,7 +30,8 @@ #include "Element.h" #include "XmlElementSerializingContext.h" #include "ElementLibrary.h" -#include "ErrorContext.h" +#include "ErrorContext.hpp" +#include <algorithm> #include <assert.h> #include <stdio.h> #include <stdarg.h> @@ -40,7 +41,7 @@ using std::string; const std::string CElement::gDescriptionPropertyName = "Description"; -CElement::CElement(const string& strName) : _strName(strName), _pParent(NULL) +CElement::CElement(const string &strName) : _strName(strName) { } @@ -49,87 +50,12 @@ CElement::~CElement() removeChildren(); } -// Logging -void CElement::log_info(const char* strMessage, ...) const -{ - char *pacBuffer; - va_list listPointer; - - va_start(listPointer, strMessage); - - vasprintf(&pacBuffer, strMessage, listPointer); - - va_end(listPointer); - - if (pacBuffer != NULL) { - doLog(false, pacBuffer); - } - - free(pacBuffer); -} - -void CElement::log_warning(const char* strMessage, ...) const -{ - char *pacBuffer; - va_list listPointer; - - va_start(listPointer, strMessage); - - vasprintf(&pacBuffer, strMessage, listPointer); - - va_end(listPointer); - - if (pacBuffer != NULL) { - doLog(true, pacBuffer); - } - - free(pacBuffer); -} - -// Log each element of the string list -void CElement::log_table(bool bIsWarning, const std::list<string> lstrMessage) const -{ - std::list<string>::const_iterator iterator(lstrMessage.begin()); - std::list<string>::const_iterator end(lstrMessage.end()); - - while (iterator != end) { - // Log current list element - doLog(bIsWarning, iterator->c_str()); - ++iterator; - } -} - -void CElement::doLog(bool bIsWarning, const string& strLog) const -{ - assert(_pParent); - - // Propagate till root - _pParent->doLog(bIsWarning, strLog); -} - -void CElement::nestLog() const -{ - assert(_pParent); - - // Propagate till root - _pParent->nestLog(); -} - -void CElement::unnestLog() const -{ - assert(_pParent); - - // Propagate till root - _pParent->unnestLog(); -} - - -void CElement::setDescription(const string& strDescription) +void CElement::setDescription(const string &strDescription) { _strDescription = strDescription; } -const string& CElement::getDescription() const +const string &CElement::getDescription() const { return _strDescription; } @@ -140,15 +66,12 @@ bool CElement::childrenAreDynamic() const return false; } -bool CElement::init(string& strError) +bool CElement::init(string &strError) { - uint32_t uiIndex; - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + for (CElement *child : _childArray) { - CElement* pElement = _childArray[uiIndex];; - - if (!pElement->init(strError)) { + if (!child->init(strError)) { return false; } @@ -157,49 +80,48 @@ bool CElement::init(string& strError) return true; } -void CElement::dumpContent(string& strContent, CErrorContext& errorContext, const uint32_t uiDepth) const +string CElement::dumpContent(utility::ErrorContext &errorContext, const size_t depth) const { + string output; string strIndent; // Level - uint32_t uiNbIndents = uiDepth; + size_t indents = depth; - while (uiNbIndents--) { + while (indents--) { strIndent += " "; } // Type - strContent += strIndent + "- " + getKind(); + output += strIndent + "- " + getKind(); // Name if (!_strName.empty()) { - strContent += ": " + getName(); + output += ": " + getName(); } // Value - string strValue; - logValue(strValue, errorContext); + string strValue = logValue(errorContext); if (!strValue.empty()) { - strContent += " = " + strValue; + output += " = " + strValue; } - strContent += "\n"; - - uint32_t uiIndex; + output += "\n"; - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + for (CElement *pChild : _childArray) { - _childArray[uiIndex]->dumpContent(strContent, errorContext, uiDepth + 1); + output += pChild->dumpContent(errorContext, depth + 1); } + + return output; } // Element properties -void CElement::showProperties(string& strResult) const +void CElement::showProperties(string &strResult) const { - strResult = "\n"; strResult += "Kind: " + getKind() + "\n"; showDescriptionProperty(strResult); } @@ -212,28 +134,24 @@ void CElement::showDescriptionProperty(std::string &strResult) const } // Content dumping -void CElement::logValue(string& strValue, CErrorContext& errorContext) const +string CElement::logValue(utility::ErrorContext & /*ctx*/) const { - (void)strValue; - (void)errorContext; + return ""; } // From IXmlSink -bool CElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CElement::fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) { - setDescription(getXmlDescriptionAttribute(xmlElement)); + xmlElement.getAttribute(gDescriptionPropertyName, _strDescription); // Propagate through children CXmlElement::CChildIterator childIterator(xmlElement); - // Context - CXmlElementSerializingContext& elementSerializingContext = static_cast<CXmlElementSerializingContext&>(serializingContext); - CXmlElement childElement; while (childIterator.next(childElement)) { - CElement* pChild; + CElement *pChild; if (!childrenAreDynamic()) { @@ -241,7 +159,8 @@ bool CElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& se if (!pChild) { - elementSerializingContext.setError("Unable to handle XML element: " + childElement.getPath()); + serializingContext.setError("Unable to handle XML element: " + + childElement.getPath()); return false; } @@ -257,7 +176,7 @@ bool CElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& se } // Dig - if (!pChild->fromXml(childElement, elementSerializingContext)) { + if (!pChild->fromXml(childElement, serializingContext)) { return false; } @@ -266,48 +185,38 @@ bool CElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& se return true; } -void CElement::childrenToXml(CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) const +void CElement::childrenToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Browse children and propagate - size_t uiNbChildren = getNbChildren(); - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - const CElement* pChild = _childArray[uiChild]; + for (CElement *pChild : _childArray) { // Create corresponding child element CXmlElement xmlChildElement; - xmlElement.createChild(xmlChildElement, pChild->getKind()); + xmlElement.createChild(xmlChildElement, pChild->getXmlElementName()); // Propagate pChild->toXml(xmlChildElement, serializingContext); } } -void CElement::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CElement::toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const { setXmlNameAttribute(xmlElement); setXmlDescriptionAttribute(xmlElement); childrenToXml(xmlElement, serializingContext); } -void CElement::setXmlDescriptionAttribute(CXmlElement& xmlElement) const +void CElement::setXmlDescriptionAttribute(CXmlElement &xmlElement) const { const string &description = getDescription(); if (!description.empty()) { - xmlElement.setAttributeString(gDescriptionPropertyName, description); + xmlElement.setAttribute(gDescriptionPropertyName, description); } } -string CElement::getXmlDescriptionAttribute(const CXmlElement& xmlElement) const -{ - return xmlElement.getAttributeString(gDescriptionPropertyName); -} - -void CElement::setXmlNameAttribute(CXmlElement& xmlElement) const +void CElement::setXmlNameAttribute(CXmlElement &xmlElement) const { // By default, set Name attribute if any string strName = getName(); @@ -319,27 +228,22 @@ void CElement::setXmlNameAttribute(CXmlElement& xmlElement) const } // Name -void CElement::setName(const string& strName) +void CElement::setName(const string &strName) { _strName = strName; } -const string& CElement::getName() const +const string &CElement::getName() const { return _strName; } -bool CElement::rename(const string& strName, string& strError) +bool CElement::rename(const string &strName, string &strError) { // Check for conflict with brotherhood if relevant if (_pParent && _pParent->childrenAreDynamic()) { - size_t uiParentChild; - size_t uiParentNbChildren = _pParent->getNbChildren(); - - for (uiParentChild = 0; uiParentChild < uiParentNbChildren; uiParentChild++) { - - const CElement* pParentChild = _pParent->getChild(uiParentChild); + for (CElement *pParentChild : _pParent->_childArray) { if (pParentChild != this && pParentChild->getName() == strName) { @@ -368,41 +272,41 @@ string CElement::getPathName() const } // Hierarchy -void CElement::addChild(CElement* pChild) +void CElement::addChild(CElement *pChild) { _childArray.push_back(pChild); pChild->_pParent = this; } -CElement* CElement::getChild(size_t uiIndex) +CElement *CElement::getChild(size_t index) { - assert(uiIndex <= _childArray.size()); + assert(index <= _childArray.size()); - return _childArray[uiIndex]; + return _childArray[index]; } -const CElement* CElement::getChild(size_t uiIndex) const +const CElement *CElement::getChild(size_t index) const { - assert(uiIndex <= _childArray.size()); + assert(index <= _childArray.size()); - return _childArray[uiIndex]; + return _childArray[index]; } -CElement* CElement::createChild(const CXmlElement& childElement, - CXmlSerializingContext& serializingContext) +CElement *CElement::createChild(const CXmlElement &childElement, + CXmlSerializingContext &serializingContext) { // Context - CXmlElementSerializingContext& elementSerializingContext = - static_cast<CXmlElementSerializingContext&>(serializingContext); + CXmlElementSerializingContext &elementSerializingContext = + static_cast<CXmlElementSerializingContext &>(serializingContext); // Child needs creation - CElement* pChild = elementSerializingContext.getElementLibrary()->createElement(childElement); + CElement *pChild = elementSerializingContext.getElementLibrary()->createElement(childElement); if (!pChild) { - elementSerializingContext.setError( - "Unable to create XML element " + childElement.getPath()); + elementSerializingContext.setError("Unable to create XML element " + + childElement.getPath()); return NULL; } @@ -412,74 +316,50 @@ CElement* CElement::createChild(const CXmlElement& childElement, return pChild; } -bool CElement::removeChild(CElement* pChild) +bool CElement::removeChild(CElement *pChild) { - ChildArrayIterator it; - - for (it = _childArray.begin(); it != _childArray.end(); ++it) { + auto childIt = find(begin(_childArray), end(_childArray), pChild); + if (childIt != end(_childArray)) { - CElement* pElement = *it; - - if (pElement == pChild) { - - _childArray.erase(it); - - return true; - } + _childArray.erase(childIt); + return true; } return false; } -void CElement::listChildren(string& strChildList) const +void CElement::listChildren(string &strChildList) const { - strChildList = "\n"; - // Get list of children names - size_t uiNbChildren = getNbChildren(); - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - const CElement* pChild = _childArray[uiChild]; + for (CElement *pChild : _childArray) { strChildList += pChild->getName() + "\n"; } } -string CElement::listQualifiedPaths(bool bDive, uint32_t uiLevel) const +string CElement::listQualifiedPaths(bool bDive, size_t level) const { - size_t uiNbChildren = getNbChildren(); string strResult; // Dive Will cause only leaf nodes to be printed - if (!bDive || !uiNbChildren) { + if (!bDive || !getNbChildren()) { strResult = getQualifiedPath() + "\n"; } - if (bDive || !uiLevel) { + if (bDive || !level) { // Get list of children paths - size_t uiChild; + for (CElement *pChild : _childArray) { - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - const CElement* pChild = _childArray[uiChild]; - - strResult += pChild->listQualifiedPaths(bDive, uiLevel + 1); + strResult += pChild->listQualifiedPaths(bDive, level + 1); } } return strResult; } -void CElement::listChildrenPaths(string& strChildList) const +void CElement::listChildrenPaths(string &strChildList) const { // Get list of children paths - size_t uiNbChildren = getNbChildren(); - size_t uiChild; - - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - - const CElement* pChild = _childArray[uiChild]; + for (CElement *pChild : _childArray) { strChildList += pChild->getPath() + "\n"; } @@ -490,12 +370,12 @@ size_t CElement::getNbChildren() const return _childArray.size(); } -const CElement* CElement::getParent() const +const CElement *CElement::getParent() const { return _pParent; } -CElement* CElement::getParent() +CElement *CElement::getParent() { return _pParent; } @@ -507,11 +387,9 @@ void CElement::clean() removeChildren(); } else { // Just propagate - uint32_t uiIndex; - - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + for (CElement *pChild : _childArray) { - _childArray[uiIndex]->clean(); + pChild->clean(); } } } @@ -528,16 +406,16 @@ void CElement::removeChildren() _childArray.clear(); } -const CElement* CElement::findDescendant(CPathNavigator& pathNavigator) const +const CElement *CElement::findDescendant(CPathNavigator &pathNavigator) const { - string* pStrChildName = pathNavigator.next(); + string *pStrChildName = pathNavigator.next(); if (!pStrChildName) { return this; } - const CElement* pChild = findChild(*pStrChildName); + const CElement *pChild = findChild(*pStrChildName); if (!pChild) { @@ -547,16 +425,16 @@ const CElement* CElement::findDescendant(CPathNavigator& pathNavigator) const return pChild->findDescendant(pathNavigator); } -CElement* CElement::findDescendant(CPathNavigator& pathNavigator) +CElement *CElement::findDescendant(CPathNavigator &pathNavigator) { - string* pStrChildName = pathNavigator.next(); + string *pStrChildName = pathNavigator.next(); if (!pStrChildName) { return this; } - CElement* pChild = findChild(*pStrChildName); + CElement *pChild = findChild(*pStrChildName); if (!pChild) { @@ -566,7 +444,7 @@ CElement* CElement::findDescendant(CPathNavigator& pathNavigator) return pChild->findDescendant(pathNavigator); } -bool CElement::isDescendantOf(const CElement* pCandidateAscendant) const +bool CElement::isDescendantOf(const CElement *pCandidateAscendant) const { if (!_pParent) { @@ -579,68 +457,52 @@ bool CElement::isDescendantOf(const CElement* pCandidateAscendant) const return _pParent->isDescendantOf(pCandidateAscendant); } -CElement* CElement::findChild(const string& strName) +CElement *CElement::findChild(const string &strName) { - uint32_t uiIndex; - - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + for (CElement *pChild : _childArray) { - CElement* pElement = _childArray[uiIndex]; + if (pChild->getPathName() == strName) { - if (pElement->getPathName() == strName) { - - return pElement; + return pChild; } } return NULL; } -const CElement* CElement::findChild(const string& strName) const +const CElement *CElement::findChild(const string &strName) const { - uint32_t uiIndex; - - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + for (CElement *pChild : _childArray) { - const CElement* pElement = _childArray[uiIndex]; + if (pChild->getPathName() == strName) { - if (pElement->getPathName() == strName) { - - return pElement; + return pChild; } } return NULL; } -CElement* CElement::findChildOfKind(const string& strKind) +CElement *CElement::findChildOfKind(const string &strKind) { - uint32_t uiIndex; - - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { - - CElement* pElement = _childArray[uiIndex]; + for (CElement *pChild : _childArray) { - if (pElement->getKind() == strKind) { + if (pChild->getKind() == strKind) { - return pElement; + return pChild; } } return NULL; } -const CElement* CElement::findChildOfKind(const string& strKind) const +const CElement *CElement::findChildOfKind(const string &strKind) const { - uint32_t uiIndex; + for (CElement *pChild : _childArray) { - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { + if (pChild->getKind() == strKind) { - const CElement* pElement = _childArray[uiIndex];; - - if (pElement->getKind() == strKind) { - - return pElement; + return pChild; } } @@ -662,41 +524,8 @@ string CElement::getQualifiedPath() const return getPath() + " [" + getKind() + "]"; } -uint32_t CElement::getDepth() const -{ - if (_pParent) { - - return _pParent->getDepth() + 1; - } - - return 0; -} - -// Checksum for integrity checks -uint8_t CElement::computeStructureChecksum() const +string CElement::getXmlElementName() const { - // Base checksum computation on element kind - string strKind = getKind(); - - // Get element kind - const char* pcData = strKind.c_str(); - - // Cumulate - uint8_t uiChecksum = 0; - - while (*pcData) { - - uiChecksum += *pcData++; - } - - // Propagate - uint32_t uiIndex; - for (uiIndex = 0; uiIndex < _childArray.size(); uiIndex++) { - - const CElement* pChild = _childArray[uiIndex]; - - uiChecksum += pChild->computeStructureChecksum(); - } - - return uiChecksum; + // Default to element kind + return getKind(); } diff --git a/parameter/Element.h b/parameter/Element.h index d3844e6..11d41b5 100644 --- a/parameter/Element.h +++ b/parameter/Element.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,89 +29,87 @@ */ #pragma once +#include "parameter_export.h" + #include <string> #include <vector> #include <stdint.h> -#include <list> #include "XmlSink.h" #include "XmlSource.h" #include "PathNavigator.h" class CXmlElementSerializingContext; -class CErrorContext; +namespace utility +{ +class ErrorContext; +} -class CElement : public IXmlSink, public IXmlSource +class PARAMETER_EXPORT CElement : public IXmlSink, public IXmlSource { - friend class CAutoLog; public: - CElement(const std::string& strName = ""); + CElement(const std::string &strName = ""); virtual ~CElement(); - // Logging - void log_info(const char* strMessage, ...) const; - void log_warning(const char* strMessage, ...) const; - void log_table(bool bIsWarning, const std::list<std::string> lstrMessage) const; - // Description - void setDescription(const std::string& strDescription); - const std::string& getDescription() const; + void setDescription(const std::string &strDescription); + const std::string &getDescription() const; // Name / Path - const std::string& getName() const; - void setName(const std::string& strName); - bool rename(const std::string& strName, std::string& strError); + const std::string &getName() const; + void setName(const std::string &strName); + bool rename(const std::string &strName, std::string &strError); std::string getPath() const; std::string getQualifiedPath() const; // Creation / build - virtual bool init(std::string& strError); + virtual bool init(std::string &strError); virtual void clean(); // Children management - void addChild(CElement* pChild); - bool removeChild(CElement* pChild); - void listChildren(std::string& strChildList) const; - std::string listQualifiedPaths(bool bDive, uint32_t uiLevel = 0) const; - void listChildrenPaths(std::string& strChildPathList) const; + void addChild(CElement *pChild); + bool removeChild(CElement *pChild); + void listChildren(std::string &strChildList) const; + std::string listQualifiedPaths(bool bDive, size_t level = 0) const; + void listChildrenPaths(std::string &strChildPathList) const; // Hierarchy query size_t getNbChildren() const; - CElement* findChildOfKind(const std::string& strKind); - const CElement* findChildOfKind(const std::string& strKind) const; - const CElement* getParent() const; + CElement *findChildOfKind(const std::string &strKind); + const CElement *findChildOfKind(const std::string &strKind) const; + const CElement *getParent() const; /** * Get a child element (const) * * Note: this method will assert if given a wrong child index (>= number of children) * - * @param[in] uiIndex the index of the child element from 0 to number of children - 1 + * @param[in] index the index of the child element from 0 to number of children - 1 * @return the child element */ - const CElement* getChild(size_t uiIndex) const; + const CElement *getChild(size_t index) const; /** * Get a child element * * Note: this method will assert if given a wrong child index (>= number of children) * - * @param[in] uiIndex the index of the child element from 0 to number of children - 1 + * @param[in] index the index of the child element from 0 to number of children - 1 * @return the child element */ - CElement* getChild(size_t uiIndex); + CElement *getChild(size_t index); - const CElement* findChild(const std::string& strName) const; - CElement* findChild(const std::string& strName); - const CElement* findDescendant(CPathNavigator& pathNavigator) const; - CElement* findDescendant(CPathNavigator& pathNavigator); - bool isDescendantOf(const CElement* pCandidateAscendant) const; + const CElement *findChild(const std::string &strName) const; + CElement *findChild(const std::string &strName); + const CElement *findDescendant(CPathNavigator &pathNavigator) const; + CElement *findDescendant(CPathNavigator &pathNavigator); + bool isDescendantOf(const CElement *pCandidateAscendant) const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; /** * Serialize the children to XML @@ -124,17 +122,14 @@ public: * object upon which this method is called) * @param[in,out] serializingContext information about the serialization */ - virtual void childrenToXml(CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) const; + virtual void childrenToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const; // Content structure dump - void dumpContent(std::string& strContent, CErrorContext& errorContext, const uint32_t uiDepth = 0) const; + std::string dumpContent(utility::ErrorContext &errorContext, const size_t depth = 0) const; // Element properties - virtual void showProperties(std::string& strResult) const; - - // Checksum for integrity checks - uint8_t computeStructureChecksum() const; + virtual void showProperties(std::string &strResult) const; // Class kind virtual std::string getKind() const = 0; @@ -144,16 +139,7 @@ public: * * @param[in,out] xmlElement to fill with the description */ - void setXmlDescriptionAttribute(CXmlElement& xmlElement) const; - - /** - * Extract the Description field from the Xml Element during XML decomposing. - * - * @param[in] xmlElement to extract the description from. - * - * @return description represented as a string, empty if not found - */ - std::string getXmlDescriptionAttribute(const CXmlElement &xmlElement) const; + void setXmlDescriptionAttribute(CXmlElement &xmlElement) const; /** * Appends if found human readable description property. @@ -162,12 +148,17 @@ public: */ void showDescriptionProperty(std::string &strResult) const; + /** + * Returns Xml element name used for element XML importing/exporting functionalities + */ + virtual std::string getXmlElementName() const; + protected: // Content dumping - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + virtual std::string logValue(utility::ErrorContext &errorContext) const; // Hierarchy - CElement* getParent(); + CElement *getParent(); /** * Creates a child CElement from a child XML Element @@ -177,24 +168,20 @@ protected: * * @return child a pointer on the CElement object that has been added to the tree */ - CElement* createChild(const CXmlElement& childElement, - CXmlSerializingContext& elementSerializingContext); + CElement *createChild(const CXmlElement &childElement, + CXmlSerializingContext &elementSerializingContext); + + static const std::string gDescriptionPropertyName; private: - // Logging (done by root) - virtual void doLog(bool bIsWarning, const std::string& strLog) const; - virtual void nestLog() const; - virtual void unnestLog() const; // Returns Name or Kind if no Name std::string getPathName() const; // Returns true if children dynamic creation is to be dealt with virtual bool childrenAreDynamic() const; // House keeping void removeChildren(); - // For logging - uint32_t getDepth() const; // Fill XmlElement during XML composing - void setXmlNameAttribute(CXmlElement& xmlElement) const; + void setXmlNameAttribute(CXmlElement &xmlElement) const; // Name std::string _strName; @@ -203,12 +190,10 @@ private: std::string _strDescription; // Child iterators - typedef std::vector<CElement*>::iterator ChildArrayIterator; - typedef std::vector<CElement*>::reverse_iterator ChildArrayReverseIterator; + typedef std::vector<CElement *>::iterator ChildArrayIterator; + typedef std::vector<CElement *>::reverse_iterator ChildArrayReverseIterator; // Children - std::vector<CElement*> _childArray; + std::vector<CElement *> _childArray; // Parent - CElement* _pParent; - - static const std::string gDescriptionPropertyName; + CElement *_pParent{nullptr}; }; diff --git a/parameter/ElementBuilder.h b/parameter/ElementBuilder.h index 819387f..ff1ae0a 100644 --- a/parameter/ElementBuilder.h +++ b/parameter/ElementBuilder.h @@ -30,11 +30,12 @@ #pragma once #include "Element.h" +#include <NonCopyable.hpp> -class CElementBuilder +class CElementBuilder : private utility::NonCopyable { public: - virtual ~CElementBuilder() {} + virtual ~CElementBuilder() = default; - virtual CElement* createElement(const CXmlElement& xmlElement) const = 0; + virtual CElement *createElement(const CXmlElement &xmlElement) const = 0; }; diff --git a/parameter/ElementBuilderTemplate.h b/parameter/ElementBuilderTemplate.h index 0fb1212..8f7c44f 100644 --- a/parameter/ElementBuilderTemplate.h +++ b/parameter/ElementBuilderTemplate.h @@ -35,10 +35,5 @@ template <class ElementType> class TElementBuilderTemplate : public CElementBuilder { public: - - virtual CElement* createElement(const CXmlElement& xmlElement) const - { - (void)xmlElement; - return new ElementType; - } + virtual CElement *createElement(const CXmlElement & /*elem*/) const { return new ElementType; } }; diff --git a/parameter/ElementHandle.cpp b/parameter/ElementHandle.cpp new file mode 100644 index 0000000..ecf1bcf --- /dev/null +++ b/parameter/ElementHandle.cpp @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "ElementHandle.h" +#include "ParameterAccessContext.h" +#include "BaseParameter.h" +#include "XmlParameterSerializingContext.h" +#include "Subsystem.h" +#include <assert.h> +#include "ParameterMgr.h" + +#include <mutex> + +using std::string; +using std::mutex; +using std::lock_guard; + +/** @return 0 by default, ie for non overloaded types. */ +template <class T> +static size_t getUserInputSize(const T & /*scalar*/) +{ + return 0; +} + +/** @return the vector's size. */ +template <class T> +static size_t getUserInputSize(const std::vector<T> &vector) +{ + return vector.size(); +} + +ElementHandle::ElementHandle(CConfigurableElement &element, CParameterMgr ¶meterMgr) + : mElement(element), mParameterMgr(parameterMgr) +{ +} + +string ElementHandle::getName() const +{ + return mElement.getName(); +} + +size_t ElementHandle::getSize() const +{ + return mElement.getFootPrint(); +} + +bool ElementHandle::isParameter() const +{ + return mElement.isParameter(); +} + +string ElementHandle::getDescription() const +{ + return mElement.getDescription(); +} + +// Parameter features +bool ElementHandle::isRogue() const +{ + return mElement.isRogue(); +} + +bool ElementHandle::isArray() const +{ + return getArrayLength() != 0; +} + +size_t ElementHandle::getArrayLength() const +{ + // Only instances can be arrays, SystemClass can not, nor subsystems + auto *instance = dynamic_cast<CInstanceConfigurableElement *>(&mElement); + if (instance == nullptr) { + return 0; + } + return instance->getArrayLength(); +} + +string ElementHandle::getPath() const +{ + return mElement.getPath(); +} + +string ElementHandle::getKind() const +{ + return mElement.getKind(); +} + +std::vector<ElementHandle> ElementHandle::getChildren() +{ + size_t nbChildren = mElement.getNbChildren(); + + std::vector<ElementHandle> children; + children.reserve(nbChildren); + + for (size_t childIndex = 0; childIndex < nbChildren; ++childIndex) { + auto *child = static_cast<CConfigurableElement *>(mElement.getChild(childIndex)); + // Can not use emplace back as the constructor is private + children.push_back({*child, mParameterMgr}); + } + return children; +} + +bool ElementHandle::getMappingData(const string &strKey, string &strValue) const +{ + const std::string *pStrValue; + + // Seach for the key in self and ancestors + auto elements = mElement.getConfigurableElementContext(); + + for (auto *element : elements) + if (element->getMappingData(strKey, pStrValue)) { + strValue = *pStrValue; + return true; + } + + return false; +} + +bool ElementHandle::getStructureAsXML(std::string &xmlSettings, std::string &error) const +{ + // Use default access context for structure export + CParameterAccessContext accessContext(error); + return mParameterMgr.exportElementToXMLString( + &mElement, mElement.getXmlElementName(), + CXmlParameterSerializingContext{accessContext, error}, xmlSettings); +} + +template <class T> +struct isVector : std::false_type +{ +}; +template <class T> +struct isVector<std::vector<T>> : std::true_type +{ +}; + +bool ElementHandle::getAsXML(std::string &xmlValue, std::string &error) const +{ + std::string result; + if (not mParameterMgr.getSettingsAsXML(&mElement, result)) { + error = result; + return false; + } + + xmlValue = result; + return true; +} + +bool ElementHandle::setAsXML(const std::string &xmlValue, std::string &error) +{ + return mParameterMgr.setSettingsAsXML(&mElement, xmlValue, error); +} + +bool ElementHandle::getAsBytes(std::vector<uint8_t> &bytesValue, std::string & /*error*/) const +{ + mParameterMgr.getSettingsAsBytes(mElement, bytesValue); + + // Currently this operation can not fail. + // Nevertheless this is more a design than intrinsic property. + // Use the same error reporting pattern to avoid breaking the api in future + // release if an error need to be reported (and be consistent with all other getAs*). + return true; +} + +bool ElementHandle::setAsBytes(const std::vector<uint8_t> &bytesValue, std::string &error) +{ + return mParameterMgr.setSettingsAsBytes(mElement, bytesValue, error); +} + +template <class T> +bool ElementHandle::setAs(const T value, string &error) const +{ + if (not checkSetValidity(getUserInputSize(value), error)) { + return false; + } + // Safe downcast thanks to isParameter check in checkSetValidity + auto ¶meter = static_cast<CBaseParameter &>(mElement); + + // When in tuning mode, silently skip "set" requests + if (mParameterMgr.tuningModeOn()) { + + return true; + } + + CParameterAccessContext parameterAccessContext(error, mParameterMgr.getParameterBlackboard()); + + // BaseParamere::access takes a non-const argument - therefore we need to + // copy the value + T copy = value; + + // Ensure we're safe against blackboard foreign access + lock_guard<mutex> autoLock(mParameterMgr.getBlackboardMutex()); + + return parameter.access(copy, true, parameterAccessContext); +} + +template <class T> +bool ElementHandle::getAs(T &value, string &error) const +{ + if (not checkGetValidity(isVector<T>::value, error)) { + return false; + } + // Safe downcast thanks to isParameter check in checkGetValidity + auto ¶meter = static_cast<const CBaseParameter &>(mElement); + + // Ensure we're safe against blackboard foreign access + lock_guard<mutex> autoLock(mParameterMgr.getBlackboardMutex()); + + CParameterAccessContext parameterAccessContext(error, mParameterMgr.getParameterBlackboard()); + + return parameter.access(value, false, parameterAccessContext); +} + +// Boolean access +bool ElementHandle::setAsBoolean(bool value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsBoolean(bool &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::setAsBooleanArray(const std::vector<bool> &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsBooleanArray(std::vector<bool> &value, string &error) const +{ + return getAs(value, error); +} + +// Integer Access +bool ElementHandle::setAsInteger(uint32_t value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsInteger(uint32_t &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::setAsIntegerArray(const std::vector<uint32_t> &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsIntegerArray(std::vector<uint32_t> &value, string &error) const +{ + return getAs(value, error); +} + +// Signed Integer Access +bool ElementHandle::setAsSignedInteger(int32_t value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsSignedInteger(int32_t &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::setAsSignedIntegerArray(const std::vector<int32_t> &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsSignedIntegerArray(std::vector<int32_t> &value, string &error) const +{ + return getAs(value, error); +} + +// Double Access +bool ElementHandle::setAsDouble(double value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsDouble(double &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::setAsDoubleArray(const std::vector<double> &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsDoubleArray(std::vector<double> &value, string &error) const +{ + return getAs(value, error); +} + +// String Access +bool ElementHandle::setAsString(const string &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsString(string &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::setAsStringArray(const std::vector<string> &value, string &error) +{ + return setAs(value, error); +} + +bool ElementHandle::getAsStringArray(std::vector<string> &value, string &error) const +{ + return getAs(value, error); +} + +bool ElementHandle::checkGetValidity(bool asArray, string &error) const +{ + if (not isParameter()) { + error = "Can not set element " + getPath() + " as it is not a parameter."; + return false; + } + + if (asArray != isArray()) { + + auto toStr = [](bool array) { return array ? "an array" : "a scalar"; }; + error = "Can not get \"" + getPath() + "\" as " + toStr(asArray) + " because it is " + + toStr(isArray()); + return false; + } + + return true; +} + +// Access validity +bool ElementHandle::checkSetValidity(size_t arrayLength, string &error) const +{ + // Settings a parameter necessitates the right to get it + if (not checkGetValidity(arrayLength != 0, error)) { + return false; + } + + if (!isRogue()) { + + error = "Can not set parameter \"" + getPath() + "\" as it is not rogue."; + return false; + } + + if (arrayLength && (arrayLength != getArrayLength())) { + + using std::to_string; + error = "Array length mismatch for \"" + getPath() + "\", expected: " + + to_string(getArrayLength()) + ", got: " + to_string(arrayLength); + return false; + } + + return true; +} diff --git a/parameter/ElementLibrary.cpp b/parameter/ElementLibrary.cpp index 7709f0c..bde9b91 100644 --- a/parameter/ElementLibrary.cpp +++ b/parameter/ElementLibrary.cpp @@ -30,11 +30,6 @@ #include "ElementLibrary.h" #include "ElementBuilder.h" - -CElementLibrary::CElementLibrary() -{ -} - CElementLibrary::~CElementLibrary() { clean(); @@ -51,7 +46,7 @@ void CElementLibrary::clean() _elementBuilderMap.clear(); } -CElement* CElementLibrary::createElement(const CXmlElement& xmlElement) const +CElement *CElementLibrary::createElement(const CXmlElement &xmlElement) const { ElementBuilderMapConstIterator it = _elementBuilderMap.find(getBuilderType(xmlElement)); @@ -62,12 +57,13 @@ CElement* CElementLibrary::createElement(const CXmlElement& xmlElement) const return NULL; } -void CElementLibrary::addElementBuilder(const std::string& type, const CElementBuilder *pElementBuilder) +void CElementLibrary::addElementBuilder(const std::string &type, + const CElementBuilder *pElementBuilder) { _elementBuilderMap[type] = pElementBuilder; } -std::string CElementLibrary::getBuilderType(const CXmlElement& xmlElement) const +std::string CElementLibrary::getBuilderType(const CXmlElement &xmlElement) const { // Defaulting to xml element name return xmlElement.getType(); diff --git a/parameter/ElementLibrary.h b/parameter/ElementLibrary.h index e50be95..943fc8a 100644 --- a/parameter/ElementLibrary.h +++ b/parameter/ElementLibrary.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,6 +29,8 @@ */ #pragma once +#include "parameter_export.h" + #include <map> #include <string> @@ -36,31 +38,30 @@ class CElementBuilder; -class CElementLibrary +class PARAMETER_EXPORT CElementLibrary { - typedef std::map<std::string, const CElementBuilder*> ElementBuilderMap; + typedef std::map<std::string, const CElementBuilder *> ElementBuilderMap; typedef ElementBuilderMap::iterator ElementBuilderMapIterator; typedef ElementBuilderMap::const_iterator ElementBuilderMapConstIterator; public: - CElementLibrary(); virtual ~CElementLibrary(); /** Add a xml tag and it's corresponding builder in the library. * - * @param[in] xmlTag is the tag of an xml element that can be given to the builder to - * create a new element. + * @param[in] type is the tag of an xml element that can be given to the builder to + * create a new element. * @param[in] pElementBuilder is the tag associated element builder. */ - void addElementBuilder(const std::string& type, const CElementBuilder *pElementBuilder); + void addElementBuilder(const std::string &type, const CElementBuilder *pElementBuilder); void clean(); // Instantiation - CElement* createElement(const CXmlElement& xmlElement) const; + CElement *createElement(const CXmlElement &xmlElement) const; private: // Builder type - virtual std::string getBuilderType(const CXmlElement& xmlElement) const; + virtual std::string getBuilderType(const CXmlElement &xmlElement) const; // Builders ElementBuilderMap _elementBuilderMap; diff --git a/parameter/ElementLibrarySet.cpp b/parameter/ElementLibrarySet.cpp index e420d8c..1eaa2c5 100644 --- a/parameter/ElementLibrarySet.cpp +++ b/parameter/ElementLibrarySet.cpp @@ -30,28 +30,23 @@ #include "ElementLibrarySet.h" #include <assert.h> -CElementLibrarySet::CElementLibrarySet() -{ -} - CElementLibrarySet::~CElementLibrarySet() { - uint32_t uiIndex; - - for (uiIndex = 0; uiIndex < _elementLibraryArray.size(); uiIndex++) { + // FIXME: use an array of unique_ptr + for (auto *elementLibrary : _elementLibraryArray) { - delete _elementLibraryArray[uiIndex]; + delete elementLibrary; } } -void CElementLibrarySet::addElementLibrary(CElementLibrary* pElementLibrary) +void CElementLibrarySet::addElementLibrary(CElementLibrary *pElementLibrary) { _elementLibraryArray.push_back(pElementLibrary); } -CElementLibrary* CElementLibrarySet::getElementLibrary(uint32_t uiIndex) const +CElementLibrary *CElementLibrarySet::getElementLibrary(size_t index) const { - assert(uiIndex <= _elementLibraryArray.size()); + assert(index <= _elementLibraryArray.size()); - return _elementLibraryArray[uiIndex]; + return _elementLibraryArray[index]; } diff --git a/parameter/ElementLibrarySet.h b/parameter/ElementLibrarySet.h index cdcfdfe..d92ace9 100644 --- a/parameter/ElementLibrarySet.h +++ b/parameter/ElementLibrarySet.h @@ -34,13 +34,11 @@ class CElementLibrarySet { public: - CElementLibrarySet(); ~CElementLibrarySet(); - void addElementLibrary(CElementLibrary* pElementLibrary); - CElementLibrary* getElementLibrary(uint32_t uiIndex) const; + void addElementLibrary(CElementLibrary *pElementLibrary); + CElementLibrary *getElementLibrary(size_t index) const; private: - typedef std::vector<CElementLibrary*>::iterator CElementLibraryArrayIterator; - std::vector<CElementLibrary*> _elementLibraryArray; + std::vector<CElementLibrary *> _elementLibraryArray; }; diff --git a/parameter/ElementLocator.cpp b/parameter/ElementLocator.cpp index 4c2fa99..b7721b3 100644 --- a/parameter/ElementLocator.cpp +++ b/parameter/ElementLocator.cpp @@ -32,12 +32,13 @@ using std::string; -CElementLocator::CElementLocator(CElement* pSubRootElement, bool bStrict) : _pSubRootElement(pSubRootElement), _bStrict(bStrict) +CElementLocator::CElementLocator(CElement *pSubRootElement, bool bStrict) + : _pSubRootElement(pSubRootElement), _bStrict(bStrict) { } // Locate element -bool CElementLocator::locate(const string& strPath, CElement** ppElement, string& strError) +bool CElementLocator::locate(const string &strPath, CElement **ppElement, string &strError) { CPathNavigator pathNavigator(strPath); @@ -49,7 +50,7 @@ bool CElementLocator::locate(const string& strPath, CElement** ppElement, string } // Sub root element? - string* pStrChildName = pathNavigator.next(); + string *pStrChildName = pathNavigator.next(); if (!pStrChildName) { @@ -82,4 +83,3 @@ bool CElementLocator::locate(const string& strPath, CElement** ppElement, string return true; } - diff --git a/parameter/ElementLocator.h b/parameter/ElementLocator.h index c35eb5c..eca6fa9 100644 --- a/parameter/ElementLocator.h +++ b/parameter/ElementLocator.h @@ -36,16 +36,15 @@ class CElementLocator { public: - CElementLocator(CElement* pSubRootElement, bool bStrict = true); + CElementLocator(CElement *pSubRootElement, bool bStrict = true); // Locate element - bool locate(const std::string& strPath, CElement** ppElement, std::string& strError); + bool locate(const std::string &strPath, CElement **ppElement, std::string &strError); private: // Subroot element - CElement* _pSubRootElement; + CElement *_pSubRootElement; // Strict means empty path will cause path not found error to be returned bool _bStrict; }; - diff --git a/parameter/EnumParameterType.cpp b/parameter/EnumParameterType.cpp index 147ee95..6eea694 100644 --- a/parameter/EnumParameterType.cpp +++ b/parameter/EnumParameterType.cpp @@ -28,21 +28,15 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "EnumParameterType.h" -#include <stdlib.h> -#include <sstream> -#include <iomanip> -#include <ctype.h> -#include <assert.h> -#include "ParameterAccessContext.h" #include "EnumValuePair.h" -#include "Utility.h" -#include <errno.h> +#include "ParameterAccessContext.h" +#include "convert.hpp" #define base CParameterType using std::string; -CEnumParameterType::CEnumParameterType(const string& strName) : base(strName) +CEnumParameterType::CEnumParameterType(const string &strName) : base(strName) { } @@ -57,7 +51,7 @@ bool CEnumParameterType::childrenAreDynamic() const } // Element properties -void CEnumParameterType::showProperties(string& strResult) const +void CEnumParameterType::showProperties(string &strResult) const { base::showProperties(strResult); @@ -69,7 +63,7 @@ void CEnumParameterType::showProperties(string& strResult) const for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CEnumValuePair* pValuePair = static_cast<const CEnumValuePair*>(getChild(uiChild)); + const CEnumValuePair *pValuePair = static_cast<const CEnumValuePair *>(getChild(uiChild)); strResult += "\tLiteral: \""; strResult += pValuePair->getName(); @@ -79,182 +73,108 @@ void CEnumParameterType::showProperties(string& strResult) const } } -bool CEnumParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CEnumParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Size in bits - uint32_t uiSizeInBits = xmlElement.getAttributeInteger("Size"); + size_t sizeInBits = 0; + if (not xmlElement.getAttribute("Size", sizeInBits)) { + return false; + } // Size - setSize(uiSizeInBits / 8); + setSize(sizeInBits / 8); // Base return base::fromXml(xmlElement, serializingContext); } // Conversion (tuning) -bool CEnumParameterType::toBlackboard(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CEnumParameterType::toBlackboard(const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - int64_t iData; - - if (isNumber(strValue)) { - - /// Numerical value provided - - // Hexa - bool bValueProvidedAsHexa = !strValue.compare(0, 2, "0x"); - - errno = 0; - char *pcStrEnd; - - // Get value - iData = strtoll(strValue.c_str(), &pcStrEnd, 0); - - // Conversion error when the input string does not contain any digit or the number is out of range (int32_t type) - bool bConversionSucceeded = !errno && (strValue.c_str() != pcStrEnd); - - // Check validity against type - if (!checkValueAgainstRange(strValue, iData, parameterAccessContext, bValueProvidedAsHexa, bConversionSucceeded)) { - - return false; - } - - if (bValueProvidedAsHexa) { - - // Sign extend - signExtend(iData); - } + int32_t iParsedUserValue = 0; - // Check validity against lexical space - string strError; - if (!isValid(iData, parameterAccessContext)) { + // Try to read the user-provided string as an integer + if (not convertTo(strValue, iParsedUserValue)) { + // If it fails to parse as an integer, first try to convert it from + // lexical to numerical space. + int32_t iNumerical; + if (not getNumerical(strValue, iNumerical)) { - parameterAccessContext.setError(strError); - - return false; - } - } else { - /// Literal value provided - - // Check validity against lexical space - int iNumerical; - if (!getNumerical(strValue, iNumerical)) { - - parameterAccessContext.setError("Provided value not part of lexical space"); - - return false; - } - iData = iNumerical; - - // Check validity against type - if (!checkValueAgainstRange(strValue, iData, parameterAccessContext, false, isEncodable((uint64_t)iData, true))) { + parameterAccessContext.setError("Provided value '" + strValue + + "' is not part of the lexical space" + " or not within the numerical range."); return false; } + iParsedUserValue = iNumerical; } - // Return data - uiValue = (uint32_t)iData; - - return true; + // Once it has been converted to a number (either through parsing or + // through lexical->numerical conversion), call the numerical overload of + // toBlackboard. + return toBlackboard(iParsedUserValue, uiValue, parameterAccessContext); } -// Range checking -bool CEnumParameterType::checkValueAgainstRange(const string& strValue, int64_t value, CParameterAccessContext& parameterAccessContext, bool bHexaValue, bool bConversionSucceeded) const +int32_t CEnumParameterType::getMin() const { // Enums are always signed, it means we have one less util bit - int64_t maxValue = getMaxValue<uint64_t>(); - int64_t minValue = -maxValue - 1; - - if (!bConversionSucceeded || value < minValue || value > maxValue) { - - std::ostringstream strStream; - - strStream << "Value " << strValue << " standing out of admitted range ["; - - if (bHexaValue) { - - // Format Min - strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(minValue); - // Format Max - strStream << ", 0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(maxValue); - - } else { - - strStream << minValue << ", " << maxValue; - } - - strStream << "] for " << getKind(); - - parameterAccessContext.setError(strStream.str()); - - return false; - } - return true; + return -getMax() - 1; } -bool CEnumParameterType::fromBlackboard(string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +int32_t CEnumParameterType::getMax() const { - // Take care of format - if (parameterAccessContext.valueSpaceIsRaw()) { - - // Format - std::ostringstream strStream; - - // Numerical format requested - if (parameterAccessContext.outputRawFormatIsHex()) { - - // Hexa display with unecessary bits cleared out - strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(uiValue); - - strValue = strStream.str(); - } else { - - // Integer display - int32_t iValue = uiValue; - - // Sign extend - signExtend(iValue); + return getMaxValue<int32_t>(); +} - strStream << iValue; +bool CEnumParameterType::fromBlackboard(string &userValue, const uint32_t &value, + CParameterAccessContext & /*ctx*/) const +{ + // Convert the raw value from the blackboard + int32_t signedValue = static_cast<int32_t>(value); + signExtend(signedValue); - strValue = strStream.str(); - } - } else { + // Convert from numerical space to literal space + return getLiteral(signedValue, userValue); +} - // Integer display - int32_t iValue = uiValue; +// Value access +bool CEnumParameterType::toBlackboard(int32_t userValue, uint32_t &value, + CParameterAccessContext ¶meterAccessContext) const +{ + if (!checkValueAgainstSpace(userValue)) { - // Sign extend - signExtend(iValue); + parameterAccessContext.setError(std::to_string(userValue) + + " is not part of numerical space."); - // Literal display requested (should succeed) - getLiteral(iValue, strValue); + return false; } - return true; -} -// Value access -bool CEnumParameterType::toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const -{ - if (!isValid(iUserValue, parameterAccessContext)) { + if (userValue < getMin() or userValue > getMax()) { + // FIXME: values provided as hexa (either on command line or in a config + // file will appear in decimal base instead of hexa base... + parameterAccessContext.setError( + "Value " + std::to_string(userValue) + " standing out of admitted range [" + + std::to_string(getMin()) + ", " + std::to_string(getMax()) + "] for " + getKind()); return false; } - uiValue = iUserValue; + + value = static_cast<uint32_t>(userValue); return true; } -bool CEnumParameterType::fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CEnumParameterType::fromBlackboard(int32_t &userValue, uint32_t value, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - - int32_t iValue = uiValue; + int32_t signedValue = static_cast<int32_t>(value); // Sign extend - signExtend(iValue); + signExtend(signedValue); - iUserValue = iValue; + userValue = signedValue; return true; } @@ -268,26 +188,18 @@ uint32_t CEnumParameterType::getDefaultValue() const } // Return first available numerical - return static_cast<const CEnumValuePair*>(getChild(0))->getNumerical(); -} - -// Check string is a number -bool CEnumParameterType::isNumber(const string& strValue) -{ - char cFirst = strValue[0]; - - return isdigit(cFirst) || cFirst == '+' || cFirst == '-'; + return static_cast<const CEnumValuePair *>(getChild(0))->getNumerical(); } // Literal - numerical conversions -bool CEnumParameterType::getLiteral(int32_t iNumerical, string& strLiteral) const +bool CEnumParameterType::getLiteral(int32_t iNumerical, string &strLiteral) const { size_t uiChild; size_t uiNbChildren = getNbChildren(); for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CEnumValuePair* pValuePair = static_cast<const CEnumValuePair*>(getChild(uiChild)); + const CEnumValuePair *pValuePair = static_cast<const CEnumValuePair *>(getChild(uiChild)); if (pValuePair->getNumerical() == iNumerical) { @@ -300,14 +212,14 @@ bool CEnumParameterType::getLiteral(int32_t iNumerical, string& strLiteral) cons return false; } -bool CEnumParameterType::getNumerical(const string& strLiteral, int& iNumerical) const +bool CEnumParameterType::getNumerical(const string &strLiteral, int32_t &iNumerical) const { size_t uiChild; size_t uiNbChildren = getNbChildren(); for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CEnumValuePair* pValuePair = static_cast<const CEnumValuePair*>(getChild(uiChild)); + const CEnumValuePair *pValuePair = static_cast<const CEnumValuePair *>(getChild(uiChild)); if (pValuePair->getName() == strLiteral) { @@ -321,7 +233,7 @@ bool CEnumParameterType::getNumerical(const string& strLiteral, int& iNumerical) } // Numerical validity of the enum value -bool CEnumParameterType::isValid(int iNumerical, CParameterAccessContext& parameterAccessContext) const +bool CEnumParameterType::checkValueAgainstSpace(int32_t iNumerical) const { // Check that the value is part of the allowed values for this kind of enum size_t uiChild; @@ -329,7 +241,7 @@ bool CEnumParameterType::isValid(int iNumerical, CParameterAccessContext& parame for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CEnumValuePair* pValuePair = static_cast<const CEnumValuePair*>(getChild(uiChild)); + const CEnumValuePair *pValuePair = static_cast<const CEnumValuePair *>(getChild(uiChild)); if (pValuePair->getNumerical() == iNumerical) { @@ -337,15 +249,15 @@ bool CEnumParameterType::isValid(int iNumerical, CParameterAccessContext& parame } } - parameterAccessContext.setError("Provided value not part of numerical space"); - return false; } + // From IXmlSource -void CEnumParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CEnumParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Size - xmlElement.setAttributeString("Size", CUtility::toString(getSize() * 8)); + xmlElement.setAttribute("Size", getSize() * 8); base::toXml(xmlElement, serializingContext); } diff --git a/parameter/EnumParameterType.h b/parameter/EnumParameterType.h index 681f9b9..b8f67f4 100644 --- a/parameter/EnumParameterType.h +++ b/parameter/EnumParameterType.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,49 +31,56 @@ #include "ParameterType.h" -#include <list> #include <string> class CEnumParameterType : public CParameterType { public: - CEnumParameterType(const std::string& strName); + CEnumParameterType(const std::string &strName); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; /// Conversion // String - virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Integer - virtual bool toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(int32_t iUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(int32_t &iUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Default value handling (simulation only) virtual uint32_t getDefaultValue() const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // CElement virtual std::string getKind() const; + private: + // Specialized version of toBlackboard in case the access context is in raw + // value space + bool toBlackboardFromRaw(const std::string &strUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + // Returns true if children dynamic creation is to be dealt with virtual bool childrenAreDynamic() const; - // Check std::string is a number - static bool isNumber(const std::string& strValue); // Literal - numerical conversions - bool getLiteral(int32_t iNumerical, std::string& strLiteral) const; - bool getNumerical(const std::string& strLiteral, int& iNumerical) const; + bool getLiteral(int32_t iNumerical, std::string &strLiteral) const; + bool getNumerical(const std::string &strLiteral, int &iNumerical) const; // Numerical validity - bool isValid(int iNumerical, CParameterAccessContext& parameterAccessContext) const; + bool checkValueAgainstSpace(int32_t iNumerical) const; - // Range validity - bool checkValueAgainstRange(const std::string& strValue, int64_t value, CParameterAccessContext& parameterAccessContext, bool bHexaValue, bool bConversionSucceeded) const; + int32_t getMin() const; + int32_t getMax() const; }; diff --git a/parameter/EnumValuePair.cpp b/parameter/EnumValuePair.cpp index 35f4cd2..b5e967b 100644 --- a/parameter/EnumValuePair.cpp +++ b/parameter/EnumValuePair.cpp @@ -28,16 +28,11 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "EnumValuePair.h" -#include "Utility.h" #define base CElement using std::string; -CEnumValuePair::CEnumValuePair() : _iNumerical(0) -{ -} - // CElement string CEnumValuePair::getKind() const { @@ -52,38 +47,43 @@ int32_t CEnumValuePair::getNumerical() const string CEnumValuePair::getNumericalAsString() const { - return CUtility::toString(_iNumerical); + return std::to_string(_iNumerical); } // From IXmlSink -bool CEnumValuePair::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CEnumValuePair::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Literal - setName(xmlElement.getAttributeString("Literal")); + std::string name; + xmlElement.getAttribute("Literal", name); + setName(name); // Numerical - _iNumerical = xmlElement.getAttributeSignedInteger("Numerical"); + xmlElement.getAttribute("Numerical", _iNumerical); // Base return base::fromXml(xmlElement, serializingContext); } // Content dumping -void CEnumValuePair::logValue(string& strValue, CErrorContext& errorContext) const +string CEnumValuePair::logValue(utility::ErrorContext & /*ctx*/) const { - (void)errorContext; // Convert value - strValue = getNumericalAsString(); + return getNumericalAsString(); } // From IXmlSource -void CEnumValuePair::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CEnumValuePair::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Literal - xmlElement.setAttributeString("Literal", this->getName()); + xmlElement.setAttribute("Literal", this->getName()); // Numerical - xmlElement.setAttributeString("Numerical", getNumericalAsString()); + xmlElement.setAttribute("Numerical", getNumericalAsString()); - base::toXml(xmlElement, serializingContext); + // Ask for children processing only so as to avoid setting the Name attribute + // which does not exist for this element + base::childrenToXml(xmlElement, serializingContext); } diff --git a/parameter/EnumValuePair.h b/parameter/EnumValuePair.h index b29fea0..46d5578 100644 --- a/parameter/EnumValuePair.h +++ b/parameter/EnumValuePair.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -34,25 +34,24 @@ class CEnumValuePair : public CElement { public: - CEnumValuePair(); - // Numerical int32_t getNumerical() const; std::string getNumericalAsString() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // CElement virtual std::string getKind() const; + protected: // Content dumping - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + std::string logValue(utility::ErrorContext &errorContext) const override; + private: // Numerical - int32_t _iNumerical; + int32_t _iNumerical{0}; }; - diff --git a/parameter/FileIncluderElementBuilder.h b/parameter/FileIncluderElementBuilder.h index bccb227..d66065c 100644 --- a/parameter/FileIncluderElementBuilder.h +++ b/parameter/FileIncluderElementBuilder.h @@ -41,17 +41,19 @@ class CFileIncluderElementBuilder : public CElementBuilder { public: - CFileIncluderElementBuilder(bool bValidateWithSchemas) : - CElementBuilder(), - _bValidateWithSchemas(bValidateWithSchemas) - {} + CFileIncluderElementBuilder(bool bValidateWithSchemas, const std::string &schemaBaseUri) + : CElementBuilder(), _bValidateWithSchemas(bValidateWithSchemas), + _schemaBaseUri(schemaBaseUri) + { + } virtual CElement *createElement(const CXmlElement &xmlElement) const { - return new CXmlFileIncluderElement(xmlElement.getNameAttribute(), - xmlElement.getType(), _bValidateWithSchemas); + return new CXmlFileIncluderElement(xmlElement.getNameAttribute(), xmlElement.getType(), + _bValidateWithSchemas, _schemaBaseUri); } private: bool _bValidateWithSchemas; + const std::string _schemaBaseUri; }; diff --git a/parameter/FixedPointParameterType.cpp b/parameter/FixedPointParameterType.cpp index 5189a07..830ac64 100644 --- a/parameter/FixedPointParameterType.cpp +++ b/parameter/FixedPointParameterType.cpp @@ -44,7 +44,7 @@ using std::string; -CFixedPointParameterType::CFixedPointParameterType(const string& strName) : base(strName), _uiIntegral(0), _uiFractional(0) +CFixedPointParameterType::CFixedPointParameterType(const string &strName) : base(strName) { } @@ -54,73 +54,78 @@ string CFixedPointParameterType::getKind() const } // Element properties -void CFixedPointParameterType::showProperties(string& strResult) const +void CFixedPointParameterType::showProperties(string &strResult) const { base::showProperties(strResult); // Notation strResult += "Notation: Q"; - strResult += CUtility::toString(_uiIntegral); + strResult += std::to_string(_uiIntegral); strResult += "."; - strResult += CUtility::toString(_uiFractional); + strResult += std::to_string(_uiFractional); strResult += "\n"; } // XML Serialization value space handling // Value space handling for configuration import -void CFixedPointParameterType::handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const +void CFixedPointParameterType::handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const { // Direction? if (!configurationAccessContext.serializeOut()) { - // Get Value space from XML - if (xmlConfigurableElementSettingsElement.hasAttribute("ValueSpace")) { - - configurationAccessContext.setValueSpaceRaw(xmlConfigurableElementSettingsElement.getAttributeBoolean("ValueSpace", "Raw")); - } else { - - configurationAccessContext.setValueSpaceRaw(false); - } + string strValueSpace; + xmlConfigurableElementSettingsElement.getAttribute("ValueSpace", strValueSpace); + configurationAccessContext.setValueSpaceRaw(strValueSpace == "Raw"); } else { // Provide value space only if not the default one if (configurationAccessContext.valueSpaceIsRaw()) { - xmlConfigurableElementSettingsElement.setAttributeString("ValueSpace", "Raw"); + xmlConfigurableElementSettingsElement.setAttribute("ValueSpace", "Raw"); } } } -bool CFixedPointParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CFixedPointParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Size - uint32_t uiSizeInBits = xmlElement.getAttributeInteger("Size"); + size_t sizeInBits = 0; + xmlElement.getAttribute("Size", sizeInBits); // Q notation - _uiIntegral = xmlElement.getAttributeInteger("Integral"); - _uiFractional = xmlElement.getAttributeInteger("Fractional"); + xmlElement.getAttribute("Integral", _uiIntegral); + xmlElement.getAttribute("Fractional", _uiFractional); // Size vs. Q notation integrity check - if (uiSizeInBits < getUtilSizeInBits()) { + if (sizeInBits < getUtilSizeInBits()) { - serializingContext.setError("Inconsistent Size vs. Q notation for " + getKind() + " " + xmlElement.getPath() + ": Summing (Integral + _uiFractional + 1) should not exceed given Size (" + xmlElement.getAttributeString("Size") + ")"); + std::string size; + xmlElement.getAttribute("Size", size); + serializingContext.setError( + "Inconsistent Size vs. Q notation for " + getKind() + " " + xmlElement.getPath() + + ": Summing (Integral + _uiFractional + 1) should not exceed given Size (" + size + ")"); return false; } // Set the size - setSize(uiSizeInBits / 8); + setSize(sizeInBits / 8); return base::fromXml(xmlElement, serializingContext); } -bool CFixedPointParameterType::toBlackboard(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::toBlackboard(const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - bool bValueProvidedAsHexa = isHexadecimal(strValue); + bool bValueProvidedAsHexa = utility::isHexadecimal(strValue); // Check data integrity if (bValueProvidedAsHexa && !parameterAccessContext.valueSpaceIsRaw()) { - parameterAccessContext.setError("Hexadecimal values are not supported for " + getKind() + " when selected value space is real:"); + parameterAccessContext.setError("Hexadecimal values are not supported for " + getKind() + + " when selected value space is real:"); return false; } @@ -130,18 +135,18 @@ bool CFixedPointParameterType::toBlackboard(const string& strValue, uint32_t& ui if (bValueProvidedAsHexa) { return convertFromHexadecimal(strValue, uiValue, parameterAccessContext); - } return convertFromDecimal(strValue, uiValue, parameterAccessContext); } return convertFromQnm(strValue, uiValue, parameterAccessContext); } -void CFixedPointParameterType::setOutOfRangeError(const string& strValue, CParameterAccessContext& parameterAccessContext) const +void CFixedPointParameterType::setOutOfRangeError( + const string &strValue, CParameterAccessContext ¶meterAccessContext) const { - std::ostringstream strStream; + std::ostringstream stream; - strStream << "Value " << strValue << " standing out of admitted "; + stream << "Value " << strValue << " standing out of admitted "; if (!parameterAccessContext.valueSpaceIsRaw()) { @@ -150,79 +155,81 @@ void CFixedPointParameterType::setOutOfRangeError(const string& strValue, CParam double dMax = 0; getRange(dMin, dMax); - strStream << std::fixed << std::setprecision(_uiFractional) - << "real range [" << dMin << ", " << dMax << "]"; + stream << std::fixed << std::setprecision(_uiFractional) << "real range [" << dMin << ", " + << dMax << "]"; } else { // Min/Max computation int32_t iMax = getMaxValue<uint32_t>(); int32_t iMin = -iMax - 1; - strStream << "raw range ["; + stream << "raw range ["; - if (isHexadecimal(strValue)) { + if (utility::isHexadecimal(strValue)) { + + stream << std::hex << std::uppercase << std::setw(static_cast<int>(getSize()) * 2) + << std::setfill('0'); // Format Min - strStream << "0x" << std::hex << std::uppercase << - std::setw(getSize() * 2) << std::setfill('0') << makeEncodable(iMin); + stream << "0x" << makeEncodable(iMin); // Format Max - strStream << ", 0x" << std::hex << std::uppercase << - std::setw(getSize() * 2) << std::setfill('0') << makeEncodable(iMax); + stream << ", 0x" << makeEncodable(iMax); } else { - strStream << iMin << ", " << iMax; + stream << iMin << ", " << iMax; } - strStream << "]"; + stream << "]"; } - strStream << " for " << getKind(); + stream << " for " << getKind(); - parameterAccessContext.setError(strStream.str()); + parameterAccessContext.setError(stream.str()); } -bool CFixedPointParameterType::fromBlackboard(string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::fromBlackboard(string &strValue, const uint32_t &value, + CParameterAccessContext ¶meterAccessContext) const { - int32_t iData = uiValue; - // Check encodability - assert(isEncodable((uint32_t)iData, false)); + assert(isEncodable(value, false)); // Format - std::ostringstream strStream; + std::ostringstream stream; // Raw formatting? if (parameterAccessContext.valueSpaceIsRaw()) { - // Hexa formatting? if (parameterAccessContext.outputRawFormatIsHex()) { + uint32_t data = static_cast<uint32_t>(value); - strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << (uint32_t)iData; + stream << "0x" << std::hex << std::uppercase + << std::setw(static_cast<int>(getSize() * 2)) << std::setfill('0') << data; } else { + int32_t data = value; // Sign extend - signExtend(iData); + signExtend(data); - strStream << iData; + stream << data; } } else { + int32_t data = value; // Sign extend - signExtend(iData); + signExtend(data); // Conversion - double dData = binaryQnmToDouble(iData); - - strStream << std::fixed << std::setprecision(_uiFractional) << dData; + stream << std::fixed << std::setprecision(_uiFractional) << binaryQnmToDouble(data); } - strValue = strStream.str(); + strValue = stream.str(); return true; } // Value access -bool CFixedPointParameterType::toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { // Check that the value is within the allowed range for this type if (!checkValueAgainstRange(dUserValue)) { @@ -244,10 +251,9 @@ bool CFixedPointParameterType::toBlackboard(double dUserValue, uint32_t& uiValue return true; } -bool CFixedPointParameterType::fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - int32_t iData = uiValue; // Check unsigned value is encodable @@ -262,59 +268,52 @@ bool CFixedPointParameterType::fromBlackboard(double& dUserValue, uint32_t uiVal } // Util size -uint32_t CFixedPointParameterType::getUtilSizeInBits() const +size_t CFixedPointParameterType::getUtilSizeInBits() const { return _uiIntegral + _uiFractional + 1; } // Compute the range for the type (minimum and maximum values) -void CFixedPointParameterType::getRange(double& dMin, double& dMax) const -{ - dMax = (double)((1UL << (_uiIntegral + _uiFractional)) - 1) / (1UL << _uiFractional); - dMin = -(double)(1UL << (_uiIntegral + _uiFractional)) / (1UL << _uiFractional); -} - -bool CFixedPointParameterType::isHexadecimal(const string& strValue) const +void CFixedPointParameterType::getRange(double &dMin, double &dMax) const { - return !strValue.compare(0, 2, "0x"); + dMax = ((1U << (_uiIntegral + _uiFractional)) - 1) / double(1U << _uiFractional); + dMin = -((1U << (_uiIntegral + _uiFractional)) / double(1U << _uiFractional)); } -bool CFixedPointParameterType::convertFromHexadecimal(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::convertFromHexadecimal( + const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { // For hexadecimal representation, we need full 32 bit range conversion. - uint32_t uiData; - if (!convertTo(strValue, uiData) || !isEncodable(uiData, false)) { + if (!convertTo(strValue, uiValue) || !isEncodable(uiValue, false)) { setOutOfRangeError(strValue, parameterAccessContext); return false; } - signExtend((int32_t&)uiData); + signExtend(reinterpret_cast<int32_t &>(uiValue)); // check that the data is encodable and can been safely written to the blackboard - assert(isEncodable(uiData, true)); - uiValue = uiData; + assert(isEncodable(uiValue, true)); return true; } -bool CFixedPointParameterType::convertFromDecimal(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::convertFromDecimal( + const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - int32_t iData; - - if (!convertTo(strValue, iData) || !isEncodable((uint32_t)iData, true)) { + if (!convertTo(strValue, reinterpret_cast<int32_t &>(uiValue)) || !isEncodable(uiValue, true)) { setOutOfRangeError(strValue, parameterAccessContext); return false; } - uiValue = static_cast<uint32_t>(iData); - return true; } -bool CFixedPointParameterType::convertFromQnm(const string& strValue, uint32_t& uiValue, - CParameterAccessContext& parameterAccessContext) const +bool CFixedPointParameterType::convertFromQnm(const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { - double dData; + double dData = 0; if (!convertTo(strValue, dData) || !checkValueAgainstRange(dData)) { @@ -343,7 +342,7 @@ bool CFixedPointParameterType::checkValueAgainstRange(double dValue) const int32_t CFixedPointParameterType::doubleToBinaryQnm(double dValue) const { // For Qn.m number, multiply by 2^n and round to the nearest integer - int32_t iData = static_cast<int32_t>(round(dValue * (1UL << _uiFractional))); + int32_t iData = static_cast<int32_t>(round(dValue * double(1UL << _uiFractional))); // Left justify // For a Qn.m number, shift 32 - (n + m + 1) bits to the left (the rest of // the bits aren't used) @@ -352,25 +351,25 @@ int32_t CFixedPointParameterType::doubleToBinaryQnm(double dValue) const return iData; } - double CFixedPointParameterType::binaryQnmToDouble(int32_t iValue) const { // Unjustify iValue >>= getSize() * 8 - getUtilSizeInBits(); - return static_cast<double>(iValue) / (1UL << _uiFractional); + return static_cast<double>(iValue) / double(1UL << _uiFractional); } // From IXmlSource -void CFixedPointParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CFixedPointParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Size - xmlElement.setAttributeString("Size", CUtility::toString(getSize() * 8)); + xmlElement.setAttribute("Size", getSize() * 8); // Integral - xmlElement.setAttributeString("Integral", CUtility::toString(_uiIntegral)); + xmlElement.setAttribute("Integral", _uiIntegral); // Fractional - xmlElement.setAttributeString("Fractional", CUtility::toString(_uiFractional)); + xmlElement.setAttribute("Fractional", _uiFractional); base::toXml(xmlElement, serializingContext); } diff --git a/parameter/FixedPointParameterType.h b/parameter/FixedPointParameterType.h index c2f5f47..d4e96b6 100644 --- a/parameter/FixedPointParameterType.h +++ b/parameter/FixedPointParameterType.h @@ -36,46 +36,43 @@ class CFixedPointParameterType : public CParameterType { public: - CFixedPointParameterType(const std::string& strName); + CFixedPointParameterType(const std::string &strName); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // XML Serialization value space handling // Value space handling for configuration import - virtual void handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const; + virtual void handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const; /// Conversion // String - virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Double - virtual bool toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // CElement virtual std::string getKind() const; + private: // Util size - uint32_t getUtilSizeInBits() const; + size_t getUtilSizeInBits() const; // Range computation - void getRange(double& dMin, double& dMax) const; - - /** - * Checks if a string has the written representation of an hexadecimal number (Which is - * the prefix "Ox" in C++). - * - * @param[in] strValue Parameter read from the XML file representated as a string. - * - * @return true if the string is written as hexa, false otherwise. - */ - bool isHexadecimal(const std::string& strValue) const; + void getRange(double &dMin, double &dMax) const; /** * Convert a decimal raw represented string into an unsigned long integer. @@ -85,11 +82,12 @@ private: * @param[in] strValue Parameter read from the XML file representated as a string in decimal * raw format * @param[out] uiValue Parameter representated as a long unsigned integer. - * @param[in:out] parameterAccessContext Parameter access context. + * @param[in,out] parameterAccessContext Parameter access context. * * @return true if the string was successfully converted, false otherwise. */ - bool convertFromDecimal(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + bool convertFromDecimal(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; /** * Convert an hexadecimal raw represented string into an unsigned long integer. @@ -99,11 +97,12 @@ private: * @param[in] strValue Parameter read from the XML file representated as a string in hexadecimal * raw format * @param[out] uiValue Parameter representated as a long unsigned integer. - * @param[in:out] parameterAccessContext Parameter access context. + * @param[in,out] parameterAccessContext Parameter access context. * * @return true if the string was successfully converted, false otherwise. */ - bool convertFromHexadecimal(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + bool convertFromHexadecimal(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; /** * Convert a Qn.m represented string into an unsigned long integer. @@ -113,11 +112,12 @@ private: * @param[in] strValue Parameter read from the XML file representated as a string in Qn.m * representation. * @param[out] uiValue Parameter representated as a long unsigned integer. - * @param[in:out] parameterAccessContext Parameter access context. + * @param[in,out] parameterAccessContext Parameter access context. * * @return true if the string was successfully converted, false otherwise. */ - bool convertFromQnm(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + bool convertFromQnm(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; /** * Set the out of range error. @@ -125,9 +125,10 @@ private: * illegal value provided and gives the range allowed for the parameter. * * @param[in] strValue Parameter read from the XML file representated as a string - * @param[in:out] parameterAccessContext Parameter Access Context + * @param[in,out] parameterAccessContext Parameter Access Context */ - void setOutOfRangeError(const std::string& strValue, CParameterAccessContext& parameterAccessContext) const; + void setOutOfRangeError(const std::string &strValue, + CParameterAccessContext ¶meterAccessContext) const; // Check if data is encodable bool checkValueAgainstRange(double dValue) const; @@ -152,7 +153,7 @@ private: double binaryQnmToDouble(int32_t iValue) const; // Integral part in Q notation - uint32_t _uiIntegral; + uint32_t _uiIntegral{0}; // Fractional part in Q notation - uint32_t _uiFractional; + uint32_t _uiFractional{0}; }; diff --git a/parameter/FloatingPointParameterType.cpp b/parameter/FloatingPointParameterType.cpp new file mode 100644 index 0000000..44de9e2 --- /dev/null +++ b/parameter/FloatingPointParameterType.cpp @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2014-2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, Value, 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 "FloatingPointParameterType.h" +#include <sstream> +#include <iomanip> +#include "ParameterAccessContext.h" +#include "ConfigurationAccessContext.h" +#include <limits> +#include <climits> +#include "convert.hpp" +#include "Utility.h" +#include "BinaryCopy.hpp" + +using std::string; + +CFloatingPointParameterType::CFloatingPointParameterType(const string &strName) : base(strName) +{ +} + +string CFloatingPointParameterType::getKind() const +{ + return "FloatingPointParameter"; +} + +// Element properties +void CFloatingPointParameterType::showProperties(string &strResult) const +{ + base::showProperties(strResult); + + strResult += "Min:" + std::to_string(_fMin) + "\n" + "Max:" + std::to_string(_fMax) + "\n"; +} + +void CFloatingPointParameterType::handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const +{ + if (!configurationAccessContext.serializeOut()) { + + string strValueSpace; + + if (xmlConfigurableElementSettingsElement.getAttribute("ValueSpace", strValueSpace)) { + + configurationAccessContext.setValueSpaceRaw(strValueSpace == "Raw"); + } else { + + configurationAccessContext.setValueSpaceRaw(false); + } + } else { + // Set the value space only if it is raw (i.e. not the default one) + if (configurationAccessContext.valueSpaceIsRaw()) { + + xmlConfigurableElementSettingsElement.setAttribute("ValueSpace", "Raw"); + } + } +} + +bool CFloatingPointParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) +{ + // Size. The XSD fixes it to 32 + size_t sizeInBits = 32; + xmlElement.getAttribute("Size", sizeInBits); + + // Size support check: only floats are supported + // (e.g. doubles are not supported) + if (sizeInBits != sizeof(float) * CHAR_BIT) { + + serializingContext.setError("Unsupported size (" + std::to_string(sizeInBits) + ") for " + + getKind() + " " + xmlElement.getPath() + + ". For now, only 32 is supported."); + + return false; + } + + setSize(sizeInBits / CHAR_BIT); + + xmlElement.getAttribute("Min", _fMin); + xmlElement.getAttribute("Max", _fMax); + + if (_fMin > _fMax) { + serializingContext.setError("Min (" + std::to_string(_fMin) + + ") can't be greater than Max (" + std::to_string(_fMax) + ")"); + return false; + } + + return base::fromXml(xmlElement, serializingContext); +} + +bool CFloatingPointParameterType::toBlackboard( + const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const +{ + // Check Value integrity + if (utility::isHexadecimal(strValue) && !parameterAccessContext.valueSpaceIsRaw()) { + + parameterAccessContext.setError("Hexadecimal values are not supported for " + getKind() + + " when selected value space is real: " + strValue); + + return false; + } + + if (parameterAccessContext.valueSpaceIsRaw()) { + // Raw value: interpret the user input as the memory content of the + // parameter + if (!convertTo(strValue, uiValue)) { + + parameterAccessContext.setError("Value '" + strValue + "' is invalid"); + return false; + } + + auto fData = utility::binaryCopy<float>(uiValue); + + // Check against NaN or infinity + if (!std::isfinite(fData)) { + + parameterAccessContext.setError("Value " + strValue + " is not a finite number"); + return false; + } + + if (!checkValueAgainstRange(fData)) { + + setOutOfRangeError(strValue, parameterAccessContext); + return false; + } + return true; + } else { + + float fValue = 0.0f; + + // Interpret the user input as float + if (!convertTo(strValue, fValue)) { + + parameterAccessContext.setError("Value " + strValue + " is invalid"); + return false; + } + + if (!checkValueAgainstRange(fValue)) { + + setOutOfRangeError(strValue, parameterAccessContext); + return false; + } + + // Move to the "raw memory" value space + uiValue = utility::binaryCopy<decltype(uiValue)>(fValue); + return true; + } +} + +void CFloatingPointParameterType::setOutOfRangeError( + const string &strValue, CParameterAccessContext ¶meterAccessContext) const +{ + // error message buffer + std::ostringstream ostrStream; + + ostrStream << "Value " << strValue << " standing out of admitted "; + + if (!parameterAccessContext.valueSpaceIsRaw()) { + + ostrStream << "real range [" << _fMin << ", " << _fMax << "]"; + } else { + + auto uiMin = utility::binaryCopy<uint32_t>(_fMin); + auto uiMax = utility::binaryCopy<uint32_t>(_fMax); + + if (utility::isHexadecimal(strValue)) { + + ostrStream << std::showbase << std::hex << std::setw(static_cast<int>(getSize() * 2)) + << std::setfill('0'); + } + + ostrStream << "raw range [" << uiMin << ", " << uiMax << "]"; + } + ostrStream << " for " << getKind(); + + parameterAccessContext.setError(ostrStream.str()); +} + +bool CFloatingPointParameterType::fromBlackboard( + string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const +{ + std::ostringstream ostrStream; + + if (parameterAccessContext.valueSpaceIsRaw()) { + + if (parameterAccessContext.outputRawFormatIsHex()) { + + ostrStream << std::showbase << std::hex << std::setw(static_cast<int>(getSize() * 2)) + << std::setfill('0'); + } + + ostrStream << uiValue; + } else { + + // Move from "raw memory" value space to real space + auto fValue = utility::binaryCopy<float>(uiValue); + + ostrStream << fValue; + } + + strValue = ostrStream.str(); + + return true; +} + +// Value access +bool CFloatingPointParameterType::toBlackboard( + double dUserValue, uint32_t &uiValue, CParameterAccessContext ¶meterAccessContext) const +{ + if (!checkValueAgainstRange(dUserValue)) { + + parameterAccessContext.setError("Value out of range"); + return false; + } + + // Cast is fine because dValue has been checked against the value range + float fValue = static_cast<float>(dUserValue); + uiValue = utility::binaryCopy<decltype(uiValue)>(fValue); + return true; +} + +bool CFloatingPointParameterType::fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const +{ + // Move from "raw memory" value space to real space + auto fValue = utility::binaryCopy<float>(uiValue); + + dUserValue = fValue; + return true; +} + +bool CFloatingPointParameterType::checkValueAgainstRange(double dValue) const +{ + // Check that dValue can safely be cast to a float + // (otherwise, behaviour is undefined) + if ((dValue < -std::numeric_limits<float>::max()) || + (dValue > std::numeric_limits<float>::max())) { + return false; + } + + return checkValueAgainstRange(static_cast<float>(dValue)); +} + +bool CFloatingPointParameterType::checkValueAgainstRange(float fValue) const +{ + return fValue <= _fMax && fValue >= _fMin; +} + +void CFloatingPointParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const +{ + xmlElement.setAttribute("Size", getSize() * CHAR_BIT); + xmlElement.setAttribute("Min", _fMin); + xmlElement.setAttribute("Max", _fMax); + + base::toXml(xmlElement, serializingContext); +} diff --git a/parameter/FloatingPointParameterType.h b/parameter/FloatingPointParameterType.h new file mode 100644 index 0000000..aafb5e2 --- /dev/null +++ b/parameter/FloatingPointParameterType.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2014-2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +#include "ParameterType.h" +#include <string> + +class CFloatingPointParameterType : public CParameterType +{ +public: + CFloatingPointParameterType(const std::string &strName); + + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; + + virtual void handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const; + + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; + + virtual void showProperties(std::string &strResult) const; + + virtual std::string getKind() const; + +private: + typedef CParameterType base; + + /** + * Format an out of range error. + * + * @param[in] strValue the user provided value + * @param[in,out] parameterAccessContext Parameter Access Context + */ + void setOutOfRangeError(const std::string &strValue, + CParameterAccessContext ¶meterAccessContext) const; + + /** + * Check value validity against range. + * + * @param[in] fValue the user interpreted value + * @return true if data is valid against range, false otherwise + */ + bool checkValueAgainstRange(float fValue) const; + /** + * Check value validity against range. + * + * @param[in] dValue the user interpreted value (as double) + * @return true if data is valid against range, false otherwise + */ + bool checkValueAgainstRange(double dValue) const; + + /** Bounds */ + float _fMin{std::numeric_limits<float>::lowest()}; + float _fMax{std::numeric_limits<float>::max()}; +}; diff --git a/parameter/FormattedSubsystemObject.cpp b/parameter/FormattedSubsystemObject.cpp index 591ef90..dc7dded 100644 --- a/parameter/FormattedSubsystemObject.cpp +++ b/parameter/FormattedSubsystemObject.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -38,39 +38,31 @@ using std::string; CFormattedSubsystemObject::CFormattedSubsystemObject( - CInstanceConfigurableElement* pInstanceConfigurableElement) - : base(pInstanceConfigurableElement) + CInstanceConfigurableElement *pInstanceConfigurableElement, core::log::Logger &logger) + : base(pInstanceConfigurableElement, logger) { } CFormattedSubsystemObject::CFormattedSubsystemObject( - CInstanceConfigurableElement* pInstanceConfigurableElement, - const string& strMappingValue) - : base(pInstanceConfigurableElement), _strFormattedMappingValue(strMappingValue) + CInstanceConfigurableElement *pInstanceConfigurableElement, core::log::Logger &logger, + const string &strMappingValue) + : base(pInstanceConfigurableElement, logger), _strFormattedMappingValue(strMappingValue) { - } - CFormattedSubsystemObject::CFormattedSubsystemObject( - CInstanceConfigurableElement* pInstanceConfigurableElement, - const string& strMappingValue, - uint32_t uiFirstAmendKey, - uint32_t uiNbAmendKeys, - const CMappingContext& context) - : base(pInstanceConfigurableElement), _strFormattedMappingValue(strMappingValue) + CInstanceConfigurableElement *pInstanceConfigurableElement, core::log::Logger &logger, + const string &strMappingValue, size_t firstAmendKey, size_t nbAmendKeys, + const CMappingContext &context) + : base(pInstanceConfigurableElement, logger), _strFormattedMappingValue(strMappingValue) { // Cope with quotes in the name if (strMappingValue[0] == '\'' && strMappingValue.length() >= 2) { _strFormattedMappingValue = strMappingValue.substr(1, strMappingValue.length() - 2); } - _strFormattedMappingValue = formatMappingValue(_strFormattedMappingValue, uiFirstAmendKey, - uiNbAmendKeys, context); -} - -CFormattedSubsystemObject::~CFormattedSubsystemObject() -{ + _strFormattedMappingValue = + formatMappingValue(_strFormattedMappingValue, firstAmendKey, nbAmendKeys, context); } string CFormattedSubsystemObject::getFormattedMappingValue() const @@ -78,16 +70,15 @@ string CFormattedSubsystemObject::getFormattedMappingValue() const return _strFormattedMappingValue; } -bool CFormattedSubsystemObject::isAmendKeyValid(uint32_t uiAmendKey) +bool CFormattedSubsystemObject::isAmendKeyValid(size_t uiAmendKey) { return (uiAmendKey > 0) && (uiAmendKey <= 9); } -string CFormattedSubsystemObject::formatMappingValue(const string& strMappingValue, - uint32_t uiFirstAmendKey, - uint32_t uiNbAmendKeys, - const CMappingContext& context) +string CFormattedSubsystemObject::formatMappingValue(const string &strMappingValue, + size_t firstAmendKey, size_t nbAmendKeys, + const CMappingContext &context) { string strFormattedValue = strMappingValue; @@ -95,36 +86,34 @@ string CFormattedSubsystemObject::formatMappingValue(const string& strMappingVal string::size_type uiPercentPos = strFormattedValue.find('%', 0); // Amendment limited to one digit (values from 1 to 9) - assert(isAmendKeyValid(uiNbAmendKeys)); + assert(isAmendKeyValid(nbAmendKeys)); // Check we found one and that there's room for value if (uiPercentPos != string::npos && uiPercentPos < strFormattedValue.size() - 1) { // Get Amend number - uint32_t uiAmendNumber = strFormattedValue[uiPercentPos + 1] - '0'; + size_t uiAmendNumber = strFormattedValue[uiPercentPos + 1] - '0'; // Check if current Amend number is Valid - if ((uiAmendNumber > 0) && (uiAmendNumber <= uiNbAmendKeys)) { + if ((uiAmendNumber > 0) && (uiAmendNumber <= nbAmendKeys)) { - uint32_t uiAmendType = uiFirstAmendKey + uiAmendNumber - 1; + size_t uiAmendType = firstAmendKey + uiAmendNumber - 1; // Check if current Amend type is Set in the context if (context.iSet(uiAmendType)) { // Make the amendment on the part of the string after the current Amend - string strEndOfLine = strFormattedValue.substr(uiPercentPos + 2, - strFormattedValue.size() - - uiPercentPos - 2); - string strEndOfLineAmended = formatMappingValue(strEndOfLine, uiFirstAmendKey, - uiNbAmendKeys, context); + string strEndOfLine = strFormattedValue.substr( + uiPercentPos + 2, strFormattedValue.size() - uiPercentPos - 2); + string strEndOfLineAmended = + formatMappingValue(strEndOfLine, firstAmendKey, nbAmendKeys, context); // Get current Amend value string strAmendValue = context.getItem(uiAmendType); // Make the amendment - strFormattedValue = strFormattedValue.substr(0, uiPercentPos) + strAmendValue - + strEndOfLineAmended; - + strFormattedValue = + strFormattedValue.substr(0, uiPercentPos) + strAmendValue + strEndOfLineAmended; } } } diff --git a/parameter/FormattedSubsystemObject.h b/parameter/FormattedSubsystemObject.h index c04583b..4793635 100644 --- a/parameter/FormattedSubsystemObject.h +++ b/parameter/FormattedSubsystemObject.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,44 +29,49 @@ */ #pragma once +#include "parameter_export.h" + #include "SubsystemObject.h" -class CFormattedSubsystemObject : public CSubsystemObject +class PARAMETER_EXPORT CFormattedSubsystemObject : public CSubsystemObject { public: /** * Builds a new CFormattedSubsystemObject instance, without any mapping information. * * @param[in] pInstanceConfigurableElement Instance of the element linked to the SubsytemObject. + * @param[in] logger the logger provided by the client */ - CFormattedSubsystemObject(CInstanceConfigurableElement* pInstanceConfigurableElement); + CFormattedSubsystemObject(CInstanceConfigurableElement *pInstanceConfigurableElement, + core::log::Logger &logger); /** * Builds a new CFormattedSubsystemObject instance, using a simple mapping value without Amends. * * @param[in] pInstanceConfigurableElement Instance of the element linked to the SubsytemObject. + * @param[in] logger the logger provided by the client * @param[in] strFormattedMapping A std::string corresponding to the mapping of the element. The * std::string does not contain any Amend (%) and does not need to be formatted. */ - CFormattedSubsystemObject(CInstanceConfigurableElement* pInstanceConfigurableElement, - const std::string& strFormattedMapping); + CFormattedSubsystemObject(CInstanceConfigurableElement *pInstanceConfigurableElement, + core::log::Logger &logger, const std::string &strFormattedMapping); /** * Builds a new CFormattedSubsystemObject instance, using a mapping value containing Amends. * * @param[in] pInstanceConfigurableElement Instance of the element linked to the SubsytemObject. + * @param[in] logger the logger provided by the client * @param[in] strMappingValue A std::string corresponding to the mapping of the element. The * std::string contains Amend (%) and needs to be formatted with information from the context. - * @param[in] uiFirstAmendKey Index of the first Amend key - * @param[in] uiNbAmendKeys Number of Amends + * @param[in] firstAmendKey Index of the first Amend key + * @param[in] nbAmendKeys Number of Amends * @param[in] context Contains values associated to Amend keys */ - CFormattedSubsystemObject(CInstanceConfigurableElement* pInstanceConfigurableElement, - const std::string& strMappingValue, - uint32_t uiFirstAmendKey, - uint32_t uiNbAmendKeys, - const CMappingContext& context); - virtual ~CFormattedSubsystemObject(); + CFormattedSubsystemObject(CInstanceConfigurableElement *pInstanceConfigurableElement, + core::log::Logger &logger, const std::string &strMappingValue, + size_t firstAmendKey, size_t nbAmendKeys, + const CMappingContext &context); + virtual ~CFormattedSubsystemObject() = default; /** * Returns the formatted mapping value associated to the element. @@ -76,7 +81,6 @@ public: virtual std::string getFormattedMappingValue() const; private: - /** * Check if the index of Amend key is valid. * @@ -84,7 +88,7 @@ private: * * @return true if the index of the Amend key is > 0 and <= 9. */ - static bool isAmendKeyValid(uint32_t uiAmendKey); + static bool isAmendKeyValid(size_t uiAmendKey); /** * Generic mapping formatting @@ -92,18 +96,17 @@ private: * Format a std::string from mapping data and its context, replacing amendments by their value * * @param[in] strMappingValue The input mapping std::string containing amendments - * @param[in] context uiFirstAmendKey The index of the first Amend key in the key list of the + * @param[in] context firstAmendKey The index of the first Amend key in the key list of the * context - * @param[in] uiNbAmendKeys Number of Amend keys in the context + * @param[in] nbAmendKeys Number of Amend keys in the context * @param[in] context The context containing Amend values * - * @return The formatted std::string, corresponding to the input strMappingValue where %n have been + * @return The formatted std::string, corresponding to the input strMappingValue where %n have + * been * replaced by their value */ - static std::string formatMappingValue(const std::string& strMappingValue, - uint32_t uiFirstAmendKey, - uint32_t uiNbAmendKeys, - const CMappingContext& context); + static std::string formatMappingValue(const std::string &strMappingValue, size_t firstAmendKey, + size_t nbAmendKeys, const CMappingContext &context); /** * std::string containing the formatted mapping value diff --git a/parameter/FrameworkConfigurationGroup.h b/parameter/FrameworkConfigurationGroup.h index e4da540..551cb5e 100644 --- a/parameter/FrameworkConfigurationGroup.h +++ b/parameter/FrameworkConfigurationGroup.h @@ -36,15 +36,11 @@ class CFrameworkConfigurationGroup : public CKindElement { public: - CFrameworkConfigurationGroup(const std::string& strName, const std::string& strKind) : CKindElement(strName, strKind) + CFrameworkConfigurationGroup(const std::string &strName, const std::string &strKind) + : CKindElement(strName, strKind) { } private: - virtual bool childrenAreDynamic() const - { - return true; - } - - + virtual bool childrenAreDynamic() const { return true; } }; diff --git a/parameter/FrameworkConfigurationLocation.cpp b/parameter/FrameworkConfigurationLocation.cpp index 6983f16..23c27e3 100644 --- a/parameter/FrameworkConfigurationLocation.cpp +++ b/parameter/FrameworkConfigurationLocation.cpp @@ -27,21 +27,25 @@ * (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 "XmlDocSource.h" #include "FrameworkConfigurationLocation.h" #include <assert.h> #define base CKindElement -CFrameworkConfigurationLocation::CFrameworkConfigurationLocation(const std::string& strName, const std::string& strKind) : base(strName, strKind) +CFrameworkConfigurationLocation::CFrameworkConfigurationLocation(const std::string &strName, + const std::string &strKind) + : base(strName, strKind) { } // From IXmlSink -bool CFrameworkConfigurationLocation::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CFrameworkConfigurationLocation::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { - _strPath = xmlElement.getAttributeString("Path"); + xmlElement.getAttribute("Path", _configurationUri); - if (_strPath.empty()) { + if (_configurationUri.empty()) { serializingContext.setError("Empty Path attribute in element " + xmlElement.getPath()); @@ -50,41 +54,7 @@ bool CFrameworkConfigurationLocation::fromXml(const CXmlElement& xmlElement, CXm return true; } -// File path -std::string CFrameworkConfigurationLocation::getFilePath(const std::string& strBaseFolder) const +const std::string &CFrameworkConfigurationLocation::getUri() const { - if (isPathRelative()) { - - return strBaseFolder + "/" + _strPath; - } - return _strPath; -} - -// Folder path -std::string CFrameworkConfigurationLocation::getFolderPath(const std::string& strBaseFolder) const -{ - uint32_t uiSlashPos = _strPath.rfind('/', -1); - - if (isPathRelative()) { - - if (uiSlashPos != (uint32_t)-1) { - - return strBaseFolder + "/" + _strPath.substr(0, uiSlashPos); - - } else { - - return strBaseFolder; - } - } else { - - assert(uiSlashPos != (uint32_t)-1); - - return _strPath.substr(0, uiSlashPos); - } -} - -// Detect relative path -bool CFrameworkConfigurationLocation::isPathRelative() const -{ - return _strPath[0] != '/'; + return _configurationUri; } diff --git a/parameter/FrameworkConfigurationLocation.h b/parameter/FrameworkConfigurationLocation.h index 56cc5f6..7182db9 100644 --- a/parameter/FrameworkConfigurationLocation.h +++ b/parameter/FrameworkConfigurationLocation.h @@ -36,20 +36,15 @@ class CFrameworkConfigurationLocation : public CKindElement { public: - CFrameworkConfigurationLocation(const std::string& strName, const std::string& strKind); + CFrameworkConfigurationLocation(const std::string &strName, const std::string &strKind); - // File path - std::string getFilePath(const std::string& strBaseFolder) const; - - // Folder path - std::string getFolderPath(const std::string& strBaseFolder) const; + /** Get Configuration file URI + */ + const std::string &getUri() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); -private: - // Detect relative path - bool isPathRelative() const; + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); - // Path - std::string _strPath; +private: + std::string _configurationUri; }; diff --git a/parameter/HardwareBackSynchronizer.cpp b/parameter/HardwareBackSynchronizer.cpp index b16ea79..dbc23eb 100644 --- a/parameter/HardwareBackSynchronizer.cpp +++ b/parameter/HardwareBackSynchronizer.cpp @@ -32,15 +32,16 @@ #define base CBackSynchronizer -CHardwareBackSynchronizer::CHardwareBackSynchronizer(const CConfigurableElement* pConfigurableElement, CParameterBlackboard* pParameterBlackboard) +CHardwareBackSynchronizer::CHardwareBackSynchronizer( + const CConfigurableElement *pConfigurableElement, CParameterBlackboard *pParameterBlackboard) : base(pConfigurableElement), _pParameterBlackboard(pParameterBlackboard) { // Fill back syncer set - std::list<const CConfigurableElement*>::const_iterator it; + std::list<const CConfigurableElement *>::const_iterator it; for (it = _needingBackSyncList.begin(); it != _needingBackSyncList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; pConfigurableElement->fillSyncerSet(_backSyncerSet); } diff --git a/parameter/HardwareBackSynchronizer.h b/parameter/HardwareBackSynchronizer.h index 9572017..fd2e70d 100644 --- a/parameter/HardwareBackSynchronizer.h +++ b/parameter/HardwareBackSynchronizer.h @@ -35,7 +35,8 @@ class CHardwareBackSynchronizer : public CBackSynchronizer { public: - CHardwareBackSynchronizer(const CConfigurableElement* pConfigurableElement, CParameterBlackboard* pParameterBlackboard); + CHardwareBackSynchronizer(const CConfigurableElement *pConfigurableElement, + CParameterBlackboard *pParameterBlackboard); // Back synchronization virtual void sync(); @@ -44,6 +45,5 @@ private: // Back syncer set CSyncerSet _backSyncerSet; // Parameter blackboard - CParameterBlackboard* _pParameterBlackboard; + CParameterBlackboard *_pParameterBlackboard; }; - diff --git a/parameter/InstanceConfigurableElement.cpp b/parameter/InstanceConfigurableElement.cpp index b59cffd..f9afa20 100644 --- a/parameter/InstanceConfigurableElement.cpp +++ b/parameter/InstanceConfigurableElement.cpp @@ -35,9 +35,11 @@ #include "ParameterAccessContext.h" #include <assert.h> -#define base CConfigurableElementWithMapping +#define base CConfigurableElement -CInstanceConfigurableElement::CInstanceConfigurableElement(const std::string& strName, const CTypeElement* pTypeElement) : base(strName), _pTypeElement(pTypeElement), _pSyncer(NULL) +CInstanceConfigurableElement::CInstanceConfigurableElement(const std::string &strName, + const CTypeElement *pTypeElement) + : base(strName), _pTypeElement(pTypeElement) { } @@ -47,14 +49,21 @@ std::string CInstanceConfigurableElement::getKind() const return _pTypeElement->getKind(); } +std::string CInstanceConfigurableElement::getXmlElementName() const +{ + // Delegate + return _pTypeElement->getXmlElementName(); +} + // Type element -const CTypeElement* CInstanceConfigurableElement::getTypeElement() const +const CTypeElement *CInstanceConfigurableElement::getTypeElement() const { return _pTypeElement; } // Mapping -bool CInstanceConfigurableElement::getMappingData(const std::string& strKey, const std::string*& pStrValue) const +bool CInstanceConfigurableElement::getMappingData(const std::string &strKey, + const std::string *&pStrValue) const { // Delegate return getTypeElement()->getMappingData(strKey, pStrValue); @@ -67,7 +76,7 @@ std::string CInstanceConfigurableElement::getFormattedMapping() const return getTypeElement()->getFormattedMapping(); } -bool CInstanceConfigurableElement::map(IMapper& mapper, std::string& strError) +bool CInstanceConfigurableElement::map(IMapper &mapper, std::string &strError) { bool bHasMappingData = getTypeElement()->hasMappingData(); bool bKeepDiving = true; @@ -87,8 +96,8 @@ bool CInstanceConfigurableElement::map(IMapper& mapper, std::string& strError) for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - CInstanceConfigurableElement* pInstanceConfigurableChildElement = - static_cast<CInstanceConfigurableElement*>(getChild(uiChild)); + CInstanceConfigurableElement *pInstanceConfigurableChildElement = + static_cast<CInstanceConfigurableElement *>(getChild(uiChild)); if (!pInstanceConfigurableChildElement->map(mapper, strError)) { @@ -105,21 +114,8 @@ bool CInstanceConfigurableElement::map(IMapper& mapper, std::string& strError) return true; } -void CInstanceConfigurableElement::getListOfElementsWithMapping( - std::list<const CConfigurableElement*>& configurableElementPath) const -{ - const CTypeElement* pTypeElement = getTypeElement(); - - if (pTypeElement && pTypeElement->hasMappingData()) { - - configurableElementPath.push_back(this); - } - - base::getListOfElementsWithMapping(configurableElementPath); -} - // Element properties -void CInstanceConfigurableElement::showProperties(std::string& strResult) const +void CInstanceConfigurableElement::showProperties(std::string &strResult) const { base::showProperties(strResult); @@ -134,13 +130,13 @@ bool CInstanceConfigurableElement::isScalar() const } // Array Length -uint32_t CInstanceConfigurableElement::getArrayLength() const +size_t CInstanceConfigurableElement::getArrayLength() const { return _pTypeElement->getArrayLength(); } // Sync to HW -void CInstanceConfigurableElement::setSyncer(ISyncer* pSyncer) +void CInstanceConfigurableElement::setSyncer(ISyncer *pSyncer) { assert(!_pSyncer); @@ -153,7 +149,7 @@ void CInstanceConfigurableElement::unsetSyncer() } // Syncer -ISyncer* CInstanceConfigurableElement::getSyncer() const +ISyncer *CInstanceConfigurableElement::getSyncer() const { if (_pSyncer) { @@ -164,7 +160,7 @@ ISyncer* CInstanceConfigurableElement::getSyncer() const } // Syncer set (descendant) -void CInstanceConfigurableElement::fillSyncerSetFromDescendant(CSyncerSet& syncerSet) const +void CInstanceConfigurableElement::fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const { if (_pSyncer) { @@ -175,7 +171,7 @@ void CInstanceConfigurableElement::fillSyncerSetFromDescendant(CSyncerSet& synce } } -bool CInstanceConfigurableElement::sync(CParameterAccessContext& parameterAccessContext) const +bool CInstanceConfigurableElement::sync(CParameterAccessContext ¶meterAccessContext) const { if (!parameterAccessContext.getAutoSync()) { @@ -183,11 +179,12 @@ bool CInstanceConfigurableElement::sync(CParameterAccessContext& parameterAccess // This is not an error, but the expected behavior so return true anyway. return true; } - ISyncer* pSyncer = getSyncer(); + ISyncer *pSyncer = getSyncer(); if (!pSyncer) { - parameterAccessContext.setError("Unable to synchronize modification. No Syncer object associated to configurable element:"); + parameterAccessContext.setError("Unable to synchronize modification. No Syncer object " + "associated to configurable element:"); return false; } @@ -203,9 +200,10 @@ bool CInstanceConfigurableElement::sync(CParameterAccessContext& parameterAccess } // Check parameter access path well formed for leaf elements -bool CInstanceConfigurableElement::checkPathExhausted(CPathNavigator& pathNavigator, CErrorContext& errorContext) +bool CInstanceConfigurableElement::checkPathExhausted(CPathNavigator &pathNavigator, + utility::ErrorContext &errorContext) { - std::string* pStrChildName = pathNavigator.next(); + std::string *pStrChildName = pathNavigator.next(); if (pStrChildName) { @@ -217,9 +215,10 @@ bool CInstanceConfigurableElement::checkPathExhausted(CPathNavigator& pathNaviga return true; } -void CInstanceConfigurableElement::toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const +void CInstanceConfigurableElement::structureToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { - base::toXml(xmlElement, serializingContext); + base::structureToXml(xmlElement, serializingContext); // Since Description belongs to the Type of Element, delegate it to the type element. getTypeElement()->setXmlDescriptionAttribute(xmlElement); } diff --git a/parameter/InstanceConfigurableElement.h b/parameter/InstanceConfigurableElement.h index eea3df6..0b4a7f9 100644 --- a/parameter/InstanceConfigurableElement.h +++ b/parameter/InstanceConfigurableElement.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,7 +29,9 @@ */ #pragma once -#include "ConfigurableElementWithMapping.h" +#include "parameter_export.h" + +#include "ConfigurableElement.h" #include "TypeElement.h" #include <list> @@ -39,10 +41,11 @@ class IMapper; class CParameterBlackboard; class CParameterAccessContext; -class CInstanceConfigurableElement : public CConfigurableElementWithMapping +class PARAMETER_EXPORT CInstanceConfigurableElement : public CConfigurableElement { public: - enum Type { + enum Type + { EBitParameter, EBitParameterBlock, EParameter, @@ -51,12 +54,12 @@ public: EComponent }; - CInstanceConfigurableElement(const std::string& strName, const CTypeElement* pTypeElement); + CInstanceConfigurableElement(const std::string &strName, const CTypeElement *pTypeElement); // Instantiated type - const CTypeElement* getTypeElement() const; + const CTypeElement *getTypeElement() const; - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const; + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const; /** * Returns the mapping data associated to the type element of the current @@ -64,71 +67,59 @@ public: * * @return A std::string containing the formatted mapping */ - std::string getFormattedMapping() const; + std::string getFormattedMapping() const override; // From CElement virtual std::string getKind() const; + std::string getXmlElementName() const override; // Syncer to/from HW - void setSyncer(ISyncer* pSyncer); + void setSyncer(ISyncer *pSyncer); void unsetSyncer(); // Type virtual Type getType() const = 0; // Mapping execution - bool map(IMapper& mapper, std::string& strError); + bool map(IMapper &mapper, std::string &strError); // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // Scalar or Array? bool isScalar() const; // Array Length - uint32_t getArrayLength() const; - - /** - * Get the list of all the ancestors that have a mapping. - * - * The mapping is represented as a std::string of all the mapping data (key:value) defined in the - * context of the element. - * In this class, the method is generic and calls its parent getListOfElementsWithMappings(...) - * method. - * - * @param[in:out] configurableElementPath List of all the ConfigurableElements found - * that have a mapping. Elements are added at the end of the list, so the root Element will be - * the last one. - */ - virtual void getListOfElementsWithMapping(std::list<const CConfigurableElement*>& - configurableElementPath) const; + size_t getArrayLength() const; - virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; + virtual void structureToXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const; protected: // Syncer - virtual ISyncer* getSyncer() const; + virtual ISyncer *getSyncer() const; // Syncer set (descendant) - virtual void fillSyncerSetFromDescendant(CSyncerSet& syncerSet) const; + virtual void fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const; /** * Performs the sync if the AutoSync is enabled. * If AutoSync is disabled, any call to sync will returns true, even if synchronization has not * been done. It will happen when the AutoSync will be switched back on. * - * @param[in:out] parameterAccessContext Parameter access context object + * @param[in,out] parameterAccessContext Parameter access context object * * @return true if the synchronization succeded or if the AutoSync is off, false otherwise. */ - bool sync(CParameterAccessContext& parameterAccessContext) const; + bool sync(CParameterAccessContext ¶meterAccessContext) const; // Check parameter access path well formed for leaf elements - static bool checkPathExhausted(CPathNavigator& pathNavigator, CErrorContext& errorContext); + static bool checkPathExhausted(CPathNavigator &pathNavigator, + utility::ErrorContext &errorContext); + private: // Type Element - const CTypeElement* _pTypeElement; + const CTypeElement *_pTypeElement; // Sync to HW - ISyncer* _pSyncer; + ISyncer *_pSyncer{nullptr}; }; - diff --git a/parameter/InstanceDefinition.cpp b/parameter/InstanceDefinition.cpp index 74498ac..e461fa4 100644 --- a/parameter/InstanceDefinition.cpp +++ b/parameter/InstanceDefinition.cpp @@ -32,10 +32,6 @@ #define base CTypeElement -CInstanceDefinition::CInstanceDefinition() -{ -} - std::string CInstanceDefinition::getKind() const { return "InstanceDefinition"; @@ -46,7 +42,7 @@ bool CInstanceDefinition::childrenAreDynamic() const return true; } -CInstanceConfigurableElement* CInstanceDefinition::doInstantiate() const +CInstanceConfigurableElement *CInstanceDefinition::doInstantiate() const { // Element not supposed to be instantiated direcly assert(0); @@ -54,7 +50,7 @@ CInstanceConfigurableElement* CInstanceDefinition::doInstantiate() const return NULL; } -void CInstanceDefinition::createInstances(CElement* pFatherElement) +void CInstanceDefinition::createInstances(CElement *pFatherElement) { populate(pFatherElement); } diff --git a/parameter/InstanceDefinition.h b/parameter/InstanceDefinition.h index 046f76c..212c535 100644 --- a/parameter/InstanceDefinition.h +++ b/parameter/InstanceDefinition.h @@ -36,12 +36,11 @@ class CInstanceDefinition : public CTypeElement { public: - CInstanceDefinition(); - - void createInstances(CElement* pFatherElement); + void createInstances(CElement *pFatherElement); virtual std::string getKind() const; + private: virtual bool childrenAreDynamic() const; - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; }; diff --git a/parameter/IntegerParameterType.cpp b/parameter/IntegerParameterType.cpp index 2d48d53..4899514 100644 --- a/parameter/IntegerParameterType.cpp +++ b/parameter/IntegerParameterType.cpp @@ -42,7 +42,7 @@ using std::string; using std::ostringstream; -CIntegerParameterType::CIntegerParameterType(const string& strName) : base(strName), _uiMin(0), _uiMax(uint32_t(-1)) +CIntegerParameterType::CIntegerParameterType(const string &strName) : base(strName) { } @@ -59,7 +59,7 @@ bool CIntegerParameterType::childrenAreDynamic() const } // Element properties -void CIntegerParameterType::showProperties(string& strResult) const +void CIntegerParameterType::showProperties(string &strResult) const { base::showProperties(strResult); @@ -70,16 +70,16 @@ void CIntegerParameterType::showProperties(string& strResult) const // Min strResult += "Min: "; - strResult += _bSigned ? CUtility::toString((int32_t)_uiMin) : CUtility::toString(_uiMin); + strResult += _bSigned ? std::to_string((int32_t)_uiMin) : std::to_string(_uiMin); strResult += "\n"; // Max strResult += "Max: "; - strResult += _bSigned ? CUtility::toString((int32_t)_uiMax) : CUtility::toString(_uiMax); + strResult += _bSigned ? std::to_string((int32_t)_uiMax) : std::to_string(_uiMax); strResult += "\n"; // Check if there's an adaptation object available - const CParameterAdaptation* pParameterAdaption = getParameterAdaptation(); + const CParameterAdaptation *pParameterAdaption = getParameterAdaptation(); if (pParameterAdaption) { @@ -90,56 +90,46 @@ void CIntegerParameterType::showProperties(string& strResult) const } } -bool CIntegerParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CIntegerParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Sign - _bSigned = xmlElement.getAttributeBoolean("Signed"); + xmlElement.getAttribute("Signed", _bSigned); // Size in bits - uint32_t uiSizeInBits = xmlElement.getAttributeInteger("Size"); + size_t sizeInBits = 0; + xmlElement.getAttribute("Size", sizeInBits); // Size - setSize(uiSizeInBits / 8); + setSize(sizeInBits / 8); // Min / Max + // TODO: Make IntegerParameter template if (_bSigned) { // Signed means we have one less util bit - uiSizeInBits--; + sizeInBits--; - if (xmlElement.hasAttribute("Min")) { - - _uiMin = (uint32_t)xmlElement.getAttributeSignedInteger("Min"); - } else { - - _uiMin = 1UL << uiSizeInBits; + if (!xmlElement.getAttribute("Min", (int32_t &)_uiMin)) { + _uiMin = 1U << sizeInBits; } - signExtend((int32_t&)_uiMin); - - if (xmlElement.hasAttribute("Max")) { - _uiMax = (uint32_t)xmlElement.getAttributeSignedInteger("Max"); + if (!xmlElement.getAttribute("Max", (int32_t &)_uiMax)) { - signExtend((int32_t&)_uiMax); - } else { - - _uiMax = (1UL << uiSizeInBits) - 1; + _uiMax = (1U << sizeInBits) - 1; } + signExtend((int32_t &)_uiMin); + signExtend((int32_t &)_uiMax); } else { - if (xmlElement.hasAttribute("Min")) { - - _uiMin = xmlElement.getAttributeInteger("Min"); - } else { + if (!xmlElement.getAttribute("Min", _uiMin)) { _uiMin = 0; } - if (xmlElement.hasAttribute("Max")) { - _uiMax = xmlElement.getAttributeInteger("Max"); - } else { + if (!xmlElement.getAttribute("Max", _uiMax)) { - _uiMax = (uint32_t)-1L >> (8 * sizeof(uint32_t) - uiSizeInBits); + _uiMax = ~0U >> (8 * sizeof(size_t) - sizeInBits); } } @@ -148,10 +138,11 @@ bool CIntegerParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializi } // Conversion (tuning) -bool CIntegerParameterType::toBlackboard(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::toBlackboard(const string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { // Hexa - bool bValueProvidedAsHexa = !strValue.compare(0, 2, "0x"); + bool bValueProvidedAsHexa = utility::isHexadecimal(strValue); // Get integer value from the string provided int64_t iData; @@ -170,13 +161,15 @@ bool CIntegerParameterType::toBlackboard(const string& strValue, uint32_t& uiVal signExtend(iData); } - if (!checkValueAgainstRange<int64_t>(strValue, iData, (int32_t)_uiMin, (int32_t)_uiMax, parameterAccessContext, bValueProvidedAsHexa)) { + if (!checkValueAgainstRange<int64_t>(strValue, iData, (int32_t)_uiMin, (int32_t)_uiMax, + parameterAccessContext, bValueProvidedAsHexa)) { return false; } } else { - if (!checkValueAgainstRange<uint64_t>(strValue, iData, _uiMin, _uiMax, parameterAccessContext, bValueProvidedAsHexa)) { + if (!checkValueAgainstRange<uint64_t>(strValue, iData, _uiMin, _uiMax, + parameterAccessContext, bValueProvidedAsHexa)) { return false; } @@ -187,43 +180,46 @@ bool CIntegerParameterType::toBlackboard(const string& strValue, uint32_t& uiVal return true; } -bool CIntegerParameterType::fromBlackboard(string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::fromBlackboard(string &strValue, const uint32_t &value, + CParameterAccessContext ¶meterAccessContext) const { // Check unsigned value is encodable - assert(isEncodable(uiValue, false)); + assert(isEncodable(value, false)); // Format - ostringstream strStream; + ostringstream stream; // Take care of format if (parameterAccessContext.valueSpaceIsRaw() && parameterAccessContext.outputRawFormatIsHex()) { // Hexa display with unecessary bits cleared out - strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << uiValue; + stream << "0x" << std::hex << std::uppercase << std::setw(static_cast<int>(getSize() * 2)) + << std::setfill('0') << value; } else { if (_bSigned) { - int32_t iValue = uiValue; + int32_t iValue = value; // Sign extend signExtend(iValue); - strStream << iValue; + stream << iValue; } else { - strStream << uiValue; + stream << value; } } - strValue = strStream.str(); + strValue = stream.str(); return true; } // Value access // Integer -bool CIntegerParameterType::toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::toBlackboard(uint32_t uiUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { if (uiUserValue < _uiMin || uiUserValue > _uiMax) { @@ -237,10 +233,9 @@ bool CIntegerParameterType::toBlackboard(uint32_t uiUserValue, uint32_t& uiValue return true; } -bool CIntegerParameterType::fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::fromBlackboard(uint32_t &uiUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - // Do assign uiUserValue = uiValue; @@ -248,7 +243,8 @@ bool CIntegerParameterType::fromBlackboard(uint32_t& uiUserValue, uint32_t uiVal } // Signed Integer -bool CIntegerParameterType::toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::toBlackboard(int32_t iUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { if (iUserValue < (int32_t)_uiMin || iUserValue > (int32_t)_uiMax) { @@ -262,10 +258,9 @@ bool CIntegerParameterType::toBlackboard(int32_t iUserValue, uint32_t& uiValue, return true; } -bool CIntegerParameterType::fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::fromBlackboard(int32_t &iUserValue, uint32_t uiValue, + CParameterAccessContext & /*ctx*/) const { - (void)parameterAccessContext; - int32_t iValue = uiValue; // Sign extend @@ -278,10 +273,11 @@ bool CIntegerParameterType::fromBlackboard(int32_t& iUserValue, uint32_t uiValue } // Double -bool CIntegerParameterType::toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const { // Check if there's an adaptation object available - const CParameterAdaptation* pParameterAdaption = getParameterAdaptation(); + const CParameterAdaptation *pParameterAdaption = getParameterAdaptation(); if (!pParameterAdaption) { @@ -317,10 +313,11 @@ bool CIntegerParameterType::toBlackboard(double dUserValue, uint32_t& uiValue, C return true; } -bool CIntegerParameterType::fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CIntegerParameterType::fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const { // Check if there's an adaptation object available - const CParameterAdaptation* pParameterAdaption = getParameterAdaptation(); + const CParameterAdaptation *pParameterAdaption = getParameterAdaptation(); if (!pParameterAdaption) { @@ -366,7 +363,9 @@ int CIntegerParameterType::toPlainInteger(int iSizeOptimizedData) const } // Convert value provided by the user as a string into an int64 -bool CIntegerParameterType::convertValueFromString(const string& strValue, int64_t& iData, CParameterAccessContext& parameterAccessContext) const { +bool CIntegerParameterType::convertValueFromString( + const string &strValue, int64_t &iData, CParameterAccessContext ¶meterAccessContext) const +{ // Reset errno to check if it is updated during the conversion (strtol/strtoul) errno = 0; @@ -381,11 +380,12 @@ bool CIntegerParameterType::convertValueFromString(const string& strValue, int64 iData = strtoull(strValue.c_str(), &pcStrEnd, 0); } - // Conversion error when the input string does not contain only digits or the number is out of range (int32_t type) + // Conversion error when the input string does not contain only digits or the number is out of + // range (int32_t type) if (errno || (*pcStrEnd != '\0')) { string strError; - strError = "Impossible to convert value " + strValue + " for " + getKind(); + strError = "Impossible to convert value " + strValue + " for " + getKind(); parameterAccessContext.setError(strError); @@ -396,29 +396,35 @@ bool CIntegerParameterType::convertValueFromString(const string& strValue, int64 } // Range checking -template <typename type> bool CIntegerParameterType::checkValueAgainstRange(const string& strValue, type value, type minValue, type maxValue, CParameterAccessContext& parameterAccessContext, bool bHexaValue) const +template <typename type> +bool CIntegerParameterType::checkValueAgainstRange(const string &strValue, type value, + type minValue, type maxValue, + CParameterAccessContext ¶meterAccessContext, + bool bHexaValue) const { if (value < minValue || value > maxValue) { - ostringstream strStream; + ostringstream stream; - strStream << "Value " << strValue << " standing out of admitted range ["; + stream << "Value " << strValue << " standing out of admitted range ["; if (bHexaValue) { + stream << "0x" << std::hex << std::uppercase + << std::setw(static_cast<int>(getSize() * 2)) << std::setfill('0'); // Format Min - strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(minValue); + stream << minValue; // Format Max - strStream << ", 0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(maxValue); + stream << maxValue; } else { - strStream << minValue << ", " << maxValue; + stream << minValue << ", " << maxValue; } - strStream << "] for " << getKind(); + stream << "] for " << getKind(); - parameterAccessContext.setError(strStream.str()); + parameterAccessContext.setError(stream.str()); return false; } @@ -426,37 +432,37 @@ template <typename type> bool CIntegerParameterType::checkValueAgainstRange(cons } // Adaptation element retrieval -const CParameterAdaptation* CIntegerParameterType::getParameterAdaptation() const +const CParameterAdaptation *CIntegerParameterType::getParameterAdaptation() const { - return static_cast<const CParameterAdaptation*>(findChildOfKind("Adaptation")); + return static_cast<const CParameterAdaptation *>(findChildOfKind("Adaptation")); } // From IXmlSource -void CIntegerParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CIntegerParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Sign - xmlElement.setAttributeBoolean("Signed", _bSigned); + xmlElement.setAttribute("Signed", _bSigned); if (_bSigned) { // Mininmum - xmlElement.setAttributeString("Min", CUtility::toString((int32_t)_uiMin)); + xmlElement.setAttribute("Min", (int32_t)_uiMin); // Maximum - xmlElement.setAttributeString("Max", CUtility::toString((int32_t)_uiMax)); + xmlElement.setAttribute("Max", (int32_t)_uiMax); } else { // Minimum - xmlElement.setAttributeString("Min", CUtility::toString(_uiMin)); + xmlElement.setAttribute("Min", _uiMin); // Maximum - xmlElement.setAttributeString("Max", CUtility::toString(_uiMax)); + xmlElement.setAttribute("Max", _uiMax); } // Size - xmlElement.setAttributeString("Size", CUtility::toString(getSize() * 8)); + xmlElement.setAttribute("Size", getSize() * 8); base::toXml(xmlElement, serializingContext); - } diff --git a/parameter/IntegerParameterType.h b/parameter/IntegerParameterType.h index 53bd4a8..5eea40b 100644 --- a/parameter/IntegerParameterType.h +++ b/parameter/IntegerParameterType.h @@ -32,39 +32,48 @@ #include "ParameterType.h" #include <string> +#include <limits> class CParameterAdaptation; class CIntegerParameterType : public CParameterType { public: - CIntegerParameterType(const std::string& strName); + CIntegerParameterType(const std::string &strName); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; /// Conversion // String - virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Integer - virtual bool toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(uint32_t uiUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(uint32_t &uiUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Signed Integer - virtual bool toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(int32_t iUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(int32_t &iUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Double - virtual bool toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Default value handling (simulation only) virtual uint32_t getDefaultValue() const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // Integer conversion virtual int toPlainInteger(int iSizeOptimizedData) const; @@ -77,17 +86,21 @@ private: virtual bool childrenAreDynamic() const; // Conversion from std::string - bool convertValueFromString(const std::string& strValue, int64_t& iData, CParameterAccessContext& parameterAccessContext) const; + bool convertValueFromString(const std::string &strValue, int64_t &iData, + CParameterAccessContext ¶meterAccessContext) const; // Range checking - template <typename type> bool checkValueAgainstRange(const std::string& strValue, type value, type minValue, type maxValue, CParameterAccessContext& parameterAccessContext, bool bHexaValue) const; + template <typename type> + bool checkValueAgainstRange(const std::string &strValue, type value, type minValue, + type maxValue, CParameterAccessContext ¶meterAccessContext, + bool bHexaValue) const; // Adaptation element retrieval - const CParameterAdaptation* getParameterAdaptation() const; + const CParameterAdaptation *getParameterAdaptation() const; // Signing - bool _bSigned; + bool _bSigned{false}; // Range - uint32_t _uiMin; - uint32_t _uiMax; + uint32_t _uiMin{0}; + uint32_t _uiMax{std::numeric_limits<uint32_t>::max()}; }; diff --git a/parameter/KindElement.h b/parameter/KindElement.h index df826ff..848180a 100644 --- a/parameter/KindElement.h +++ b/parameter/KindElement.h @@ -36,15 +36,12 @@ class CKindElement : public CElement { public: - CKindElement(const std::string& strName, const std::string& strKind) : CElement(strName), _strKind(strKind) + CKindElement(const std::string &strName, const std::string &strKind) + : CElement(strName), _strKind(strKind) { } - virtual std::string getKind() const - { - return _strKind; - } + virtual std::string getKind() const { return _strKind; } private: - std::string _strKind; }; diff --git a/parameter/KindElementBuilderTemplate.h b/parameter/KindElementBuilderTemplate.h index dc576db..ffce475 100644 --- a/parameter/KindElementBuilderTemplate.h +++ b/parameter/KindElementBuilderTemplate.h @@ -37,7 +37,7 @@ class TKindElementBuilderTemplate : public CElementBuilder public: TKindElementBuilderTemplate() : CElementBuilder() {} - virtual CElement* createElement(const CXmlElement& xmlElement) const + virtual CElement *createElement(const CXmlElement &xmlElement) const { return new ElementType(xmlElement.getNameAttribute(), xmlElement.getType()); } diff --git a/parameter/LinearParameterAdaptation.cpp b/parameter/LinearParameterAdaptation.cpp index ae925a7..5c8002d 100644 --- a/parameter/LinearParameterAdaptation.cpp +++ b/parameter/LinearParameterAdaptation.cpp @@ -28,65 +28,50 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LinearParameterAdaptation.h" -#include "Utility.h" #define base CParameterAdaptation using std::string; -CLinearParameterAdaptation::CLinearParameterAdaptation() : base("Linear"), _dSlopeNumerator(1), _dSlopeDenominator(1) +CLinearParameterAdaptation::CLinearParameterAdaptation() : base("Linear") { } -CLinearParameterAdaptation::CLinearParameterAdaptation(const string& strType) : - base(strType), _dSlopeNumerator(1), _dSlopeDenominator(1) +CLinearParameterAdaptation::CLinearParameterAdaptation(const string &strType) : base(strType) { } // Element properties -void CLinearParameterAdaptation::showProperties(string& strResult) const +void CLinearParameterAdaptation::showProperties(string &strResult) const { base::showProperties(strResult); // SlopeNumerator strResult += " - SlopeNumerator: "; - strResult += CUtility::toString(_dSlopeNumerator); + strResult += std::to_string(_dSlopeNumerator); strResult += "\n"; // SlopeDenominator strResult += " - SlopeDenominator: "; - strResult += CUtility::toString(_dSlopeDenominator); + strResult += std::to_string(_dSlopeDenominator); strResult += "\n"; } // From IXmlSink -bool CLinearParameterAdaptation::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CLinearParameterAdaptation::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Get SlopeNumerator - if (xmlElement.hasAttribute("SlopeNumerator")) { + xmlElement.getAttribute("SlopeNumerator", _dSlopeNumerator); - _dSlopeNumerator = xmlElement.getAttributeDouble("SlopeNumerator"); - - } else { - // Default - _dSlopeNumerator = 1; - } // Get SlopeDenominator - if (xmlElement.hasAttribute("SlopeDenominator")) { - - _dSlopeDenominator = xmlElement.getAttributeDouble("SlopeDenominator"); + if (xmlElement.getAttribute("SlopeDenominator", _dSlopeDenominator) && + (_dSlopeDenominator == 0)) { // Avoid by 0 division errors - if (_dSlopeDenominator == 0) { - - serializingContext.setError("SlopeDenominator attribute can't be 0 on element" + xmlElement.getPath()); - - return false; - } - - } else { - // Default - _dSlopeDenominator = 1; + serializingContext.setError("SlopeDenominator attribute can't be 0 on element" + + xmlElement.getPath()); + return false; } // Base diff --git a/parameter/LinearParameterAdaptation.h b/parameter/LinearParameterAdaptation.h index 8037c31..0c6ff5e 100644 --- a/parameter/LinearParameterAdaptation.h +++ b/parameter/LinearParameterAdaptation.h @@ -37,19 +37,20 @@ class CLinearParameterAdaptation : public CParameterAdaptation { public: CLinearParameterAdaptation(); - CLinearParameterAdaptation(const std::string& strType); + CLinearParameterAdaptation(const std::string &strType); // Conversions virtual int64_t fromUserValue(double dValue) const; virtual double toUserValue(int64_t iValue) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); + private: // Slope attributes - double _dSlopeNumerator; - double _dSlopeDenominator; + double _dSlopeNumerator{1}; + double _dSlopeDenominator{1}; }; diff --git a/parameter/LogarithmicParameterAdaptation.cpp b/parameter/LogarithmicParameterAdaptation.cpp index bca4948..128ab07 100644 --- a/parameter/LogarithmicParameterAdaptation.cpp +++ b/parameter/LogarithmicParameterAdaptation.cpp @@ -29,59 +29,54 @@ */ #include "LogarithmicParameterAdaptation.h" -#include "Utility.h" -#include <math.h> +#include <cmath> +#include <limits> +#include <algorithm> #define base CLinearParameterAdaptation -// M_E is the base of the natural logarithm for 'e' from math.h -CLogarithmicParameterAdaptation::CLogarithmicParameterAdaptation() : base("Logarithmic"), - _dLogarithmBase(M_E), _dFloorValue(-INFINITY) +CLogarithmicParameterAdaptation::CLogarithmicParameterAdaptation() : base("Logarithmic") { + static_assert(std::numeric_limits<double>::is_iec559, + "Only double-precision floating points that are compliant with" + " IEC 559 (aka IEEE 754) are supported"); } // Element properties -void CLogarithmicParameterAdaptation::showProperties(std::string& strResult) const +void CLogarithmicParameterAdaptation::showProperties(std::string &strResult) const { base::showProperties(strResult); strResult += " - LogarithmBase: "; - strResult += CUtility::toString(_dLogarithmBase); + strResult += std::to_string(_dLogarithmBase); strResult += "\n"; strResult += " - FloorValue: "; - strResult += CUtility::toString(_dFloorValue); + strResult += std::to_string(_dFloorValue); strResult += "\n"; } -bool CLogarithmicParameterAdaptation::fromXml(const CXmlElement& xmlElement, - CXmlSerializingContext& serializingContext) +bool CLogarithmicParameterAdaptation::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { - - if (xmlElement.hasAttribute("LogarithmBase")) { - - _dLogarithmBase = xmlElement.getAttributeDouble("LogarithmBase"); - + if (xmlElement.getAttribute("LogarithmBase", _dLogarithmBase) && + (_dLogarithmBase <= 0 || _dLogarithmBase == 1)) { // Avoid negative and 1 values - if (_dLogarithmBase <= 0 || _dLogarithmBase == 1) { - serializingContext.setError("LogarithmBase attribute cannot be negative or 1 on element" - + xmlElement.getPath()); + serializingContext.setError("LogarithmBase attribute cannot be negative or 1 on element" + + xmlElement.getPath()); - return false; - } + return false; } - if (xmlElement.hasAttribute("FloorValue")) { - _dFloorValue = xmlElement.getAttributeDouble("FloorValue"); - } + xmlElement.getAttribute("FloorValue", _dFloorValue); + // Base return base::fromXml(xmlElement, serializingContext); } - -int64_t CLogarithmicParameterAdaptation::fromUserValue(double dValue) const +int64_t CLogarithmicParameterAdaptation::fromUserValue(double value) const { - return fmax(round(base::fromUserValue(log(dValue) / log(_dLogarithmBase))), - _dFloorValue); + return std::max(base::fromUserValue(log(value) / log(_dLogarithmBase)), + static_cast<int64_t>(_dFloorValue)); } double CLogarithmicParameterAdaptation::toUserValue(int64_t iValue) const diff --git a/parameter/LogarithmicParameterAdaptation.h b/parameter/LogarithmicParameterAdaptation.h index 3b7fd4d..9c2553b 100644 --- a/parameter/LogarithmicParameterAdaptation.h +++ b/parameter/LogarithmicParameterAdaptation.h @@ -31,6 +31,8 @@ #pragma once #include "LinearParameterAdaptation.h" +#include <cmath> +#include <limits> /** * This class is used to perform a logarithmic adapation of type: @@ -54,18 +56,23 @@ public: virtual int64_t fromUserValue(double dValue) const; virtual double toUserValue(int64_t iValue) const; - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; + + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); private: /** * _dLogarithmBase characterizes the new logarithm logB(x) with * the following property: logB(x) = log(x) / log(_dLogarithmBase). * log being the base-e logarithm. + * + * std::exp(1) == e^1 == e == natural logarithm base + * Make sure there is no precision lose by using std::exp overload that + * return the same type as _dLogarithmBase */ - double _dLogarithmBase; + double _dLogarithmBase{std::exp(decltype(_dLogarithmBase){1})}; /** * _dFloorValue reflects the lower bound for volume attenuation */ - double _dFloorValue; + double _dFloorValue{-std::numeric_limits<double>::infinity()}; }; diff --git a/parameter/BinarySerializableElement.h b/parameter/LoggingElementBuilderTemplate.cpp index 222b8e9..8c87a47 100644 --- a/parameter/BinarySerializableElement.h +++ b/parameter/LoggingElementBuilderTemplate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,22 +27,14 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#pragma once -#include "Element.h" -#include "BinaryStream.h" +#include "LoggingElementBuilderTemplate.h" +#include <XmlElement.h> -#include <string> - -class CBinarySerializableElement : public CElement +namespace details { -public: - CBinarySerializableElement(const std::string& strName = ""); - - // Serialization - virtual void binarySerialize(CBinaryStream& binaryStream); - - // Data size - virtual size_t getDataSize() const; -protected: -}; +std::string getName(const CXmlElement &xmlElement) +{ + return xmlElement.getNameAttribute(); +} +} diff --git a/parameter/LoggingElementBuilderTemplate.h b/parameter/LoggingElementBuilderTemplate.h new file mode 100644 index 0000000..1bfff06 --- /dev/null +++ b/parameter/LoggingElementBuilderTemplate.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +#include <parameter_export.h> + +#include "ElementBuilder.h" +#include <log/Logger.h> + +namespace details +{ +/** Part of the implementation of `TLoggingElementBuilderTemplate` + * that does not need to be template. + * + * If this was implemented in this header, the xmlElement implementation + * would leak to sources including this header. + * + * Plugins are including this header. As a result they would include + * the xmlElement implementation if it was not hidden in a cpp. + * + * FIXME: The xml concept (forward declared) is still leaked to the plugin. + * A solution would be have two level of builders: + * - a PluginBuilder that wraps the plugin + * - and an ElementBuilder that wraps the PluginBuilder + * This way the plugin can only see the PluginBuilder and is not + * contaminated by any core specific concept. + * + * @param[in] xmlElement the XML element + * @return the "Name" attribute value of an xml element or + * empty string if attribute is not present + * + */ +std::string PARAMETER_EXPORT getName(const CXmlElement &xmlElement); +} + +/** + * Builder for elements which need logger at construction + * + * @tparam ElementType the type of the element to build + */ +template <class ElementType> +class TLoggingElementBuilderTemplate : public CElementBuilder +{ +public: + /** + * Class Constructor + * + * @param[in] logger the logger provided by the client + */ + TLoggingElementBuilderTemplate(core::log::Logger &logger) : CElementBuilder(), mLogger(logger) + { + } + + /** + * Create a new element + * + * @param[in] xmlElement the description of the object to create + * + * @return pointer to the generated element + */ + virtual CElement *createElement(const CXmlElement &xmlElement) const + { + return new ElementType(details::getName(xmlElement), mLogger); + } + +private: + /** Application Logger */ + core::log::Logger &mLogger; +}; diff --git a/parameter/Mapper.h b/parameter/Mapper.h index fcf751a..d2d76d0 100644 --- a/parameter/Mapper.h +++ b/parameter/Mapper.h @@ -36,9 +36,10 @@ class CInstanceConfigurableElement; class IMapper { public: - virtual bool mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, std::string& strError) = 0; + virtual bool mapBegin(CInstanceConfigurableElement *pInstanceConfigurableElement, + bool &bKeepDiving, std::string &strError) = 0; virtual void mapEnd() = 0; protected: - virtual ~IMapper() {} + virtual ~IMapper() = default; }; diff --git a/parameter/MappingContext.cpp b/parameter/MappingContext.cpp index 045fbd7..1235e31 100644 --- a/parameter/MappingContext.cpp +++ b/parameter/MappingContext.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -28,113 +28,53 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MappingContext.h" -#include <assert.h> -#include <string.h> -#include <stdlib.h> +#include <cassert> +#include <algorithm> +#include <cstdlib> using std::string; -CMappingContext::CMappingContext(size_t uiNbItemTypes) : _pstItemArray(new CMappingContext::SItem[uiNbItemTypes]), _uiNbItemTypes(uiNbItemTypes) -{ - // Clear items - memset(_pstItemArray, 0, sizeof(*_pstItemArray) * uiNbItemTypes); -} - -CMappingContext::~CMappingContext() -{ - delete [] _pstItemArray; -} - -// Copy constructor -CMappingContext::CMappingContext(const CMappingContext& from) : _pstItemArray(new CMappingContext::SItem[from._uiNbItemTypes]), _uiNbItemTypes(from._uiNbItemTypes) -{ - // Copy content items - memcpy(_pstItemArray, from._pstItemArray, sizeof(*_pstItemArray) * _uiNbItemTypes); -} - -// Affectation -CMappingContext& CMappingContext::operator=(const CMappingContext& right) -{ - if (&right != this) { - - // Size - _uiNbItemTypes = right._uiNbItemTypes; - - // Content - // Delete previous array - delete [] _pstItemArray; - - // Reallocate it - _pstItemArray = new CMappingContext::SItem[_uiNbItemTypes]; - - // Copy content items - memcpy(_pstItemArray, right._pstItemArray, sizeof(*_pstItemArray) * _uiNbItemTypes); - } - return *this; -} - // Item access -bool CMappingContext::setItem(uint32_t uiItemType, const string* pStrKey, const string* pStrItem) +bool CMappingContext::setItem(size_t itemType, const string *pStrKey, const string *pStrItem) { - size_t uiIndex; - - // Do some checks - for (uiIndex = 0; uiIndex < _uiNbItemTypes; uiIndex++) { - - // Does key already exist ? - assert(_pstItemArray[uiIndex].strKey != pStrKey); - } - - if (_pstItemArray[uiItemType].bSet) { - + if (iSet(itemType)) { // Already set! return false; } // Set item key - _pstItemArray[uiItemType].strKey = pStrKey; + mItems[itemType].strKey = pStrKey; // Set item value - _pstItemArray[uiItemType].strItem = pStrItem; - - // Now is set - _pstItemArray[uiItemType].bSet = true; + mItems[itemType].strItem = pStrItem; return true; } -const string& CMappingContext::getItem(uint32_t uiItemType) const +const string &CMappingContext::getItem(size_t itemType) const { - return *_pstItemArray[uiItemType].strItem; + return *mItems[itemType].strItem; } -uint32_t CMappingContext::getItemAsInteger(uint32_t uiItemType) const +size_t CMappingContext::getItemAsInteger(size_t itemType) const { - if (!_pstItemArray[uiItemType].strItem) { + if (!mItems[itemType].strItem) { return 0; } - return strtoul(_pstItemArray[uiItemType].strItem->c_str(), NULL, 0); + return strtoul(mItems[itemType].strItem->c_str(), NULL, 0); } -const string* CMappingContext::getItem(const string& strKey) const +const string *CMappingContext::getItem(const string &strKey) const { - size_t uiItemType; - - for (uiItemType = 0; uiItemType < _uiNbItemTypes; uiItemType++) { - - if (_pstItemArray[uiItemType].strKey != NULL && - strKey == *_pstItemArray[uiItemType].strKey) { - - return _pstItemArray[uiItemType].strItem; - } - } - - return NULL; + auto itemFound = find_if(begin(mItems), end(mItems), [&](const SItem &item) { + return item.strKey != NULL && strKey == *item.strKey; + }); + return (itemFound != end(mItems)) ? itemFound->strKey : NULL; } -bool CMappingContext::iSet(uint32_t uiItemType) const +bool CMappingContext::iSet(size_t itemType) const { - return _pstItemArray[uiItemType].bSet; + return mItems[itemType].strItem != nullptr; } diff --git a/parameter/MappingContext.h b/parameter/MappingContext.h index 91fd1f4..03b3317 100644 --- a/parameter/MappingContext.h +++ b/parameter/MappingContext.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,42 +29,38 @@ */ #pragma once +#include "parameter_export.h" + #include <stdint.h> #include <string> +#include <vector> -class CMappingContext +class PARAMETER_EXPORT CMappingContext { +private: // Item structure - struct SItem { - const std::string* strKey; - const std::string* strItem; - bool bSet; + struct SItem + { + const std::string *strKey{nullptr}; + const std::string *strItem{nullptr}; }; public: - // Regular Constructor - CMappingContext(size_t uiNbItemTypes); - ~CMappingContext(); - - // Copy constructor - CMappingContext(const CMappingContext& from); - - // Affectation - CMappingContext& operator=(const CMappingContext& right); + CMappingContext(size_t uiNbItemTypes) : mItems(uiNbItemTypes) {} // Item access /** * Set context mapping item key and value. * - * @param[in] uiItemType Mapping item index. + * @param[in] itemType Mapping item index. * @param[in] pStrKey Mapping item key name. * @param[in] pStrItem Mapping item value. * * @return False if already set, true else. */ - bool setItem(uint32_t uiItemType, const std::string* pStrKey, const std::string* pStrItem); - const std::string& getItem(uint32_t uiItemType) const; - uint32_t getItemAsInteger(uint32_t uiItemType) const; + bool setItem(size_t itemType, const std::string *pStrKey, const std::string *pStrItem); + const std::string &getItem(size_t itemType) const; + size_t getItemAsInteger(size_t itemType) const; /** * Get mapping item value from its key name. * @@ -72,13 +68,12 @@ public: * * @return Mapping item value pointer if found, NULL else. */ - const std::string* getItem(const std::string& strKey) const; - bool iSet(uint32_t uiItemType) const; + const std::string *getItem(const std::string &strKey) const; + bool iSet(size_t itemType) const; private: - // Item array - SItem* _pstItemArray; - // Items array size - size_t _uiNbItemTypes; -}; + size_t getNbItems() const { return mItems.size(); } + using Items = std::vector<SItem>; + Items mItems; +}; diff --git a/parameter/MappingData.cpp b/parameter/MappingData.cpp index b7a1a2a..cc34103 100644 --- a/parameter/MappingData.cpp +++ b/parameter/MappingData.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -32,21 +32,13 @@ #include "Utility.h" #include <assert.h> -CMappingData::CMappingData() +bool CMappingData::init(const std::string &rawMapping, std::string &error) { -} - -bool CMappingData::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) -{ - assert(xmlElement.hasAttribute("Mapping")); - - std::string strMapping = xmlElement.getAttributeString("Mapping"); - - Tokenizer mappingTok(strMapping, ","); + Tokenizer mappingTok(rawMapping, ","); std::string strMappingElement; - while (!(strMappingElement = mappingTok.next()).empty()) { + for (const auto &strMappingElement : mappingTok.split()) { std::string::size_type iFistDelimiterOccurrence = strMappingElement.find_first_of(':'); @@ -66,12 +58,12 @@ bool CMappingData::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext // Get mapping value strValue = strMappingElement.substr(iFistDelimiterOccurrence + 1); - } if (!addValue(strKey, strValue)) { - serializingContext.setError("Duplicate Mapping data: Unable to process Mapping element key = " + strKey + ", value = " + strValue + " from XML element " + xmlElement.getPath()); + error = "Unable to process Mapping element key = " + strKey + ", value = " + strValue + + ": Duplicate Mapping data"; return false; } @@ -79,7 +71,7 @@ bool CMappingData::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext return true; } -bool CMappingData::getValue(const std::string& strkey, const std::string*& pStrValue) const +bool CMappingData::getValue(const std::string &strkey, const std::string *&pStrValue) const { KeyToValueMapConstIterator it = _keyToValueMap.find(strkey); @@ -94,14 +86,10 @@ bool CMappingData::getValue(const std::string& strkey, const std::string*& pStrV std::string CMappingData::asString() const { - std::string strValue; - - CUtility::asString(_keyToValueMap, strValue, ", ", ":"); - - return strValue; + return utility::asString(_keyToValueMap, ", ", ":"); } -bool CMappingData::addValue(const std::string& strkey, const std::string& strValue) +bool CMappingData::addValue(const std::string &strkey, const std::string &strValue) { if (_keyToValueMap.find(strkey) != _keyToValueMap.end()) { @@ -111,4 +99,3 @@ bool CMappingData::addValue(const std::string& strkey, const std::string& strVal return true; } - diff --git a/parameter/MappingData.h b/parameter/MappingData.h index 45908b6..bd76b79 100644 --- a/parameter/MappingData.h +++ b/parameter/MappingData.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,21 +29,25 @@ */ #pragma once -#include "XmlSink.h" #include <string> #include <map> -class CMappingData : public IXmlSink +class CMappingData { typedef std::map<std::string, std::string>::const_iterator KeyToValueMapConstIterator; -public: - CMappingData(); - // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); +public: + /** Initialize mapping data through a raw value + * + * @param[in] rawMapping the raw mapping data which has to be parsed. + * This raw value is a succession of pair "key:value" separated with comma. + * @param[out] error description of the error if there is one, empty otherwise + * @return true on success, false otherwise + */ + bool init(const std::string &rawMapping, std::string &error); // Query - bool getValue(const std::string& strkey, const std::string*& pStrValue) const; + bool getValue(const std::string &strkey, const std::string *&pStrValue) const; /** * Formats the mapping as a list of comma-space separated key:value pairs @@ -53,7 +57,7 @@ public: std::string asString() const; private: - bool addValue(const std::string& strkey, const std::string& strValue); + bool addValue(const std::string &strkey, const std::string &strValue); std::map<std::string, std::string> _keyToValueMap; }; diff --git a/parameter/NamedElementBuilderTemplate.h b/parameter/NamedElementBuilderTemplate.h index 1334452..8c22956 100644 --- a/parameter/NamedElementBuilderTemplate.h +++ b/parameter/NamedElementBuilderTemplate.h @@ -35,9 +35,7 @@ template <class ElementType> class TNamedElementBuilderTemplate : public CElementBuilder { public: - TNamedElementBuilderTemplate() : CElementBuilder() {} - - virtual CElement* createElement(const CXmlElement& xmlElement) const + virtual CElement *createElement(const CXmlElement &xmlElement) const { return new ElementType(xmlElement.getNameAttribute()); } diff --git a/parameter/Parameter.cpp b/parameter/Parameter.cpp index e7de9ed..ca1d5ef 100644 --- a/parameter/Parameter.cpp +++ b/parameter/Parameter.cpp @@ -37,7 +37,8 @@ using std::string; -CParameter::CParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CParameter::CParameter(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } @@ -47,85 +48,99 @@ CInstanceConfigurableElement::Type CParameter::getType() const } // XML configuration settings parsing/composing -bool CParameter::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const +bool CParameter::serializeXmlSettings(CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const { // Check for value space handleValueSpaceAttribute(xmlConfigurationSettingsElementContent, configurationAccessContext); // Base - return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, configurationAccessContext); + return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, + configurationAccessContext); } // Value space handling for configuration import -void CParameter::handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const +void CParameter::handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const { // Delegate to type - static_cast<const CParameterType*>(getTypeElement())->handleValueSpaceAttribute(xmlConfigurableElementSettingsElement, configurationAccessContext); + static_cast<const CParameterType *>(getTypeElement()) + ->handleValueSpaceAttribute(xmlConfigurableElementSettingsElement, + configurationAccessContext); } -uint32_t CParameter::getFootPrint() const +size_t CParameter::getFootPrint() const { return getSize(); } -uint32_t CParameter::getSize() const +size_t CParameter::getSize() const { - return static_cast<const CParameterType*>(getTypeElement())->getSize(); + return static_cast<const CParameterType *>(getTypeElement())->getSize(); } // Used for simulation and virtual subsystems -void CParameter::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CParameter::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { // Get default value from type - uint32_t uiDefaultValue = static_cast<const CParameterType*>(getTypeElement())->getDefaultValue(); + uint32_t uiDefaultValue = + static_cast<const CParameterType *>(getTypeElement())->getDefaultValue(); // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->writeInteger(&uiDefaultValue, getSize(), getOffset() - parameterAccessContext.getBaseOffset(), parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->writeInteger(&uiDefaultValue, getSize(), + getOffset() - parameterAccessContext.getBaseOffset()); } /// Actual parameter access // String access -bool CParameter::doSetValue(const string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CParameter::doSetValue(const string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - return doSet(strValue, uiOffset, parameterAccessContext); + return doSet(strValue, offset, parameterAccessContext); } -void CParameter::doGetValue(string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +void CParameter::doGetValue(string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - doGet(strValue, uiOffset, parameterAccessContext); + doGet(strValue, offset, parameterAccessContext); } // Boolean access -bool CParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CParameter::access(bool &bValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return doAccess(bValue, bSet, parameterAccessContext); } // Integer Access -bool CParameter::accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CParameter::access(uint32_t &uiValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return doAccess(uiValue, bSet, parameterAccessContext); } // Signed Integer Access -bool CParameter::accessAsSignedInteger(int32_t& iValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CParameter::access(int32_t &iValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return doAccess(iValue, bSet, parameterAccessContext); } // Double Access -bool CParameter::accessAsDouble(double& dValue, bool bSet, CParameterAccessContext& parameterAccessContext) const +bool CParameter::access(double &dValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { return doAccess(dValue, bSet, parameterAccessContext); } // Generic Access template <typename type> -bool CParameter::doAccess(type& value, bool bSet, - CParameterAccessContext& parameterAccessContext) const +bool CParameter::doAccess(type &value, bool bSet, + CParameterAccessContext ¶meterAccessContext) const { if (bSet) { // set value @@ -134,10 +149,9 @@ bool CParameter::doAccess(type& value, bool bSet, appendParameterPathToError(parameterAccessContext); return false; - } // Synchronize - if (!sync(parameterAccessContext)){ + if (!sync(parameterAccessContext)) { appendParameterPathToError(parameterAccessContext); return false; @@ -155,33 +169,37 @@ bool CParameter::doAccess(type& value, bool bSet, } template <typename type> -bool CParameter::doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CParameter::doSet(type value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint32_t uiData; - if (!static_cast<const CParameterType*>(getTypeElement())->toBlackboard(value, uiData, parameterAccessContext)) { + if (!static_cast<const CParameterType *>(getTypeElement()) + ->toBlackboard(value, uiData, parameterAccessContext)) { return false; } // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->writeInteger(&uiData, getSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->writeInteger(&uiData, getSize(), offset); return true; } template <typename type> -bool CParameter::doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CParameter::doGet(type &value, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { uint32_t uiData = 0; // Read blackboard - const CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); // Beware this code works on little endian architectures only! - pBlackboard->readInteger(&uiData, getSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem()); + pBlackboard->readInteger(&uiData, getSize(), offset); - return static_cast<const CParameterType*>(getTypeElement())->fromBlackboard(value, uiData, parameterAccessContext); + return static_cast<const CParameterType *>(getTypeElement()) + ->fromBlackboard(value, uiData, parameterAccessContext); } diff --git a/parameter/Parameter.h b/parameter/Parameter.h index 8cf4bc5..2c97409 100644 --- a/parameter/Parameter.h +++ b/parameter/Parameter.h @@ -38,47 +38,58 @@ class CParameter : public CBaseParameter { public: - CParameter(const std::string& strName, const CTypeElement* pTypeElement); + CParameter(const std::string &strName, const CTypeElement *pTypeElement); // Instantiation, allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; // Type virtual Type getType() const; // XML configuration settings parsing/composing - virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const; + virtual bool serializeXmlSettings( + CXmlElement &xmlConfigurationSettingsElementContent, + CConfigurationAccessContext &configurationAccessContext) const; // Boolean access - virtual bool accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(bool &bValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override; // Integer Access - virtual bool accessAsInteger(uint32_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(uint32_t &uiValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override; // Signed Integer Access - virtual bool accessAsSignedInteger(int32_t& iValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(int32_t &iValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override; // Double Access - virtual bool accessAsDouble(double& dValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool access(double &dValue, bool bSet, + CParameterAccessContext ¶meterAccessContext) const override; + protected: // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; // Actual value access - virtual bool doSetValue(const std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; - virtual void doGetValue(std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + virtual bool doSetValue(const std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; + virtual void doGetValue(std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; // Value space handling for configuration import - void handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const; + void handleValueSpaceAttribute(CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const; // Size - uint32_t getSize() const; + size_t getSize() const; + private: // Generic Access template <typename type> - bool doAccess(type& value, bool bSet, CParameterAccessContext& parameterAccessContext) const; + bool doAccess(type &value, bool bSet, CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + bool doSet(type value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; template <typename type> - bool doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + bool doGet(type &value, size_t offset, CParameterAccessContext ¶meterAccessContext) const; }; diff --git a/parameter/ParameterAccessContext.cpp b/parameter/ParameterAccessContext.cpp index e228d9b..8895821 100644 --- a/parameter/ParameterAccessContext.cpp +++ b/parameter/ParameterAccessContext.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,54 +29,48 @@ */ #include "ParameterAccessContext.h" -#define base CErrorContext +#define base utility::ErrorContext -CParameterAccessContext::CParameterAccessContext(std::string& strError, - CParameterBlackboard* pParameterBlackboard, - bool bValueSpaceIsRaw, - bool bOutputRawFormatIsHex, - uint32_t uiBaseOffset) +CParameterAccessContext::CParameterAccessContext(std::string &strError, + CParameterBlackboard *pParameterBlackboard, + bool bValueSpaceIsRaw, bool bOutputRawFormatIsHex, + size_t baseOffset) : base(strError), _pParameterBlackboard(pParameterBlackboard), - _bValueSpaceIsRaw(bValueSpaceIsRaw), _bOutputRawFormatIsHex(bOutputRawFormatIsHex), - _bBigEndianSubsystem(false), _bAutoSync(true), _uiBaseOffset(uiBaseOffset) + _bValueSpaceIsRaw(bValueSpaceIsRaw), _bOutputRawFormatIsHex(bOutputRawFormatIsHex), + _uiBaseOffset(baseOffset) { } -CParameterAccessContext::CParameterAccessContext(std::string& strError, - bool bBigEndianSubsystem, - CParameterBlackboard* pParameterBlackboard, - uint32_t uiBaseOffset) - : base(strError), _pParameterBlackboard(pParameterBlackboard), _bValueSpaceIsRaw(false), - _bOutputRawFormatIsHex(false), _bBigEndianSubsystem(bBigEndianSubsystem), _bAutoSync(true), - _uiBaseOffset(uiBaseOffset) +CParameterAccessContext::CParameterAccessContext(std::string &strError, + CParameterBlackboard *pParameterBlackboard, + size_t baseOffset) + : base(strError), _pParameterBlackboard(pParameterBlackboard), _uiBaseOffset(baseOffset) { } -CParameterAccessContext::CParameterAccessContext(std::string& strError) - : base(strError), _pParameterBlackboard(NULL), _bValueSpaceIsRaw(false), - _bOutputRawFormatIsHex(false), _bBigEndianSubsystem(false), _bAutoSync(true), _uiBaseOffset(0) +CParameterAccessContext::CParameterAccessContext(std::string &strError) : base(strError) { } // ParameterBlackboard -CParameterBlackboard* CParameterAccessContext::getParameterBlackboard() +CParameterBlackboard *CParameterAccessContext::getParameterBlackboard() { return _pParameterBlackboard; } -void CParameterAccessContext::setParameterBlackboard(CParameterBlackboard* pBlackboard) +void CParameterAccessContext::setParameterBlackboard(CParameterBlackboard *pBlackboard) { _pParameterBlackboard = pBlackboard; _uiBaseOffset = 0; } // Base offset for blackboard access -void CParameterAccessContext::setBaseOffset(uint32_t uiBaseOffset) +void CParameterAccessContext::setBaseOffset(size_t baseOffset) { - _uiBaseOffset = uiBaseOffset; + _uiBaseOffset = baseOffset; } -uint32_t CParameterAccessContext::getBaseOffset() const +size_t CParameterAccessContext::getBaseOffset() const { return _uiBaseOffset; } @@ -103,17 +97,6 @@ bool CParameterAccessContext::outputRawFormatIsHex() const return _bOutputRawFormatIsHex; } -// Endianness -void CParameterAccessContext::setBigEndianSubsystem(bool bBigEndian) -{ - _bBigEndianSubsystem = bBigEndian; -} - -bool CParameterAccessContext::isBigEndianSubsystem() const -{ - return _bBigEndianSubsystem; -} - // Automatic synchronization to HW void CParameterAccessContext::setAutoSync(bool bAutoSync) { diff --git a/parameter/ParameterAccessContext.h b/parameter/ParameterAccessContext.h index 302f920..f3e013f 100644 --- a/parameter/ParameterAccessContext.h +++ b/parameter/ParameterAccessContext.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -30,33 +30,35 @@ #pragma once #include <stdint.h> -#include "ErrorContext.h" +#include "ErrorContext.hpp" #include <string> class CParameterBlackboard; -class CParameterAccessContext : public CErrorContext +class CParameterAccessContext : public utility::ErrorContext { public: - CParameterAccessContext(std::string& strError, - CParameterBlackboard* pParameterBlackboard, - bool bValueSpaceIsRaw, - bool bOutputRawFormatIsHex = false, - uint32_t uiOffsetBase = 0); - CParameterAccessContext(std::string& strError, - bool bBigEndianSubsystem, - CParameterBlackboard* pParameterBlackboard, - uint32_t uiOffsetBase = 0); - CParameterAccessContext(std::string& strError); + CParameterAccessContext(std::string &strError, CParameterBlackboard *pParameterBlackboard, + bool bValueSpaceIsRaw, bool bOutputRawFormatIsHex, + size_t offsetBase = 0); + CParameterAccessContext(std::string &strError, CParameterBlackboard *pParameterBlackboard, + size_t offsetBase = 0); + CParameterAccessContext(std::string &strError); + virtual ~CParameterAccessContext() = default; // ParameterBlackboard - CParameterBlackboard* getParameterBlackboard(); - void setParameterBlackboard(CParameterBlackboard* pBlackboard); + CParameterBlackboard *getParameterBlackboard(); + void setParameterBlackboard(CParameterBlackboard *pBlackboard); // Value interpretation as Real or Raw void setValueSpaceRaw(bool bIsRaw); bool valueSpaceIsRaw() const; + /** @return true if setting serialization is requested, + * false if structure serialization + */ + virtual bool serializeSettings() const { return false; } + /** * Assigns Output Raw Format for user get value interpretation. * @@ -72,30 +74,23 @@ public: */ bool outputRawFormatIsHex() const; - // Endianness - void setBigEndianSubsystem(bool bBigEndian); - bool isBigEndianSubsystem() const; - // Automatic synchronization to HW void setAutoSync(bool bAutoSync); bool getAutoSync() const; // Base offset for blackboard access - void setBaseOffset(uint32_t uiBaseOffset); - uint32_t getBaseOffset() const; + void setBaseOffset(size_t baseOffset); + size_t getBaseOffset() const; private: // Blackboard - CParameterBlackboard* _pParameterBlackboard; + CParameterBlackboard *_pParameterBlackboard{nullptr}; // Value space - bool _bValueSpaceIsRaw; + bool _bValueSpaceIsRaw{false}; // Output Raw Format - bool _bOutputRawFormatIsHex; - // Subsystem Endianness - bool _bBigEndianSubsystem; + bool _bOutputRawFormatIsHex{false}; // Automatic synchronization to HW - bool _bAutoSync; + bool _bAutoSync{true}; // Base offset where parameters are stored in configuration blackboards - uint32_t _uiBaseOffset; + size_t _uiBaseOffset{0}; }; - diff --git a/parameter/ParameterAdaptation.cpp b/parameter/ParameterAdaptation.cpp index 99955f1..67b4bca 100644 --- a/parameter/ParameterAdaptation.cpp +++ b/parameter/ParameterAdaptation.cpp @@ -28,13 +28,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ParameterAdaptation.h" -#include "Utility.h" #define base CElement using std::string; -CParameterAdaptation::CParameterAdaptation(const string& strType) : base(strType), _iOffset(0) +CParameterAdaptation::CParameterAdaptation(const string &strType) : base(strType) { } // CElement @@ -50,7 +49,7 @@ int32_t CParameterAdaptation::getOffset() const } // Element properties -void CParameterAdaptation::showProperties(string& strResult) const +void CParameterAdaptation::showProperties(string &strResult) const { // Adaptation type strResult += " - Type: "; @@ -59,22 +58,15 @@ void CParameterAdaptation::showProperties(string& strResult) const // Offset strResult += " - Offset: "; - strResult += CUtility::toString(_iOffset); + strResult += std::to_string(_iOffset); strResult += "\n"; } // From IXmlSink -bool CParameterAdaptation::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CParameterAdaptation::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { - // Get offset - if (xmlElement.hasAttribute("Offset")) { - - _iOffset = xmlElement.getAttributeSignedInteger("Offset"); - - } else { - // Default - _iOffset = 0; - } + xmlElement.getAttribute("Offset", _iOffset); // Base return base::fromXml(xmlElement, serializingContext); diff --git a/parameter/ParameterAdaptation.h b/parameter/ParameterAdaptation.h index 89daee5..d9cbe4b 100644 --- a/parameter/ParameterAdaptation.h +++ b/parameter/ParameterAdaptation.h @@ -36,13 +36,13 @@ class CParameterAdaptation : public CElement { public: - CParameterAdaptation(const std::string& strType); + CParameterAdaptation(const std::string &strType); // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // Conversions virtual int64_t fromUserValue(double dValue) const; @@ -50,12 +50,12 @@ public: // CElement virtual std::string getKind() const; + protected: // Attributes int32_t getOffset() const; private: // Offset - int32_t _iOffset; + int32_t _iOffset{0}; }; - diff --git a/parameter/ParameterBlackboard.cpp b/parameter/ParameterBlackboard.cpp index 6001c77..eaa6b97 100644 --- a/parameter/ParameterBlackboard.cpp +++ b/parameter/ParameterBlackboard.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -28,112 +28,112 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ParameterBlackboard.h" -#include <string.h> -#include <assert.h> - -CParameterBlackboard::CParameterBlackboard() : _pucData(NULL), _uiSize(0) -{ -} - -CParameterBlackboard::~CParameterBlackboard() -{ - delete [] _pucData; -} +#include "Iterator.hpp" +#include "AlwaysAssert.hpp" +#include <algorithm> // Size -void CParameterBlackboard::setSize(uint32_t uiSize) +void CParameterBlackboard::setSize(size_t size) { - if (_pucData) { - - delete [] _pucData; - } - - _pucData = new uint8_t[uiSize]; - - memset(_pucData, 0, uiSize); - - _uiSize = uiSize; + mBlackboard.resize(size); } -uint32_t CParameterBlackboard::getSize() const +size_t CParameterBlackboard::getSize() const { - return _uiSize; + return mBlackboard.size(); } // Single parameter access -void CParameterBlackboard::writeInteger(const void* pvSrcData, uint32_t uiSize, uint32_t uiOffset, bool bBigEndian) +void CParameterBlackboard::writeInteger(const void *pvSrcData, size_t size, size_t offset) { - assert(uiSize + uiOffset <= _uiSize); + assertValidAccess(offset, size); - if (!bBigEndian) { + auto first = MAKE_ARRAY_ITERATOR(static_cast<const uint8_t *>(pvSrcData), size); + auto last = first + size; + auto dest_first = atOffset(offset); - memcpy(_pucData + uiOffset, pvSrcData, uiSize); - } else { + std::copy(first, last, dest_first); +} - uint32_t uiIndex; - const uint8_t* puiSrcData = (const uint8_t*)pvSrcData; +void CParameterBlackboard::readInteger(void *pvDstData, size_t size, size_t offset) const +{ + assertValidAccess(offset, size); - for (uiIndex = 0; uiIndex < uiSize; uiIndex++) { + auto first = atOffset(offset); + auto last = first + size; + auto dest_first = MAKE_ARRAY_ITERATOR(static_cast<uint8_t *>(pvDstData), size); - _pucData[uiIndex + uiOffset] = puiSrcData[uiSize - uiIndex - 1]; - } - } + std::copy(first, last, dest_first); } -void CParameterBlackboard::readInteger(void* pvDstData, uint32_t uiSize, uint32_t uiOffset, bool bBigEndian) const +void CParameterBlackboard::writeString(const std::string &input, size_t offset) { - assert(uiSize + uiOffset <= _uiSize); + assertValidAccess(offset, input.size() + 1); - if (!bBigEndian) { - - memcpy(pvDstData, _pucData + uiOffset, uiSize); - } else { + auto dest_last = std::copy(begin(input), end(input), atOffset(offset)); + *dest_last = '\0'; +} - uint32_t uiIndex; - uint8_t* puiDstData = (uint8_t*)pvDstData; +void CParameterBlackboard::readString(std::string &output, size_t offset) const +{ + // As the string is null terminated in the blackboard, + // the size that will be read is not known. (>= 1) + assertValidAccess(offset, sizeof('\0')); - for (uiIndex = 0; uiIndex < uiSize; uiIndex++) { + // Get the pointer to the null terminated string + const uint8_t *first = &mBlackboard[offset]; + output = reinterpret_cast<const char *>(first); +} - puiDstData[uiSize - uiIndex - 1] = _pucData[uiIndex + uiOffset]; - } - } +void CParameterBlackboard::writeBuffer(const void *pvSrcData, size_t size, size_t offset) +{ + writeInteger(pvSrcData, size, offset); +} +void CParameterBlackboard::readBuffer(void *pvDstData, size_t size, size_t offset) const +{ + readInteger(pvDstData, size, offset); } -void CParameterBlackboard::writeString(const std::string &input, uint32_t uiOffset) +// Element access +void CParameterBlackboard::writeBytes(const std::vector<uint8_t> &bytes, size_t offset) { - strcpy((char*)_pucData + uiOffset, input.c_str()); + assertValidAccess(offset, bytes.size()); + + std::copy(begin(bytes), end(bytes), atOffset(offset)); } -void CParameterBlackboard::readString(std::string &output, uint32_t uiOffset) const +void CParameterBlackboard::readBytes(std::vector<uint8_t> &bytes, size_t offset) const { - output = std::string((const char*)_pucData + uiOffset); + assertValidAccess(offset, bytes.size()); + + std::copy_n(atOffset(offset), bytes.size(), begin(bytes)); } // Access from/to subsystems -uint8_t* CParameterBlackboard::getLocation(uint32_t uiOffset) +uint8_t *CParameterBlackboard::getLocation(size_t offset) { - return _pucData + uiOffset; + assertValidAccess(offset, 1); + return &mBlackboard[offset]; } // Configuration handling -void CParameterBlackboard::restoreFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset) +void CParameterBlackboard::restoreFrom(const CParameterBlackboard *pFromBlackboard, size_t offset) { - memcpy(_pucData + uiOffset, pFromBlackboard->_pucData, pFromBlackboard->_uiSize); + const auto &fromBB = pFromBlackboard->mBlackboard; + assertValidAccess(offset, fromBB.size()); + std::copy(begin(fromBB), end(fromBB), atOffset(offset)); } -void CParameterBlackboard::saveTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const +void CParameterBlackboard::saveTo(CParameterBlackboard *pToBlackboard, size_t offset) const { - memcpy(pToBlackboard->_pucData, _pucData + uiOffset, pToBlackboard->_uiSize); + auto &toBB = pToBlackboard->mBlackboard; + assertValidAccess(offset, toBB.size()); + std::copy_n(atOffset(offset), toBB.size(), begin(toBB)); } -// Serialization -void CParameterBlackboard::serialize(CBinaryStream& binaryStream) +void CParameterBlackboard::assertValidAccess(size_t offset, size_t size) const { - if (binaryStream.isOut()) { - - binaryStream.write(_pucData, _uiSize); - } else { - - binaryStream.read(_pucData, _uiSize); - } + ALWAYS_ASSERT(offset + size <= getSize(), + "Invalid data size access: offset=" << offset << " size=" << size + << "reference size=" << getSize()); } diff --git a/parameter/ParameterBlackboard.h b/parameter/ParameterBlackboard.h index bd48cc4..979e199 100644 --- a/parameter/ParameterBlackboard.h +++ b/parameter/ParameterBlackboard.h @@ -29,40 +29,72 @@ */ #pragma once -#include <stdint.h> -#include "BinaryStream.h" +#include "NonCopyable.hpp" + +#include <cstdint> #include <string> +#include <vector> -class CParameterBlackboard +class CParameterBlackboard : private utility::NonCopyable { public: - CParameterBlackboard(); - ~CParameterBlackboard(); - // Size - void setSize(uint32_t uiSize); - uint32_t getSize() const; + void setSize(size_t size); + size_t getSize() const; // Single parameter access - void writeInteger(const void* pvSrcData, uint32_t uiSize, uint32_t uiOffset, bool bBigEndian); - void readInteger(void* pvDstData, uint32_t uiSize, uint32_t uiOffset, bool bBigEndian) const; - void writeString(const std::string &input, uint32_t uiOffset); - void readString(std::string &output, uint32_t uiOffset) const; + void writeInteger(const void *pvSrcData, size_t size, size_t offset); + void readInteger(void *pvDstData, size_t size, size_t offset) const; + + void writeString(const std::string &input, size_t offset); + void readString(std::string &output, size_t offset) const; + + void writeBuffer(const void *pvSrcData, size_t size, size_t offset); + void readBuffer(void *pvDstData, size_t size, size_t offset) const; + + /** + * Raw write the blackboard memory. + * + * May be used to write a configurable element's settings + * + * @param[in] bytes the source data bytes vector. + * @param[in] offset the destination offset in the blackboard. + * + * Notes: + * - This function asserts that the input vector's size + the offset + * does not exceed the size of the blackboard istelf. + */ + void writeBytes(const std::vector<uint8_t> &bytes, size_t offset); + + /** + * Raw read the blackboard memory. + * + * May be used to read a configurable element's settings + * + * @param[out] bytes the destination data bytes vector. + * @param[in] offset the source offset in the blackboard. + * + * Notes: + * - This function asserts that the output vector's size + the offset + * does not exceed the size of the blackboard itself. + * - The user MUST resize the output vector to exactly the number of + * elements to be read + */ + void readBytes(std::vector<uint8_t> &bytes, size_t offset) const; // Access from/to subsystems - uint8_t* getLocation(uint32_t uiOffset); + uint8_t *getLocation(size_t offset); // Configuration handling - void restoreFrom(const CParameterBlackboard* pFromBlackboard, uint32_t uiOffset); - void saveTo(CParameterBlackboard* pToBlackboard, uint32_t uiOffset) const; + void restoreFrom(const CParameterBlackboard *pFromBlackboard, size_t offset); + void saveTo(CParameterBlackboard *pToBlackboard, size_t offset) const; - // Serialization - void serialize(CBinaryStream& binaryStream); private: - CParameterBlackboard(const CParameterBlackboard&); - CParameterBlackboard& operator=(const CParameterBlackboard&); + void assertValidAccess(size_t offset, size_t size) const; - uint8_t* _pucData; - uint32_t _uiSize; -}; + using Blackboard = std::vector<uint8_t>; + Blackboard mBlackboard; + Blackboard::iterator atOffset(size_t offset) { return begin(mBlackboard) + offset; } + Blackboard::const_iterator atOffset(size_t offset) const { return begin(mBlackboard) + offset; } +}; diff --git a/parameter/ParameterBlock.h b/parameter/ParameterBlock.h index cf9407f..0ebfdbe 100644 --- a/parameter/ParameterBlock.h +++ b/parameter/ParameterBlock.h @@ -36,15 +36,11 @@ class CParameterBlock : public CInstanceConfigurableElement { public: - CParameterBlock(const std::string& strName, const CTypeElement* pTypeElement) + CParameterBlock(const std::string &strName, const CTypeElement *pTypeElement) : CInstanceConfigurableElement(strName, pTypeElement) { } // Type - virtual Type getType() const - { - return EParameterBlock; - } + virtual Type getType() const { return EParameterBlock; } }; - diff --git a/parameter/ParameterBlockType.cpp b/parameter/ParameterBlockType.cpp index ad94888..d72af81 100644 --- a/parameter/ParameterBlockType.cpp +++ b/parameter/ParameterBlockType.cpp @@ -33,7 +33,7 @@ #define base CTypeElement -CParameterBlockType::CParameterBlockType(const std::string& strName) : base(strName) +CParameterBlockType::CParameterBlockType(const std::string &strName) : base(strName) { } @@ -47,24 +47,22 @@ bool CParameterBlockType::childrenAreDynamic() const return true; } -CInstanceConfigurableElement* CParameterBlockType::doInstantiate() const +CInstanceConfigurableElement *CParameterBlockType::doInstantiate() const { return new CParameterBlock(getName(), this); } -void CParameterBlockType::populate(CElement* pElement) const +void CParameterBlockType::populate(CElement *pElement) const { - uint32_t uiArrayLength = getArrayLength(); + size_t arrayLength = getArrayLength(); - if (uiArrayLength) { + if (arrayLength) { // Create child elements - size_t uiChild; + for (size_t child = 0; child < arrayLength; child++) { - for (uiChild = 0; uiChild < uiArrayLength; uiChild++) { - - CParameterBlock* pChildParameterBlock = new CParameterBlock(CUtility::toString(uiChild), - this); + CParameterBlock *pChildParameterBlock = + new CParameterBlock(std::to_string(child), this); pElement->addChild(pChildParameterBlock); diff --git a/parameter/ParameterBlockType.h b/parameter/ParameterBlockType.h index 2137a3e..6d81ee8 100644 --- a/parameter/ParameterBlockType.h +++ b/parameter/ParameterBlockType.h @@ -36,17 +36,15 @@ class CParameterBlockType : public CTypeElement { public: - CParameterBlockType(const std::string& strName); + CParameterBlockType(const std::string &strName); // CElement virtual std::string getKind() const; + private: virtual bool childrenAreDynamic() const; // Instantiation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Population - virtual void populate(CElement* pElement) const; - // Creating sub blocks with indexes - static std::string computeChildName(size_t uiChild); + virtual void populate(CElement *pElement) const; }; - diff --git a/parameter/ParameterFrameworkConfiguration.cpp b/parameter/ParameterFrameworkConfiguration.cpp index 3488454..bf735fd 100644 --- a/parameter/ParameterFrameworkConfiguration.cpp +++ b/parameter/ParameterFrameworkConfiguration.cpp @@ -31,11 +31,6 @@ #define base CElement -CParameterFrameworkConfiguration::CParameterFrameworkConfiguration() - : _bTuningAllowed(false), _uiServerPort(0) -{ -} - std::string CParameterFrameworkConfiguration::getKind() const { return "ParameterFrameworkConfiguration"; @@ -47,7 +42,7 @@ bool CParameterFrameworkConfiguration::childrenAreDynamic() const } // System class name -const std::string& CParameterFrameworkConfiguration::getSystemClassName() const +const std::string &CParameterFrameworkConfiguration::getSystemClassName() const { return _strSystemClassName; } @@ -65,16 +60,17 @@ uint16_t CParameterFrameworkConfiguration::getServerPort() const } // From IXmlSink -bool CParameterFrameworkConfiguration::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CParameterFrameworkConfiguration::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // System class name - _strSystemClassName = xmlElement.getAttributeString("SystemClassName"); + xmlElement.getAttribute("SystemClassName", _strSystemClassName); // Tuning allowed - _bTuningAllowed = xmlElement.getAttributeBoolean("TuningAllowed"); + xmlElement.getAttribute("TuningAllowed", _bTuningAllowed); // Server port - _uiServerPort = (uint16_t)xmlElement.getAttributeInteger("ServerPort"); + xmlElement.getAttribute("ServerPort", _uiServerPort); // Base return base::fromXml(xmlElement, serializingContext); diff --git a/parameter/ParameterFrameworkConfiguration.h b/parameter/ParameterFrameworkConfiguration.h index a261775..a94f7ef 100644 --- a/parameter/ParameterFrameworkConfiguration.h +++ b/parameter/ParameterFrameworkConfiguration.h @@ -36,10 +36,8 @@ class CParameterFrameworkConfiguration : public CElement { public: - CParameterFrameworkConfiguration(); - // System class name - const std::string& getSystemClassName() const; + const std::string &getSystemClassName() const; // Tuning allowed bool isTuningAllowed() const; @@ -48,7 +46,8 @@ public: uint16_t getServerPort() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); + private: virtual std::string getKind() const; virtual bool childrenAreDynamic() const; @@ -56,7 +55,7 @@ private: // System class name std::string _strSystemClassName; // Tuning allowed - bool _bTuningAllowed; + bool _bTuningAllowed{false}; // Server port - uint16_t _uiServerPort; + uint16_t _uiServerPort{0}; }; diff --git a/parameter/ParameterHandle.cpp b/parameter/ParameterHandle.cpp deleted file mode 100644 index 3bb6120..0000000 --- a/parameter/ParameterHandle.cpp +++ /dev/null @@ -1,517 +0,0 @@ -/* - * Copyright (c) 2011-2014, Intel Corporation - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "ParameterHandle.h" -#include "ParameterAccessContext.h" -#include "BaseParameter.h" -#include "Subsystem.h" -#include <assert.h> -#include "ParameterMgr.h" -#include "AutoLock.h" - -using std::string; - -CParameterHandle::CParameterHandle(const CBaseParameter* pParameter, CParameterMgr* pParameterMgr) - : _pBaseParameter(pParameter), _pParameterMgr(pParameterMgr), _bBigEndianSubsystem(pParameter->getBelongingSubsystem()->isBigEndian()) -{ -} - -// Parameter features -bool CParameterHandle::isRogue() const -{ - return _pBaseParameter->isRogue(); -} - -bool CParameterHandle::isArray() const -{ - return !_pBaseParameter->isScalar(); -} - -// Array Length -uint32_t CParameterHandle::getArrayLength() const -{ - return _pBaseParameter->getArrayLength(); -} - -// Parameter path -string CParameterHandle::getPath() const -{ - return _pBaseParameter->getPath(); -} - -// Parameter kind -string CParameterHandle::getKind() const -{ - return _pBaseParameter->getKind(); -} - -// Boolean access -bool CParameterHandle::setAsBoolean(bool bValue, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsBoolean(bValue, true, parameterAccessContext); -} - -bool CParameterHandle::getAsBoolean(bool& bValue, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsBoolean(bValue, false, parameterAccessContext); -} - -bool CParameterHandle::setAsBooleanArray(const std::vector<bool>& abValues, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, abValues.size(), strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy values for type adaptation - std::vector<bool> abUserValues = abValues; - - return _pBaseParameter->accessAsBooleanArray(abUserValues, true, parameterAccessContext); -} - -bool CParameterHandle::getAsBooleanArray(std::vector<bool>& abValues, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, -1, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsBooleanArray(abValues, false, parameterAccessContext); -} - -// Integer Access -bool CParameterHandle::setAsInteger(uint32_t uiValue, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsInteger(uiValue, true, parameterAccessContext); -} - -bool CParameterHandle::getAsInteger(uint32_t& uiValue, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsInteger(uiValue, false, parameterAccessContext); -} - -bool CParameterHandle::setAsIntegerArray(const std::vector<uint32_t>& auiValues, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, auiValues.size(), strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy values for type adaptation - std::vector<uint32_t> auiUserValues = auiValues; - - return _pBaseParameter->accessAsIntegerArray(auiUserValues, true, parameterAccessContext); -} - -bool CParameterHandle::getAsIntegerArray(std::vector<uint32_t>& auiValues, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, -1, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsIntegerArray(auiValues, false, parameterAccessContext); -} - -// Signed Integer Access -bool CParameterHandle::setAsSignedInteger(int32_t iValue, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsSignedInteger(iValue, true, parameterAccessContext); -} - -bool CParameterHandle::getAsSignedInteger(int32_t& iValue, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsSignedInteger(iValue, false, parameterAccessContext); -} - -bool CParameterHandle::setAsSignedIntegerArray(const std::vector<int32_t>& aiValues, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, aiValues.size(), strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy values for type adaptation - std::vector<int32_t> aiUserValues = aiValues; - - return _pBaseParameter->accessAsSignedIntegerArray(aiUserValues, true, parameterAccessContext); -} - -bool CParameterHandle::getAsSignedIntegerArray(std::vector<int32_t>& aiValues, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, -1, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsSignedIntegerArray(aiValues, false, parameterAccessContext); -} - -// Double Access -bool CParameterHandle::setAsDouble(double dValue, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsDouble(dValue, true, parameterAccessContext); -} - -bool CParameterHandle::getAsDouble(double& dValue, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsDouble(dValue, false, parameterAccessContext); -} - -bool CParameterHandle::setAsDoubleArray(const std::vector<double>& adValues, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, adValues.size(), strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy values for type adaptation - std::vector<double> adUserValues = adValues; - - return _pBaseParameter->accessAsDoubleArray(adUserValues, true, parameterAccessContext); -} - -bool CParameterHandle::getAsDoubleArray(std::vector<double>& adValues, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, -1, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsDoubleArray(adValues, false, parameterAccessContext); -} - -// String Access -bool CParameterHandle::setAsString(const string& strValue, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy value for type adaptation - string strUserValue = strValue; - - return _pBaseParameter->accessAsString(strUserValue, true, parameterAccessContext); -} - -bool CParameterHandle::getAsString(string& strValue, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, 0, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsString(strValue, false, parameterAccessContext); -} - -bool CParameterHandle::setAsStringArray(const std::vector<string>& astrValues, string& strError) -{ - // Check operation validity - if (!checkAccessValidity(true, (uint32_t)astrValues.size(), strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // When in tuning mode, silently skip the request - if (_pParameterMgr->tuningModeOn()) { - - return true; - } - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - // Copy values for type adaptation - std::vector<string> astrUserValues = astrValues; - - return _pBaseParameter->accessAsStringArray(astrUserValues, true, parameterAccessContext); -} - -bool CParameterHandle::getAsStringArray(std::vector<string>& astrValues, string& strError) const -{ - // Check operation validity - if (!checkAccessValidity(false, -1, strError)) { - - return false; - } - // Ensure we're safe against blackboard foreign access - CAutoLock autoLock(_pParameterMgr->getBlackboardMutex()); - - // Define access context - CParameterAccessContext parameterAccessContext(strError, _bBigEndianSubsystem, _pParameterMgr->getParameterBlackboard()); - - return _pBaseParameter->accessAsStringArray(astrValues, false, parameterAccessContext); -} - -// Access validity -bool CParameterHandle::checkAccessValidity(bool bSet, size_t uiArrayLength, string& strError) const -{ - if (bSet && !isRogue()) { - - strError = "Parameter is not rogue: "; - - strError += getPath(); - - return false; - } - - if (uiArrayLength && !isArray()) { - - strError = "Parameter is scalar: "; - - strError += getPath(); - - return false; - } - - if (!uiArrayLength && isArray()) { - - strError = "Parameter is an array: "; - - strError += getPath(); - - return false; - } - - if (bSet && uiArrayLength && (uiArrayLength != getArrayLength())) { - - strError = "Array length mismatch: "; - - strError += getPath(); - - return false; - } - - return true; -} diff --git a/parameter/ParameterMgr.cpp b/parameter/ParameterMgr.cpp index b42c7de..f450563 100644 --- a/parameter/ParameterMgr.cpp +++ b/parameter/ParameterMgr.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2015, Intel Corporation + * Copyright (c) 2011-2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,7 +27,9 @@ * (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 "version.h" #include "ParameterMgr.h" +#include "ConfigurationAccessContext.h" #include "XmlParameterSerializingContext.h" #include "XmlElementSerializingContext.h" #include "SystemClass.h" @@ -36,7 +38,6 @@ #include "NamedElementBuilderTemplate.h" #include "KindElementBuilderTemplate.h" #include "ElementBuilderTemplate.h" -#include "XmlFileIncluderElement.h" #include "SelectionCriterionType.h" #include "SubsystemElementBuilder.h" #include "FileIncluderElementBuilder.h" @@ -47,10 +48,10 @@ #include "BooleanParameterType.h" #include "IntegerParameterType.h" #include "FixedPointParameterType.h" +#include "FloatingPointParameterType.h" #include "ParameterBlackboard.h" #include "Parameter.h" #include "ParameterAccessContext.h" -#include "XmlFileIncluderElement.h" #include "ParameterFrameworkConfiguration.h" #include "FrameworkConfigurationGroup.h" #include "PluginLocation.h" @@ -66,17 +67,13 @@ #include "BitParameterType.h" #include "StringParameterType.h" #include "EnumParameterType.h" -#include "RemoteProcessorServerInterface.h" +#include "BackgroundRemoteProcessorServer.h" #include "ElementLocator.h" -#include "AutoLog.h" #include "CompoundRule.h" #include "SelectionCriterionRule.h" #include "SimulatedBackSynchronizer.h" #include "HardwareBackSynchronizer.h" -#include "AutoLock.h" -#include <strings.h> -#include <dlfcn.h> -#include <assert.h> +#include <cassert> #include "ParameterHandle.h" #include "LinearParameterAdaptation.h" #include "LogarithmicParameterAdaptation.h" @@ -88,21 +85,34 @@ #include "XmlMemoryDocSource.h" #include "SelectionCriteriaDefinition.h" #include "Utility.h" +#include "Memory.hpp" #include <sstream> #include <fstream> #include <algorithm> -#include <ctype.h> -#include <memory> +#include <stdexcept> +#include <mutex> +#include <iomanip> +#include "convert.hpp" #define base CElement +/** Private macro helper to declare a new context + * + * Context declaration always need logger and logging prefix to be + * passed as parameters. + * This macro aims to avoid this boring notation. + * This macro should be called only once in a scope. Nested scopes can + * call this macro too, as variable shadowing is supported. + */ +#define LOG_CONTEXT(contextTitle) core::log::Context context(_logger, contextTitle) + #ifdef SIMULATION - // In simulation, back synchronization of the blackboard won't probably work - // We need to ensure though the blackboard is initialized with valid data - typedef CSimulatedBackSynchronizer BackSynchronizer; +// In simulation, back synchronization of the blackboard won't probably work +// We need to ensure though the blackboard is initialized with valid data +typedef CSimulatedBackSynchronizer BackSynchronizer; #else - // Real back synchronizer from subsystems - typedef CHardwareBackSynchronizer BackSynchronizer; +// Real back synchronizer from subsystems +typedef CHardwareBackSynchronizer BackSynchronizer; #endif using std::string; @@ -111,18 +121,20 @@ using std::vector; using std::ostringstream; using std::ofstream; using std::ifstream; +using std::mutex; +using std::lock_guard; -// Used for remote processor server creation -typedef IRemoteProcessorServerInterface* (*CreateRemoteProcessorServer)(uint16_t uiPort, IRemoteCommandHandler* pCommandHandler); +// FIXME: integrate ParameterMgr to core namespace +using namespace core; -// Global configuration file name (fixed) -const char* gacParameterFrameworkConfigurationFileName = "ParameterFrameworkConfiguration.xml"; -const char* gacSystemSchemasSubFolder = "Schemas"; +// Used for remote processor server creation +typedef IRemoteProcessorServerInterface *(*CreateRemoteProcessorServer)( + uint16_t uiPort, IRemoteCommandHandler *pCommandHandler); // Config File System looks normally like this: // --------------------------------------------- //|-- <ParameterFrameworkConfiguration>.xml -//|-- Schemas +//|-- schemas //| `-- *.xsd //|-- Settings //| `-- <SystemClassName folder>* @@ -134,269 +146,201 @@ const char* gacSystemSchemasSubFolder = "Schemas"; // `-- <Subsystem>.xml* // -------------------------------------------- - // Remote command parser array const CParameterMgr::SRemoteCommandParserItem CParameterMgr::gastRemoteCommandParserItems[] = { /// Version - { "version", &CParameterMgr::versionCommandProcess, 0, - "", "Show version" }, + {"version", &CParameterMgr::versionCommandProcess, 0, "", "Show version"}, /// Status - { "status", &CParameterMgr::statusCommandProcess, 0, "", - "Show current status" }, + {"status", &CParameterMgr::statusCommandProcess, 0, "", "Show current status"}, /// Tuning Mode - { "setTuningMode", &CParameterMgr::setTuningModeCommandProcess, 1, - "on|off*", "Turn on or off Tuning Mode" }, - { "getTuningMode", &CParameterMgr::getTuningModeCommandProcess, 0, - "", "Show Tuning Mode" }, + {"setTuningMode", &CParameterMgr::setTuningModeCommandProcess, 1, "on|off*", + "Turn on or off Tuning Mode"}, + {"getTuningMode", &CParameterMgr::getTuningModeCommandProcess, 0, "", "Show Tuning Mode"}, /// Value Space - { "setValueSpace", &CParameterMgr::setValueSpaceCommandProcess, 1, - "raw|real*", "Assigns Value Space used for parameter value interpretation" }, - { "getValueSpace", &CParameterMgr::getValueSpaceCommandProcess, 0, - "", "Show Value Space" }, + {"setValueSpace", &CParameterMgr::setValueSpaceCommandProcess, 1, "raw|real*", + "Assigns Value Space used for parameter value interpretation"}, + {"getValueSpace", &CParameterMgr::getValueSpaceCommandProcess, 0, "", "Show Value Space"}, /// Output Raw Format - { "setOutputRawFormat", &CParameterMgr::setOutputRawFormatCommandProcess, 1, - "dec*|hex", "Assigns format used to output parameter values when in raw Value Space" }, - { "getOutputRawFormat", &CParameterMgr::getOutputRawFormatCommandProcess, 0, - "", "Show Output Raw Format" }, + {"setOutputRawFormat", &CParameterMgr::setOutputRawFormatCommandProcess, 1, "dec*|hex", + "Assigns format used to output parameter values when in raw Value Space"}, + {"getOutputRawFormat", &CParameterMgr::getOutputRawFormatCommandProcess, 0, "", + "Show Output Raw Format"}, /// Sync - { "setAutoSync", &CParameterMgr::setAutoSyncCommandProcess, 1, - "on*|off", "Turn on or off automatic synchronization to hardware while in Tuning Mode" }, - { "getAutoSync", &CParameterMgr::getAutoSyncCommandProcess, 0, - "", "Show Auto Sync state" }, - { "sync", &CParameterMgr::syncCommandProcess, 0, - "", "Synchronize current settings to hardware while in Tuning Mode and Auto Sync off" }, + {"setAutoSync", &CParameterMgr::setAutoSyncCommandProcess, 1, "on*|off", + "Turn on or off automatic synchronization to hardware while in Tuning Mode"}, + {"getAutoSync", &CParameterMgr::getAutoSyncCommandProcess, 0, "", "Show Auto Sync state"}, + {"sync", &CParameterMgr::syncCommandProcess, 0, "", + "Synchronize current settings to hardware while in Tuning Mode and Auto Sync off"}, /// Criteria - { "listCriteria", &CParameterMgr::listCriteriaCommandProcess, 0, - "[CSV|XML]", "List selection criteria" }, + {"listCriteria", &CParameterMgr::listCriteriaCommandProcess, 0, "[CSV|XML]", + "List selection criteria"}, /// Domains - { "listDomains", &CParameterMgr::listDomainsCommandProcess, 0, - "", "List configurable domains" }, - { "dumpDomains", &CParameterMgr::dumpDomainsCommandProcess, 0, - "", "Show all domains and configurations, including applicability conditions" }, - { "createDomain", &CParameterMgr::createDomainCommandProcess, 1, - "<domain>", "Create new configurable domain" }, - { "deleteDomain", &CParameterMgr::deleteDomainCommandProcess, 1, - "<domain>", "Delete configurable domain" }, - { "deleteAllDomains", &CParameterMgr::deleteAllDomainsCommandProcess, 0, - "", "Delete all configurable domains" }, - { "renameDomain", &CParameterMgr::renameDomainCommandProcess, 2, - "<domain> <new name>", "Rename configurable domain" }, - { "setSequenceAwareness", &CParameterMgr::setSequenceAwarenessCommandProcess, 1, - "<domain> true|false*", "Set configurable domain sequence awareness" }, - { "getSequenceAwareness", &CParameterMgr::getSequenceAwarenessCommandProcess, 1, - "<domain>", "Get configurable domain sequence awareness" }, - { "listDomainElements", &CParameterMgr::listDomainElementsCommandProcess, 1, - "<domain>", "List elements associated to configurable domain" }, - { "addElement", &CParameterMgr::addElementCommandProcess, 2, - "<domain> <elem path>", "Associate element at given path to configurable domain" }, - { "removeElement", &CParameterMgr::removeElementCommandProcess, 2, - "<domain> <elem path>", "Dissociate element at given path from configurable domain" }, - { "splitDomain", &CParameterMgr::splitDomainCommandProcess, 2, - "<domain> <elem path>", "Split configurable domain at given associated element path" }, + {"listDomains", &CParameterMgr::listDomainsCommandProcess, 0, "", "List configurable domains"}, + {"dumpDomains", &CParameterMgr::dumpDomainsCommandProcess, 0, "", + "Show all domains and configurations, including applicability conditions"}, + {"createDomain", &CParameterMgr::createDomainCommandProcess, 1, "<domain>", + "Create new configurable domain"}, + {"deleteDomain", &CParameterMgr::deleteDomainCommandProcess, 1, "<domain>", + "Delete configurable domain"}, + {"deleteAllDomains", &CParameterMgr::deleteAllDomainsCommandProcess, 0, "", + "Delete all configurable domains"}, + {"renameDomain", &CParameterMgr::renameDomainCommandProcess, 2, "<domain> <new name>", + "Rename configurable domain"}, + {"setSequenceAwareness", &CParameterMgr::setSequenceAwarenessCommandProcess, 1, + "<domain> true|false*", "Set configurable domain sequence awareness"}, + {"getSequenceAwareness", &CParameterMgr::getSequenceAwarenessCommandProcess, 1, "<domain>", + "Get configurable domain sequence awareness"}, + {"listDomainElements", &CParameterMgr::listDomainElementsCommandProcess, 1, "<domain>", + "List elements associated to configurable domain"}, + {"addElement", &CParameterMgr::addElementCommandProcess, 2, "<domain> <elem path>", + "Associate element at given path to configurable domain"}, + {"removeElement", &CParameterMgr::removeElementCommandProcess, 2, "<domain> <elem path>", + "Dissociate element at given path from configurable domain"}, + {"splitDomain", &CParameterMgr::splitDomainCommandProcess, 2, "<domain> <elem path>", + "Split configurable domain at given associated element path"}, /// Configurations - { "listConfigurations", &CParameterMgr::listConfigurationsCommandProcess, 1, - "<domain>", "List domain configurations" }, - { "createConfiguration", &CParameterMgr::createConfigurationCommandProcess, 2, - "<domain> <configuration>", "Create new domain configuration" }, - { "deleteConfiguration", &CParameterMgr::deleteConfigurationCommandProcess, 2, - "<domain> <configuration>", "Delete domain configuration" }, - { "renameConfiguration", &CParameterMgr::renameConfigurationCommandProcess, 3, - "<domain> <configuration> <new name>", "Rename domain configuration" }, - { "saveConfiguration", &CParameterMgr::saveConfigurationCommandProcess, 2, - "<domain> <configuration>", "Save current settings into configuration" }, - { "restoreConfiguration", &CParameterMgr::restoreConfigurationCommandProcess, 2, - "<domain> <configuration>", "Restore current settings from configuration" }, - { "setElementSequence", &CParameterMgr::setElementSequenceCommandProcess, 3, - "<domain> <configuration> <elem path list>", - "Set element application order for configuration" }, - { "getElementSequence", &CParameterMgr::getElementSequenceCommandProcess, 2, - "<domain> <configuration>", "Get element application order for configuration" }, - { "setRule", &CParameterMgr::setRuleCommandProcess, 3, - "<domain> <configuration> <rule>", "Set configuration application rule" }, - { "clearRule", &CParameterMgr::clearRuleCommandProcess, 2, - "<domain> <configuration>", "Clear configuration application rule" }, - { "getRule", &CParameterMgr::getRuleCommandProcess, 2, - "<domain> <configuration>", "Get configuration application rule" }, + {"listConfigurations", &CParameterMgr::listConfigurationsCommandProcess, 1, "<domain>", + "List domain configurations"}, + {"createConfiguration", &CParameterMgr::createConfigurationCommandProcess, 2, + "<domain> <configuration>", "Create new domain configuration"}, + {"deleteConfiguration", &CParameterMgr::deleteConfigurationCommandProcess, 2, + "<domain> <configuration>", "Delete domain configuration"}, + {"renameConfiguration", &CParameterMgr::renameConfigurationCommandProcess, 3, + "<domain> <configuration> <new name>", "Rename domain configuration"}, + {"saveConfiguration", &CParameterMgr::saveConfigurationCommandProcess, 2, + "<domain> <configuration>", "Save current settings into configuration"}, + {"restoreConfiguration", &CParameterMgr::restoreConfigurationCommandProcess, 2, + "<domain> <configuration>", "Restore current settings from configuration"}, + {"setElementSequence", &CParameterMgr::setElementSequenceCommandProcess, 3, + "<domain> <configuration> <elem path list>", + "Set element application order for configuration"}, + {"getElementSequence", &CParameterMgr::getElementSequenceCommandProcess, 2, + "<domain> <configuration>", "Get element application order for configuration"}, + {"setRule", &CParameterMgr::setRuleCommandProcess, 3, "<domain> <configuration> <rule>", + "Set configuration application rule"}, + {"clearRule", &CParameterMgr::clearRuleCommandProcess, 2, "<domain> <configuration>", + "Clear configuration application rule"}, + {"getRule", &CParameterMgr::getRuleCommandProcess, 2, "<domain> <configuration>", + "Get configuration application rule"}, /// Elements/Parameters - { "listElements", &CParameterMgr::listElementsCommandProcess, 1, - "<elem path>|/", "List elements under element at given path or root" }, - { "listParameters", &CParameterMgr::listParametersCommandProcess, 1, - "<elem path>|/", "List parameters under element at given path or root" }, - { "dumpElement", &CParameterMgr::dumpElementCommandProcess, 1, - "<elem path>", "Dump structure and content of element at given path" }, - { "getElementSize", &CParameterMgr::getElementSizeCommandProcess, 1, - "<elem path>", "Show size of element at given path" }, - { "showProperties", &CParameterMgr::showPropertiesCommandProcess, 1, - "<elem path>", "Show properties of element at given path" }, - { "getParameter", &CParameterMgr::getParameterCommandProcess, 1, - "<param path>", "Get value for parameter at given path" }, - { "setParameter", &CParameterMgr::setParameterCommandProcess, 2, - "<param path> <value>", "Set value for parameter at given path" }, - { "listBelongingDomains", &CParameterMgr::listBelongingDomainsCommandProcess, 1, - "<elem path>", "List domain(s) element at given path belongs to" }, - { "listAssociatedDomains", &CParameterMgr::listAssociatedDomainsCommandProcess, 1, - "<elem path>", "List domain(s) element at given path is associated to" }, - { "getConfigurationParameter", &CParameterMgr::getConfigurationParameterCommandProcess, 3, - "<domain> <configuration> <param path>", - "Get value for parameter at given path from configuration" }, - { "setConfigurationParameter", &CParameterMgr::setConfigurationParameterCommandProcess, 4, - "<domain> <configuration> <param path> <value>", - "Set value for parameter at given path to configuration" }, - { "showMapping", &CParameterMgr::showMappingCommandProcess, 1, - "<elem path>", "Show mapping for an element at given path" }, + {"listElements", &CParameterMgr::listElementsCommandProcess, 1, "<elem path>|/", + "List elements under element at given path or root"}, + {"listParameters", &CParameterMgr::listParametersCommandProcess, 1, "<elem path>|/", + "List parameters under element at given path or root"}, + {"getElementStructureXML", &CParameterMgr::getElementStructureXMLCommandProcess, 1, + "<elem path>", "Get structure of element at given path in XML format"}, + {"getElementBytes", &CParameterMgr::getElementBytesCommandProcess, 1, "<elem path>", + "Get settings of element at given path in Byte Array format"}, + {"setElementBytes", &CParameterMgr::setElementBytesCommandProcess, 2, "<elem path> <values>", + "Set settings of element at given path in Byte Array format"}, + {"getElementXML", &CParameterMgr::getElementXMLCommandProcess, 1, "<elem path>", + "Get settings of element at given path in XML format"}, + {"setElementXML", &CParameterMgr::setElementXMLCommandProcess, 2, "<elem path> <values>", + "Set settings of element at given path in XML format"}, + {"dumpElement", &CParameterMgr::dumpElementCommandProcess, 1, "<elem path>", + "Dump structure and content of element at given path"}, + {"getElementSize", &CParameterMgr::getElementSizeCommandProcess, 1, "<elem path>", + "Show size of element at given path"}, + {"showProperties", &CParameterMgr::showPropertiesCommandProcess, 1, "<elem path>", + "Show properties of element at given path"}, + {"getParameter", &CParameterMgr::getParameterCommandProcess, 1, "<param path>", + "Get value for parameter at given path"}, + {"setParameter", &CParameterMgr::setParameterCommandProcess, 2, "<param path> <value>", + "Set value for parameter at given path"}, + {"listBelongingDomains", &CParameterMgr::listBelongingDomainsCommandProcess, 1, "<elem path>", + "List domain(s) element at given path belongs to"}, + {"listAssociatedDomains", &CParameterMgr::listAssociatedDomainsCommandProcess, 1, "<elem path>", + "List domain(s) element at given path is associated to"}, + {"getConfigurationParameter", &CParameterMgr::getConfigurationParameterCommandProcess, 3, + "<domain> <configuration> <param path>", + "Get value for parameter at given path from configuration"}, + {"setConfigurationParameter", &CParameterMgr::setConfigurationParameterCommandProcess, 4, + "<domain> <configuration> <param path> <value>", + "Set value for parameter at given path to configuration"}, + {"showMapping", &CParameterMgr::showMappingCommandProcess, 1, "<elem path>", + "Show mapping for an element at given path"}, /// Browse - { "listAssociatedElements", &CParameterMgr::listAssociatedElementsCommandProcess, 0, - "", "List element sub-trees associated to at least one configurable domain" }, - { "listConflictingElements", &CParameterMgr::listConflictingElementsCommandProcess, 0, - "", "List element sub-trees contained in more than one configurable domain" }, - { "listRogueElements", &CParameterMgr::listRogueElementsCommandProcess, 0, - "", "List element sub-trees owned by no configurable domain" }, + {"listAssociatedElements", &CParameterMgr::listAssociatedElementsCommandProcess, 0, "", + "List element sub-trees associated to at least one configurable domain"}, + {"listConflictingElements", &CParameterMgr::listConflictingElementsCommandProcess, 0, "", + "List element sub-trees contained in more than one configurable domain"}, + {"listRogueElements", &CParameterMgr::listRogueElementsCommandProcess, 0, "", + "List element sub-trees owned by no configurable domain"}, /// Settings Import/Export - { "exportDomainsXML", &CParameterMgr::exportDomainsXMLCommandProcess, 1, - "<file path> ", "Export domains to an XML file (provide an absolute path or relative" - "to the client's working directory)" }, - { "importDomainsXML", &CParameterMgr::importDomainsXMLCommandProcess, 1, - "<file path>", "Import domains from an XML file (provide an absolute path or relative" - "to the client's working directory)" }, - { "exportDomainsWithSettingsXML", - &CParameterMgr::exportDomainsWithSettingsXMLCommandProcess, 1, - "<file path> ", "Export domains including settings to XML file (provide an absolute path or relative" - "to the client's working directory)" }, - { "exportDomainWithSettingsXML", - &CParameterMgr::exportDomainWithSettingsXMLCommandProcess, 2, - "<domain> <file path> ", "Export a single given domain including settings to XML file" - " (provide an absolute path or relative to the client's" - " working directory)" }, - { "importDomainsWithSettingsXML", - &CParameterMgr::importDomainsWithSettingsXMLCommandProcess, 1, - "<file path>", "Import domains including settings from XML file (provide an absolute path or relative" - "to the client's working directory)" }, - { "importDomainWithSettingsXML", - &CParameterMgr::importDomainWithSettingsXMLCommandProcess, 1, - "<file path> [overwrite]", "Import a single domain including settings from XML file." - " Does not overwrite an existing domain unless 'overwrite' is passed as second" - " argument. Provide an absolute path or relative to the client's working directory)" }, - { "exportSettings", &CParameterMgr::exportSettingsCommandProcess, 1, - "<file path>", "Export settings to binary file (provide an absolute path or relative" - "to the client's working directory)" }, - { "importSettings", &CParameterMgr::importSettingsCommandProcess, 1, - "<file path>", "Import settings from binary file (provide an absolute path or relative" - "to the client's working directory)" }, - { "getDomainsWithSettingsXML", - &CParameterMgr::getDomainsWithSettingsXMLCommandProcess, 0, - "", "Print domains including settings as XML" }, - { "getDomainWithSettingsXML", - &CParameterMgr::getDomainWithSettingsXMLCommandProcess, 1, - "<domain>", "Print the given domain including settings as XML" }, - { "setDomainsWithSettingsXML", - &CParameterMgr::setDomainsWithSettingsXMLCommandProcess, 1, - "<xml configurable domains>", "Import domains including settings from XML string" }, - { "setDomainWithSettingsXML", - &CParameterMgr::setDomainWithSettingsXMLCommandProcess, 1, - "<xml configurable domain> [overwrite]", "Import domains including settings from XML" - " string. Does not overwrite an existing domain unless 'overwrite' is passed as second" - " argument" }, + {"exportDomainsXML", &CParameterMgr::exportDomainsXMLCommandProcess, 1, "<file path> ", + "Export domains to an XML file (provide an absolute path or relative" + "to the client's working directory)"}, + {"importDomainsXML", &CParameterMgr::importDomainsXMLCommandProcess, 1, "<file path>", + "Import domains from an XML file (provide an absolute path or relative" + "to the client's working directory)"}, + {"exportDomainsWithSettingsXML", &CParameterMgr::exportDomainsWithSettingsXMLCommandProcess, 1, + "<file path> ", + "Export domains including settings to XML file (provide an absolute path or relative" + "to the client's working directory)"}, + {"exportDomainWithSettingsXML", &CParameterMgr::exportDomainWithSettingsXMLCommandProcess, 2, + "<domain> <file path> ", "Export a single given domain including settings to XML file" + " (provide an absolute path or relative to the client's" + " working directory)"}, + {"importDomainsWithSettingsXML", &CParameterMgr::importDomainsWithSettingsXMLCommandProcess, 1, + "<file path>", + "Import domains including settings from XML file (provide an absolute path or relative" + "to the client's working directory)"}, + {"importDomainWithSettingsXML", &CParameterMgr::importDomainWithSettingsXMLCommandProcess, 1, + "<file path> [overwrite]", + "Import a single domain including settings from XML file." + " Does not overwrite an existing domain unless 'overwrite' is passed as second" + " argument. Provide an absolute path or relative to the client's working directory)"}, + {"getDomainsWithSettingsXML", &CParameterMgr::getDomainsWithSettingsXMLCommandProcess, 0, "", + "Print domains including settings as XML"}, + {"getDomainWithSettingsXML", &CParameterMgr::getDomainWithSettingsXMLCommandProcess, 1, + "<domain>", "Print the given domain including settings as XML"}, + {"setDomainsWithSettingsXML", &CParameterMgr::setDomainsWithSettingsXMLCommandProcess, 1, + "<xml configurable domains>", "Import domains including settings from XML string"}, + {"setDomainWithSettingsXML", &CParameterMgr::setDomainWithSettingsXMLCommandProcess, 1, + "<xml configurable domain> [overwrite]", + "Import domains including settings from XML" + " string. Does not overwrite an existing domain unless 'overwrite' is passed as second" + " argument"}, /// Structure Export - { "getSystemClassXML", &CParameterMgr::getSystemClassXMLCommandProcess, 0 , - "", "Print parameter structure as XML" }, + {"getSystemClassXML", &CParameterMgr::getSystemClassXMLCommandProcess, 0, "", + "Print parameter structure as XML"}, /// Deprecated Commands - { "getDomainsXML", - &CParameterMgr::getDomainsWithSettingsXMLCommandProcess, 0, - "", "DEPRECATED COMMAND, please use getDomainsWithSettingsXML" }, + {"getDomainsXML", &CParameterMgr::getDomainsWithSettingsXMLCommandProcess, 0, "", + "DEPRECATED COMMAND, please use getDomainsWithSettingsXML"}, }; // Remote command parsers array Size -const uint32_t CParameterMgr::guiNbRemoteCommandParserItems = sizeof(gastRemoteCommandParserItems) / sizeof(gastRemoteCommandParserItems[0]); - -CParameterMgr::CParameterMgr(const string& strConfigurationFilePath) : - _bTuningModeIsOn(false), - _bValueSpaceIsRaw(false), - _bOutputRawFormatIsHex(false), - _bAutoSyncOn(true), - _pMainParameterBlackboard(new CParameterBlackboard), - _pElementLibrarySet(new CElementLibrarySet), - _strXmlConfigurationFilePath(strConfigurationFilePath), - _pSubsystemPlugins(NULL), - _pvLibRemoteProcessorHandle(NULL), - _uiStructureChecksum(0), - _pRemoteProcessorServer(NULL), - _uiMaxCommandUsageLength(0), - _pLogger(NULL), - _uiLogDepth(0), - _bForceNoRemoteInterface(false), - _bFailOnMissingSubsystem(true), - _bFailOnFailedSettingsLoad(true), - _bValidateSchemasOnStart(false) - -{ - // Tuning Mode Mutex - bzero(&_blackboardMutex, sizeof(_blackboardMutex)); - pthread_mutex_init(&_blackboardMutex, NULL); - +CParameterMgr::CParameterMgr(const string &strConfigurationFilePath, log::ILogger &logger) + : _pMainParameterBlackboard(new CParameterBlackboard), + _pElementLibrarySet(new CElementLibrarySet), + _xmlConfigurationUri(CXmlDocSource::mkUri(strConfigurationFilePath, "")), _logger(logger) +{ // Deal with children addChild(new CParameterFrameworkConfiguration); addChild(new CSelectionCriteria); - addChild(new CSystemClass); + addChild(new CSystemClass(_logger)); addChild(new CConfigurableDomains); - - _pCommandHandler = new CCommandHandler(this); - - // Add command parsers - uint32_t uiRemoteCommandParserItem; - - for (uiRemoteCommandParserItem = 0; uiRemoteCommandParserItem < guiNbRemoteCommandParserItems; uiRemoteCommandParserItem++) { - - const SRemoteCommandParserItem* pRemoteCommandParserItem = &gastRemoteCommandParserItems[uiRemoteCommandParserItem]; - - _pCommandHandler->addCommandParser(pRemoteCommandParserItem->_pcCommandName, - pRemoteCommandParserItem->_pfnParser, - pRemoteCommandParserItem->_uiMinArgumentCount, - pRemoteCommandParserItem->_pcHelp, - pRemoteCommandParserItem->_pcDescription); - } - - // Configuration file folder - std::string::size_type slashPos = _strXmlConfigurationFilePath.rfind('/', -1); - if(slashPos == std::string::npos) { - // Configuration folder is the current folder - _strXmlConfigurationFolderPath = '.'; - } else { - _strXmlConfigurationFolderPath = _strXmlConfigurationFilePath.substr(0, slashPos); - } - - // Schema absolute folder location - _strSchemaFolderLocation = _strXmlConfigurationFolderPath + "/" + gacSystemSchemasSubFolder; } CParameterMgr::~CParameterMgr() { // Children delete _pRemoteProcessorServer; - delete _pCommandHandler; delete _pMainParameterBlackboard; delete _pElementLibrarySet; - - // Close remote processor library - if (_pvLibRemoteProcessorHandle) { - - dlclose(_pvLibRemoteProcessorHandle); - } - - // Tuning Mode Mutex - pthread_mutex_destroy(&_blackboardMutex); } string CParameterMgr::getKind() const @@ -404,61 +348,15 @@ string CParameterMgr::getKind() const return "ParameterMgr"; } -// Logging -void CParameterMgr::setLogger(CParameterMgr::ILogger* pLogger) -{ - _pLogger = pLogger; -} - -// Logging -void CParameterMgr::doLog(bool bIsWarning, const string& strLog) const -{ - if (_pLogger) { - - // Nest - string strIndent; - - // Level - uint32_t uiNbIndents = _uiLogDepth; - - while (uiNbIndents--) { - - strIndent += " "; - } - - // Log - _pLogger->log(bIsWarning, strIndent + strLog); - } -} - -void CParameterMgr::nestLog() const -{ - _uiLogDepth++; -} - -void CParameterMgr::unnestLog() const -{ - _uiLogDepth--; -} - // Version string CParameterMgr::getVersion() const { - string strVersion; - - // Major - strVersion = CUtility::toString(guiEditionMajor) + "."; - // Minor - strVersion += CUtility::toString(guiEditionMinor) + "."; - // Revision - strVersion += CUtility::toString(guiRevision); - - return strVersion; + return PARAMETER_FRAMEWORK_VERSION; } -bool CParameterMgr::load(string& strError) +bool CParameterMgr::load(string &strError) { - CAutoLog autoLog(this, "Loading"); + LOG_CONTEXT("Loading"); feedElementLibraries(); @@ -468,9 +366,7 @@ bool CParameterMgr::load(string& strError) return false; } - // Load subsystems - if (!getSystemClass()->loadSubsystems(strError, - _pSubsystemPlugins, !_bFailOnMissingSubsystem)) { + if (!loadSubsystems(strError)) { return false; } @@ -493,30 +389,29 @@ bool CParameterMgr::load(string& strError) return false; } - { - CAutoLog autoLog(this, "Main blackboard back synchronization"); + LOG_CONTEXT("Main blackboard back synchronization"); - // Back synchronization for areas in parameter blackboard not covered by any domain - BackSynchronizer(getConstSystemClass(), _pMainParameterBlackboard).sync(); + // Back synchronization for areas in parameter blackboard not covered by any domain + BackSynchronizer(getConstSystemClass(), _pMainParameterBlackboard).sync(); } // We're done loading the settings and back synchronizing - CConfigurableDomains* pConfigurableDomains = getConfigurableDomains(); + CConfigurableDomains *pConfigurableDomains = getConfigurableDomains(); // We need to ensure all domains are valid pConfigurableDomains->validate(_pMainParameterBlackboard); // Log selection criterion states { - CAutoLog autoLog(this, "Criterion states"); + LOG_CONTEXT("Criterion states"); - const CSelectionCriteria* selectionCriteria = getConstSelectionCriteria(); + const CSelectionCriteria *selectionCriteria = getConstSelectionCriteria(); - list<string> lstrSelectionCriteron; - selectionCriteria->listSelectionCriteria(lstrSelectionCriteron, true, false); + list<string> criteria; + selectionCriteria->listSelectionCriteria(criteria, true, false); - log_table(false, lstrSelectionCriteron); + info() << criteria; } // Subsystem can not ask for resync as they have not been synced yet @@ -529,20 +424,21 @@ bool CParameterMgr::load(string& strError) return handleRemoteProcessingInterface(strError); } -bool CParameterMgr::loadFrameworkConfiguration(string& strError) +bool CParameterMgr::loadFrameworkConfiguration(string &strError) { - CAutoLog autoLog(this, "Loading framework configuration"); + LOG_CONTEXT("Loading framework configuration"); // Parse Structure XML file CXmlElementSerializingContext elementSerializingContext(strError); - _xmlDoc *doc = CXmlDocSource::mkXmlDoc(_strXmlConfigurationFilePath, true, true, strError); + _xmlDoc *doc = + CXmlDocSource::mkXmlDoc(_xmlConfigurationUri, true, true, elementSerializingContext); if (doc == NULL) { return false; } - if (!xmlParse(elementSerializingContext, getFrameworkConfiguration(), doc, - _strXmlConfigurationFolderPath, EFrameworkConfigurationLibrary)) { + if (!xmlParse(elementSerializingContext, getFrameworkConfiguration(), doc, _xmlConfigurationUri, + EFrameworkConfigurationLibrary)) { return false; } @@ -551,7 +447,8 @@ bool CParameterMgr::loadFrameworkConfiguration(string& strError) getConfigurableDomains()->setName(getConstFrameworkConfiguration()->getSystemClassName()); // Get subsystem plugins elements - _pSubsystemPlugins = static_cast<const CSubsystemPlugins*>(getConstFrameworkConfiguration()->findChild("SubsystemPlugins")); + _pSubsystemPlugins = static_cast<const CSubsystemPlugins *>( + getConstFrameworkConfiguration()->findChild("SubsystemPlugins")); if (!_pSubsystemPlugins) { @@ -561,47 +458,74 @@ bool CParameterMgr::loadFrameworkConfiguration(string& strError) } // Log tuning availability - log_info("Tuning %s", getConstFrameworkConfiguration()->isTuningAllowed() ? "allowed" : "prohibited"); + info() << "Tuning " + << (getConstFrameworkConfiguration()->isTuningAllowed() ? "allowed" : "prohibited"); return true; } -bool CParameterMgr::loadStructure(string& strError) +bool CParameterMgr::loadSubsystems(std::string &error) +{ + LOG_CONTEXT("Loading subsystem plugins"); + + // Load subsystems + bool isSuccess = + getSystemClass()->loadSubsystems(error, _pSubsystemPlugins, !_bFailOnMissingSubsystem); + + if (isSuccess) { + info() << "All subsystem plugins successfully loaded"; + + if (!error.empty()) { + // Log missing subsystems as info + info() << error; + } + } else { + warning() << error; + } + return isSuccess; +} + +bool CParameterMgr::loadStructure(string &strError) { // Retrieve system to load structure to - CSystemClass* pSystemClass = getSystemClass(); + CSystemClass *pSystemClass = getSystemClass(); - log_info("Loading %s system class structure", pSystemClass->getName().c_str()); + LOG_CONTEXT("Loading " + pSystemClass->getName() + " system class structure"); // Get structure description element - const CFrameworkConfigurationLocation* pStructureDescriptionFileLocation = static_cast<const CFrameworkConfigurationLocation*>(getConstFrameworkConfiguration()->findChildOfKind("StructureDescriptionFileLocation")); + const CFrameworkConfigurationLocation *pStructureDescriptionFileLocation = + static_cast<const CFrameworkConfigurationLocation *>( + getConstFrameworkConfiguration()->findChildOfKind("StructureDescriptionFileLocation")); if (!pStructureDescriptionFileLocation) { - strError = "No StructureDescriptionFileLocation element found for SystemClass " + pSystemClass->getName(); + strError = "No StructureDescriptionFileLocation element found for SystemClass " + + pSystemClass->getName(); return false; } - // Get Xml structure folder - string strXmlStructureFolder = pStructureDescriptionFileLocation->getFolderPath(_strXmlConfigurationFolderPath); - - // Get Xml structure file name - string strXmlStructureFilePath = pStructureDescriptionFileLocation->getFilePath(_strXmlConfigurationFolderPath); - // Parse Structure XML file - CXmlParameterSerializingContext parameterBuildContext(strError); + CParameterAccessContext accessContext(strError); + CXmlParameterSerializingContext parameterBuildContext(accessContext, strError); - CAutoLog autolog(pSystemClass, "Importing system structure from file " + strXmlStructureFilePath); + { + // Get structure URI + string structureUri = + CXmlDocSource::mkUri(_xmlConfigurationUri, pStructureDescriptionFileLocation->getUri()); - _xmlDoc *doc = CXmlDocSource::mkXmlDoc(strXmlStructureFilePath, true, true, strError); - if (doc == NULL) { - return false; - } + LOG_CONTEXT("Importing system structure from file " + structureUri); + + _xmlDoc *doc = CXmlDocSource::mkXmlDoc(structureUri, true, true, parameterBuildContext); + if (doc == NULL) { + return false; + } - if (!xmlParse(parameterBuildContext, pSystemClass, doc, strXmlStructureFolder, EParameterCreationLibrary)) { + if (!xmlParse(parameterBuildContext, pSystemClass, doc, structureUri, + EParameterCreationLibrary)) { - return false; + return false; + } } // Initialize offsets @@ -613,15 +537,15 @@ bool CParameterMgr::loadStructure(string& strError) return true; } -bool CParameterMgr::loadSettings(string& strError) +bool CParameterMgr::loadSettings(string &strError) { string strLoadError; bool success = loadSettingsFromConfigFile(strLoadError); if (!success && !_bFailOnFailedSettingsLoad) { // Load can not fail, ie continue but log the load errors - log_info("%s", strLoadError.c_str()); - log_info("Failed to load settings, continue without domains."); + warning() << strLoadError; + warning() << "Failed to load settings, continue without domains."; success = true; } @@ -634,12 +558,14 @@ bool CParameterMgr::loadSettings(string& strError) return true; } -bool CParameterMgr::loadSettingsFromConfigFile(string& strError) +bool CParameterMgr::loadSettingsFromConfigFile(string &strError) { - CAutoLog autoLog(this, "Loading settings"); + LOG_CONTEXT("Loading settings"); // Get settings configuration element - const CFrameworkConfigurationGroup* pParameterConfigurationGroup = static_cast<const CFrameworkConfigurationGroup*>(getConstFrameworkConfiguration()->findChildOfKind("SettingsConfiguration")); + const CFrameworkConfigurationGroup *pParameterConfigurationGroup = + static_cast<const CFrameworkConfigurationGroup *>( + getConstFrameworkConfiguration()->findChildOfKind("SettingsConfiguration")); if (!pParameterConfigurationGroup) { @@ -647,98 +573,75 @@ bool CParameterMgr::loadSettingsFromConfigFile(string& strError) return true; } - // Get binary settings file location - const CFrameworkConfigurationLocation* pBinarySettingsFileLocation = static_cast<const CFrameworkConfigurationLocation*>(pParameterConfigurationGroup->findChildOfKind("BinarySettingsFileLocation")); - - string strXmlBinarySettingsFilePath; - - if (pBinarySettingsFileLocation) { - - // Get Xml binary settings file name - strXmlBinarySettingsFilePath = pBinarySettingsFileLocation->getFilePath(_strXmlConfigurationFolderPath); - } // Get configurable domains element - const CFrameworkConfigurationLocation* pConfigurableDomainsFileLocation = static_cast<const CFrameworkConfigurationLocation*>(pParameterConfigurationGroup->findChildOfKind("ConfigurableDomainsFileLocation")); + const CFrameworkConfigurationLocation *pConfigurableDomainsFileLocation = + static_cast<const CFrameworkConfigurationLocation *>( + pParameterConfigurationGroup->findChildOfKind("ConfigurableDomainsFileLocation")); if (!pConfigurableDomainsFileLocation) { - strError = "No ConfigurableDomainsFileLocation element found for SystemClass " + getSystemClass()->getName(); + strError = "No ConfigurableDomainsFileLocation element found for SystemClass " + + getSystemClass()->getName(); return false; } // Get destination root element - CConfigurableDomains* pConfigurableDomains = getConfigurableDomains(); + CConfigurableDomains *pConfigurableDomains = getConfigurableDomains(); - // Get Xml configuration domains file name - string strXmlConfigurationDomainsFilePath = pConfigurableDomainsFileLocation->getFilePath(_strXmlConfigurationFolderPath); + // Get Xml configuration domains URI + string configurationDomainsUri = + CXmlDocSource::mkUri(_xmlConfigurationUri, pConfigurableDomainsFileLocation->getUri()); - // Get Xml configuration domains folder - string strXmlConfigurationDomainsFolder = pConfigurableDomainsFileLocation->getFolderPath(_strXmlConfigurationFolderPath); - - // Parse configuration domains XML file (ask to read settings from XML file if they are not provided as binary) - CXmlDomainImportContext xmlDomainImportContext(strError, !pBinarySettingsFileLocation, - *getSystemClass()); + // Parse configuration domains XML file + CXmlDomainImportContext xmlDomainImportContext(strError, true, *getSystemClass()); // Selection criteria definition for rule creation - xmlDomainImportContext.setSelectionCriteriaDefinition(getConstSelectionCriteria()->getSelectionCriteriaDefinition()); + xmlDomainImportContext.setSelectionCriteriaDefinition( + getConstSelectionCriteria()->getSelectionCriteriaDefinition()); - // Auto validation of configurations if no binary settings provided - xmlDomainImportContext.setAutoValidationRequired(!pBinarySettingsFileLocation); + // Auto validation of configurations + xmlDomainImportContext.setAutoValidationRequired(true); - log_info("Importing configurable domains from file %s %s settings", strXmlConfigurationDomainsFilePath.c_str(), pBinarySettingsFileLocation ? "without" : "with"); + info() << "Importing configurable domains from file " << configurationDomainsUri + << " with settings"; - _xmlDoc *doc = CXmlDocSource::mkXmlDoc(strXmlConfigurationDomainsFilePath, true, true, strError); + _xmlDoc *doc = + CXmlDocSource::mkXmlDoc(configurationDomainsUri, true, true, xmlDomainImportContext); if (doc == NULL) { return false; } - if (!xmlParse(xmlDomainImportContext, pConfigurableDomains, doc, strXmlConfigurationDomainsFolder, EParameterConfigurationLibrary, "SystemClassName")) { - - return false; - } - // We have loaded the whole system structure, compute checksum - const CSystemClass* pSystemClass = getConstSystemClass(); - _uiStructureChecksum = pSystemClass->computeStructureChecksum() + getConfigurableDomains()->computeStructureChecksum() + getSelectionCriteria()->computeStructureChecksum(); - - // Load binary settings if any provided - if (pBinarySettingsFileLocation && !pConfigurableDomains->serializeSettings(strXmlBinarySettingsFilePath, false, _uiStructureChecksum, strError)) { - - return false; - } - - return true; + return xmlParse(xmlDomainImportContext, pConfigurableDomains, doc, _xmlConfigurationUri, + EParameterConfigurationLibrary, true, "SystemClassName"); } // XML parsing -bool CParameterMgr::xmlParse(CXmlElementSerializingContext& elementSerializingContext, - CElement* pRootElement, _xmlDoc* doc, - const string& strXmlFolder, - CParameterMgr::ElementLibrary eElementLibrary, - const string& strNameAttributeName) +bool CParameterMgr::xmlParse(CXmlElementSerializingContext &elementSerializingContext, + CElement *pRootElement, _xmlDoc *doc, const string &baseUri, + CParameterMgr::ElementLibrary eElementLibrary, bool replace, + const string &strNameAttributeName) { // Init serializing context - elementSerializingContext.set(_pElementLibrarySet->getElementLibrary( - eElementLibrary), strXmlFolder, _strSchemaFolderLocation); + elementSerializingContext.set(_pElementLibrarySet->getElementLibrary(eElementLibrary), baseUri); - // Get Schema file associated to root element - string strXmlSchemaFilePath = _strSchemaFolderLocation + "/" + pRootElement->getKind() + ".xsd"; + CXmlDocSource docSource(doc, _bValidateSchemasOnStart, pRootElement->getXmlElementName(), + pRootElement->getName(), strNameAttributeName); - CXmlDocSource docSource(doc, _bValidateSchemasOnStart, - strXmlSchemaFilePath, - pRootElement->getKind(), - pRootElement->getName(), - strNameAttributeName); + docSource.setSchemaBaseUri(getSchemaUri()); // Start clean - pRootElement->clean(); + auto clean = [replace, &pRootElement] { + if (replace) { + pRootElement->clean(); + } + }; + clean(); CXmlMemoryDocSink memorySink(pRootElement); if (!memorySink.process(docSource, elementSerializingContext)) { - //Cleanup - pRootElement->clean(); - + clean(); return false; } @@ -746,26 +649,28 @@ bool CParameterMgr::xmlParse(CXmlElementSerializingContext& elementSerializingCo } // Init -bool CParameterMgr::init(string& strError) +bool CParameterMgr::init(string &strError) { return base::init(strError); } // Selection criteria interface -CSelectionCriterionType* CParameterMgr::createSelectionCriterionType(bool bIsInclusive) +CSelectionCriterionType *CParameterMgr::createSelectionCriterionType(bool bIsInclusive) { // Propagate return getSelectionCriteria()->createSelectionCriterionType(bIsInclusive); } -CSelectionCriterion* CParameterMgr::createSelectionCriterion(const string& strName, const CSelectionCriterionType* pSelectionCriterionType) +CSelectionCriterion *CParameterMgr::createSelectionCriterion( + const string &strName, const CSelectionCriterionType *pSelectionCriterionType) { // Propagate - return getSelectionCriteria()->createSelectionCriterion(strName, pSelectionCriterionType); + return getSelectionCriteria()->createSelectionCriterion(strName, pSelectionCriterionType, + _logger); } // Selection criterion retrieval -CSelectionCriterion* CParameterMgr::getSelectionCriterion(const string& strName) +CSelectionCriterion *CParameterMgr::getSelectionCriterion(const string &strName) { // Propagate return getSelectionCriteria()->getSelectionCriterion(strName); @@ -774,10 +679,10 @@ CSelectionCriterion* CParameterMgr::getSelectionCriterion(const string& strName) // Configuration application void CParameterMgr::applyConfigurations() { - CAutoLog autoLog(this, "Configuration application request"); + LOG_CONTEXT("Configuration application request"); // Lock state - CAutoLock autoLock(&_blackboardMutex); + lock_guard<mutex> autoLock(getBlackboardMutex()); if (!_bTuningModeIsOn) { @@ -785,13 +690,12 @@ void CParameterMgr::applyConfigurations() doApplyConfigurations(false); } else { - log_warning("Configurations were not applied because the TuningMode is on"); + warning() << "Configurations were not applied because the TuningMode is on"; } } -// Get the configurableElement corresponding to the given path -const CConfigurableElement* CParameterMgr::getConfigurableElement(const string& strPath, - string& strError) const +const CConfigurableElement *CParameterMgr::getConfigurableElement(const string &strPath, + string &strError) const { CPathNavigator pathNavigator(strPath); @@ -802,7 +706,7 @@ const CConfigurableElement* CParameterMgr::getConfigurableElement(const string& } // Find element - const CElement* pElement = getConstSystemClass()->findDescendant(pathNavigator); + const CElement *pElement = getConstSystemClass()->findDescendant(pathNavigator); if (!pElement) { @@ -812,15 +716,24 @@ const CConfigurableElement* CParameterMgr::getConfigurableElement(const string& } // Check found element is a parameter - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pElement); return pConfigurableElement; } +CConfigurableElement *CParameterMgr::getConfigurableElement(const string &strPath, string &strError) +{ + // Implement the mutable version by calling the const one and removing + // the const from the result. + const auto *constThis = this; + return const_cast<CConfigurableElement *>(constThis->getConfigurableElement(strPath, strError)); +} + // Dynamic parameter handling -CParameterHandle* CParameterMgr::createParameterHandle(const string& strPath, string& strError) +CParameterHandle *CParameterMgr::createParameterHandle(const string &strPath, string &strError) { - const CConfigurableElement* pConfigurableElement = getConfigurableElement(strPath, strError); + CConfigurableElement *pConfigurableElement = getConfigurableElement(strPath, strError); if (!pConfigurableElement) { @@ -838,7 +751,69 @@ CParameterHandle* CParameterMgr::createParameterHandle(const string& strPath, st } // Convert as parameter and return new handle - return new CParameterHandle(static_cast<const CBaseParameter*>(pConfigurableElement), this); + return new CParameterHandle(static_cast<CBaseParameter &>(*pConfigurableElement), *this); +} + +// Dynamic element handling +ElementHandle *CParameterMgr::createElementHandle(const std::string &path, std::string &error) +{ + CConfigurableElement *pConfigurableElement; + + if (path == "/") { + // Attempt to access root configurable element + pConfigurableElement = getSystemClass(); + } else { + pConfigurableElement = getConfigurableElement(path, error); + } + + if (!pConfigurableElement) { + + // Element not found + error = "Element not found: " + path; + return nullptr; + } + + // The only reason why a heap object is returned instead of retuning by copy + // is to inform the client of a failure through a nullptr. + // It could be avoided (return by copy) with an + // - optional equivalent (see boost::optional or std::experimental::optional) + // - exception (but the api is noexcept) + return new ElementHandle(*pConfigurableElement, *this); +} + +void CParameterMgr::getSettingsAsBytes(const CConfigurableElement &element, + std::vector<uint8_t> &settings) const +{ + // Not useful as the get can not fail, + // but the current design forces all serialization and deserialization to + // have an error out string + std::string error; + + // Prepare parameter access context for main blackboard. + // No need to handle output raw format and value space as Byte arrays are hexa formatted + CParameterAccessContext parameterAccessContext(error); + parameterAccessContext.setParameterBlackboard(_pMainParameterBlackboard); + + // Get the settings + element.getSettingsAsBytes(settings, parameterAccessContext); +} + +bool CParameterMgr::setSettingsAsBytes(const CConfigurableElement &element, + const std::vector<uint8_t> &settings, std::string &error) +{ + // Prepare parameter access context for main blackboard. + // Notes: + // - No need to handle output raw format and value space as Byte arrays are interpreted as + // raw formatted + // - No check is done as to the intgrity of the input data. + // This may lead to undetected out of range value assignment. + // Use this functionality with caution + CParameterAccessContext parameterAccessContext(error); + parameterAccessContext.setParameterBlackboard(_pMainParameterBlackboard); + parameterAccessContext.setAutoSync(autoSyncOn()); + + // Set the settings + return element.setSettingsAsBytes(settings, parameterAccessContext); } void CParameterMgr::setFailureOnMissingSubsystem(bool bFail) @@ -856,19 +831,19 @@ void CParameterMgr::setFailureOnFailedSettingsLoad(bool bFail) _bFailOnFailedSettingsLoad = bFail; } -bool CParameterMgr::getFailureOnFailedSettingsLoad() +bool CParameterMgr::getFailureOnFailedSettingsLoad() const { return _bFailOnFailedSettingsLoad; } -const string& CParameterMgr::getSchemaFolderLocation() const +const string &CParameterMgr::getSchemaUri() const { - return _strSchemaFolderLocation; + return _schemaUri; } -void CParameterMgr::setSchemaFolderLocation(const string& strSchemaFolderLocation) +void CParameterMgr::setSchemaUri(const string &schemaUri) { - _strSchemaFolderLocation = strSchemaFolderLocation; + _schemaUri = schemaUri; } void CParameterMgr::setValidateSchemasOnStart(bool bValidate) @@ -883,10 +858,9 @@ bool CParameterMgr::getValidateSchemasOnStart() const /////////////////// Remote command parsers /// Version -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::versionCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::versionCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - // Show version strResult = getVersion(); @@ -894,15 +868,15 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::versionCommandProce } /// Status -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::statusCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::statusCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; // System class - const CSystemClass* pSystemClass = getSystemClass(); + const CSystemClass *pSystemClass = getSystemClass(); // Show status /// General section - CUtility::appendTitle(strResult, "General:"); + utility::appendTitle(strResult, "General:"); // System class strResult += "System Class: "; strResult += pSystemClass->getName(); @@ -929,31 +903,30 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::statusCommandProces strResult += "\n"; /// Subsystem list - CUtility::appendTitle(strResult, "Subsystems:"); + utility::appendTitle(strResult, "Subsystems:"); string strSubsystemList; pSystemClass->listChildrenPaths(strSubsystemList); strResult += strSubsystemList; /// Last applied configurations - CUtility::appendTitle(strResult, "Last Applied [Pending] Configurations:"); + utility::appendTitle(strResult, "Last Applied [Pending] Configurations:"); string strLastAppliedConfigurations; getConfigurableDomains()->listLastAppliedConfigurations(strLastAppliedConfigurations); strResult += strLastAppliedConfigurations; /// Criteria states - CUtility::appendTitle(strResult, "Selection Criteria:"); + utility::appendTitle(strResult, "Selection Criteria:"); list<string> lstrSelectionCriteria; getSelectionCriteria()->listSelectionCriteria(lstrSelectionCriteria, false, true); // Concatenate the criterion list as the command result - string strCriteriaStates; - CUtility::asString(lstrSelectionCriteria, strCriteriaStates); - strResult += strCriteriaStates; + strResult += utility::asString(lstrSelectionCriteria); return CCommandHandler::ESucceeded; } /// Tuning Mode -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setTuningModeCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setTuningModeCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { if (remoteCommand.getArgument(0) == "on") { @@ -974,20 +947,18 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setTuningModeComman return CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getTuningModeCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getTuningModeCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - strResult = tuningModeOn() ? "on" : "off"; return CCommandHandler::ESucceeded; } /// Value Space -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setValueSpaceCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setValueSpaceCommandProcess( + const IRemoteCommand &remoteCommand, string & /*strResult*/) { - (void)strResult; - if (remoteCommand.getArgument(0) == "raw") { setValueSpace(true); @@ -1007,20 +978,18 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setValueSpaceComman return CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getValueSpaceCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getValueSpaceCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - strResult = valueSpaceIsRaw() ? "raw" : "real"; return CCommandHandler::ESucceeded; } /// Output Raw Format -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setOutputRawFormatCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setOutputRawFormatCommandProcess( + const IRemoteCommand &remoteCommand, string & /*strResult*/) { - (void)strResult; - if (remoteCommand.getArgument(0) == "hex") { setOutputRawFormat(true); @@ -1040,17 +1009,17 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setOutputRawFormatC return CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getOutputRawFormatCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getOutputRawFormatCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - strResult = outputRawFormatIsHex() ? "hex" : "dec"; return CCommandHandler::ESucceeded; } /// Sync -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setAutoSyncCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setAutoSyncCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { if (remoteCommand.getArgument(0) == "on") { @@ -1071,24 +1040,23 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setAutoSyncCommandP return CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getAutoSyncCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getAutoSyncCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - strResult = autoSyncOn() ? "on" : "off"; return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::syncCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::syncCommandProcess( + const IRemoteCommand &, string &strResult) { - (void)remoteCommand; - return sync(strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; } /// Criteria -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listCriteriaCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listCriteriaCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { if (remoteCommand.getArgumentCount() > 1) { @@ -1104,7 +1072,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listCriteriaCommand strOutputFormat = remoteCommand.getArgument(0); // Capitalize - std::transform(strOutputFormat.begin(), strOutputFormat.end(), strOutputFormat.begin(), ::toupper); + std::transform(strOutputFormat.begin(), strOutputFormat.end(), strOutputFormat.begin(), + ::toupper); if (strOutputFormat != "XML" && strOutputFormat != "CSV") { @@ -1114,10 +1083,11 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listCriteriaCommand if (strOutputFormat == "XML") { // Get Root element where to export from - const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition = getConstSelectionCriteria()->getSelectionCriteriaDefinition(); + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition = + getConstSelectionCriteria()->getSelectionCriteriaDefinition(); if (!exportElementToXMLString(pSelectionCriteriaDefinition, "SelectionCriteria", - strResult)) { + CXmlSerializingContext{strResult}, strResult)) { return CCommandHandler::EFailed; } @@ -1133,46 +1103,51 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listCriteriaCommand getSelectionCriteria()->listSelectionCriteria(lstrResult, true, bHumanReadable); // Concatenate the criterion list as the command result - CUtility::asString(lstrResult, strResult); + strResult += utility::asString(lstrResult); return CCommandHandler::ESucceeded; } } /// Domains -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listDomainsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listDomainsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - getConfigurableDomains()->listDomains(strResult); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::createDomainCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::createDomainCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return createDomain(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return createDomain(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteDomainCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteDomainCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return deleteDomain(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return deleteDomain(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteAllDomainsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteAllDomainsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - return deleteAllDomains(strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::renameDomainCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::renameDomainCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return renameDomain(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return renameDomain(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setSequenceAwarenessCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setSequenceAwarenessCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Set property bool bSequenceAware; @@ -1190,11 +1165,13 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setSequenceAwarenes return CCommandHandler::EShowUsage; } - return setSequenceAwareness(remoteCommand.getArgument(0), bSequenceAware, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return setSequenceAwareness(remoteCommand.getArgument(0), bSequenceAware, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getSequenceAwarenessCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getSequenceAwarenessCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Get property bool bSequenceAware; @@ -1209,142 +1186,182 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getSequenceAwarenes return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listDomainElementsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listDomainElementsCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return getConfigurableDomains()->listDomainElements(remoteCommand.getArgument(0), strResult) ? CCommandHandler::ESucceeded : CCommandHandler::EFailed; + return getConfigurableDomains()->listDomainElements(remoteCommand.getArgument(0), strResult) + ? CCommandHandler::ESucceeded + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::addElementCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::addElementCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return addConfigurableElementToDomain(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return addConfigurableElementToDomain(remoteCommand.getArgument(0), + remoteCommand.getArgument(1), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::removeElementCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::removeElementCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return removeConfigurableElementFromDomain(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return removeConfigurableElementFromDomain(remoteCommand.getArgument(0), + remoteCommand.getArgument(1), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::splitDomainCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::splitDomainCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return split(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return split(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } /// Configurations -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listConfigurationsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listConfigurationsCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return getConstConfigurableDomains()->listConfigurations(remoteCommand.getArgument(0), strResult) ? CCommandHandler::ESucceeded : CCommandHandler::EFailed; + return getConstConfigurableDomains()->listConfigurations(remoteCommand.getArgument(0), + strResult) + ? CCommandHandler::ESucceeded + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::dumpDomainsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::dumpDomainsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - // Dummy error context string strError; - CErrorContext errorContext(strError); + utility::ErrorContext errorContext(strError); // Dump - getConstConfigurableDomains()->dumpContent(strResult, errorContext); + strResult = getConstConfigurableDomains()->dumpContent(errorContext); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::createConfigurationCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::createConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return createConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return createConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), + strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteConfigurationCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::deleteConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return deleteConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return deleteConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), + strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::renameConfigurationCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::renameConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { return renameConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), - remoteCommand.getArgument(2), strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + remoteCommand.getArgument(2), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::saveConfigurationCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::saveConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return saveConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return saveConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::restoreConfigurationCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::restoreConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - list<string> lstrResult; - if (!restoreConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), lstrResult)) { - //Concatenate the error list as the command result - CUtility::asString(lstrResult, strResult); + core::Results result; + if (!restoreConfiguration(remoteCommand.getArgument(0), remoteCommand.getArgument(1), result)) { + // Concatenate the error list as the command result + strResult = utility::asString(result); - return CCommandHandler::EFailed; + return CCommandHandler::EFailed; } return CCommandHandler::EDone; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setElementSequenceCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setElementSequenceCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Build configurable element path list std::vector<string> astrNewElementSequence; - uint32_t uiArgument; + for (size_t argument = 2; argument < remoteCommand.getArgumentCount(); argument++) { - for (uiArgument = 2; uiArgument < remoteCommand.getArgumentCount(); uiArgument++) { - - astrNewElementSequence.push_back(remoteCommand.getArgument(uiArgument)); + astrNewElementSequence.push_back(remoteCommand.getArgument(argument)); } // Delegate to configurable domains return setElementSequence(remoteCommand.getArgument(0), remoteCommand.getArgument(1), - astrNewElementSequence, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + astrNewElementSequence, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSequenceCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSequenceCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Delegate to configurable domains - return getConfigurableDomains()->getElementSequence(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) ? CCommandHandler::ESucceeded : CCommandHandler::EFailed; + return getConfigurableDomains()->getElementSequence(remoteCommand.getArgument(0), + remoteCommand.getArgument(1), strResult) + ? CCommandHandler::ESucceeded + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setRuleCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setRuleCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Delegate to configurable domains return setApplicationRule(remoteCommand.getArgument(0), remoteCommand.getArgument(1), - remoteCommand.packArguments(2, remoteCommand.getArgumentCount() - 2), strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + remoteCommand.packArguments(2, remoteCommand.getArgumentCount() - 2), + strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::clearRuleCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::clearRuleCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Delegate to configurable domains return clearApplicationRule(remoteCommand.getArgument(0), remoteCommand.getArgument(1), - strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getRuleCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getRuleCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Delegate to configurable domains - return getApplicationRule(remoteCommand.getArgument(0), remoteCommand.getArgument(1), - strResult) ? - CCommandHandler::ESucceeded : CCommandHandler::EFailed; + return getApplicationRule(remoteCommand.getArgument(0), remoteCommand.getArgument(1), strResult) + ? CCommandHandler::ESucceeded + : CCommandHandler::EFailed; } /// Elements/Parameters -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listElementsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listElementsCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass(), false); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { return CCommandHandler::EFailed; } - strResult = string("\n"); - if (!pLocatedElement) { // List from root folder @@ -1360,19 +1377,18 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listElementsCommand } /// Elements/Parameters -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listParametersCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listParametersCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass(), false); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { return CCommandHandler::EFailed; } - strResult = string("\n"); - if (!pLocatedElement) { // List from root folder @@ -1387,11 +1403,226 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listParametersComma return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::dumpElementCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementStructureXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) +{ + CElementLocator elementLocator(getSystemClass()); + + CElement *pLocatedElement = NULL; + + if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { + + return CCommandHandler::EFailed; + } + + // Use default access context for structure export + CParameterAccessContext accessContext(strResult); + if (!exportElementToXMLString(pLocatedElement, pLocatedElement->getXmlElementName(), + CXmlParameterSerializingContext{accessContext, strResult}, + strResult)) { + + return CCommandHandler::EFailed; + } + + return CCommandHandler::ESucceeded; +} + +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementBytesCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult) +{ + CElementLocator elementLocator(getSystemClass()); + + CElement *pLocatedElement = NULL; + + if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { + + return CCommandHandler::EFailed; + } + + const CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(pLocatedElement); + + // Get the settings + vector<uint8_t> bytes; + getSettingsAsBytes(*pConfigurableElement, bytes); + + // Hexa formatting + std::ostringstream ostream; + ostream << std::hex << std::setfill('0'); + + // Format bytes + for (auto byte : bytes) { + + // Convert to an int in order to avoid the "char" overload that would + // print characters instead of numbers. + ostream << "0x" << std::setw(2) << int{byte} << " "; + } + + strResult = ostream.str(); + if (not strResult.empty()) { + // Remove the trailing space + strResult.pop_back(); + } + + return CCommandHandler::ESucceeded; +} + +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setElementBytesCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { + // Check tuning mode + if (!checkTuningModeOn(strResult)) { + + return CCommandHandler::EFailed; + } + + // Retrieve configurable element CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; + + if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { + + return CCommandHandler::EFailed; + } + + const CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(pLocatedElement); + + // Convert input data to binary + vector<uint8_t> bytes; + + auto first = remoteCommand.getArguments().cbegin() + 1; + auto last = remoteCommand.getArguments().cend(); + + try { + std::transform(first, last, begin(bytes), [](decltype(*first) input) { + uint8_t byte; + + if (!convertTo(input, byte)) { + throw std::domain_error("Some values out of byte range"); + } + + return byte; + }); + } catch (const std::domain_error &e) { + strResult = e.what(); + + return CCommandHandler::EFailed; + } + + // Set the settings + if (!setSettingsAsBytes(*pConfigurableElement, bytes, strResult)) { + + return CCommandHandler::EFailed; + } + + return CCommandHandler::EDone; +} + +bool CParameterMgr::getSettingsAsXML(const CConfigurableElement *configurableElement, + string &result) const +{ + string error; + CConfigurationAccessContext configContext(error, _pMainParameterBlackboard, _bValueSpaceIsRaw, + _bOutputRawFormatIsHex, true); + + CXmlParameterSerializingContext xmlParameterContext(configContext, error); + + // Use a doc source by loading data from instantiated Configurable Domains + CXmlMemoryDocSource memorySource(configurableElement, false, + configurableElement->getXmlElementName()); + + // Use a doc sink that write the doc data in a string + ostringstream output; + CXmlStreamDocSink streamSink(output); + + if (not streamSink.process(memorySource, xmlParameterContext)) { + result = error; + return false; + } + result = output.str(); + return true; +} + +bool CParameterMgr::setSettingsAsXML(CConfigurableElement *configurableElement, + const string &settings, string &error) +{ + CConfigurationAccessContext configContext(error, _pMainParameterBlackboard, _bValueSpaceIsRaw, + _bOutputRawFormatIsHex, false); + + CXmlParameterSerializingContext xmlParameterContext(configContext, error); + + // It doesn't make sense to resolve XIncludes on an imported file because + // we can't reliably decide of a "base url" + _xmlDoc *doc = CXmlDocSource::mkXmlDoc(settings, false, false, xmlParameterContext); + if (doc == nullptr) { + return false; + } + if (not xmlParse(xmlParameterContext, configurableElement, doc, "", + EParameterConfigurationLibrary, false)) { + return false; + } + if (_bAutoSyncOn) { + CSyncerSet syncerSet; + static_cast<CConfigurableElement *>(configurableElement)->fillSyncerSet(syncerSet); + core::Results errors; + if (not syncerSet.sync(*_pMainParameterBlackboard, false, &errors)) { + error = utility::asString(errors); + + return false; + } + } + return true; +} + +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &result) +{ + CElementLocator elementLocator(getSystemClass()); + + CElement *locatedElement = nullptr; + + if (not elementLocator.locate(remoteCommand.getArgument(0), &locatedElement, result)) { + + return CCommandHandler::EFailed; + } + + if (not getSettingsAsXML(static_cast<CConfigurableElement *>(locatedElement), result)) { + return CCommandHandler::EFailed; + } + return CCommandHandler::ESucceeded; +} + +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setElementXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &result) +{ + if (!checkTuningModeOn(result)) { + + return CCommandHandler::EFailed; + } + + CElementLocator elementLocator(getSystemClass()); + + CElement *locatedElement = nullptr; + + if (not elementLocator.locate(remoteCommand.getArgument(0), &locatedElement, result)) { + + return CCommandHandler::EFailed; + } + if (not setSettingsAsXML(static_cast<CConfigurableElement *>(locatedElement), + remoteCommand.getArgument(1), result)) { + return CCommandHandler::EFailed; + } + return CCommandHandler::EDone; +} + +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::dumpElementCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) +{ + CElementLocator elementLocator(getSystemClass()); + + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { @@ -1400,19 +1631,21 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::dumpElementCommandP string strError; - CParameterAccessContext parameterAccessContext(strError, _pMainParameterBlackboard, _bValueSpaceIsRaw, _bOutputRawFormatIsHex); + CParameterAccessContext parameterAccessContext(strError, _pMainParameterBlackboard, + _bValueSpaceIsRaw, _bOutputRawFormatIsHex); // Dump elements - pLocatedElement->dumpContent(strResult, parameterAccessContext); + strResult = pLocatedElement->dumpContent(parameterAccessContext); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSizeCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSizeCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { @@ -1420,7 +1653,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSizeComma } // Converted to actual sizable element - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pLocatedElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pLocatedElement); // Get size as string strResult = pConfigurableElement->getFootprintAsString(); @@ -1428,11 +1662,12 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getElementSizeComma return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showPropertiesCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showPropertiesCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { @@ -1440,7 +1675,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showPropertiesComma } // Convert element - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pLocatedElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pLocatedElement); // Return element properties pConfigurableElement->showProperties(strResult); @@ -1448,7 +1684,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showPropertiesComma return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getParameterCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getParameterCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { string strValue; @@ -1462,19 +1699,23 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getParameterCommand return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setParameterCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setParameterCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { // Get value to set string strValue = remoteCommand.packArguments(1, remoteCommand.getArgumentCount() - 1); - return accessParameterValue(remoteCommand.getArgument(0), strValue, true, strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return accessParameterValue(remoteCommand.getArgument(0), strValue, true, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listBelongingDomainsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listBelongingDomainsCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { @@ -1482,7 +1723,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listBelongingDomain } // Convert element - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pLocatedElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pLocatedElement); // Return element belonging domains pConfigurableElement->listBelongingDomains(strResult); @@ -1490,11 +1732,12 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listBelongingDomain return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedDomainsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedDomainsCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(remoteCommand.getArgument(0), &pLocatedElement, strResult)) { @@ -1502,7 +1745,8 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedDomai } // Convert element - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pLocatedElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pLocatedElement); // Return element belonging domains pConfigurableElement->listAssociatedDomains(strResult); @@ -1510,39 +1754,38 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedDomai return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedElementsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listAssociatedElementsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - getConfigurableDomains()->listAssociatedElements(strResult); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listConflictingElementsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listConflictingElementsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - getConfigurableDomains()->listConflictingElements(strResult); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listRogueElementsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::listRogueElementsCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - getSystemClass()->listRogueElements(strResult); return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getConfigurationParameterCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + getConfigurationParameterCommandProcess(const IRemoteCommand &remoteCommand, string &strResult) { string strOutputValue; string strError; - if (!accessConfigurationValue(remoteCommand.getArgument(0), remoteCommand.getArgument(1), remoteCommand.getArgument(2), strOutputValue, false, strError)) { + if (!accessConfigurationValue(remoteCommand.getArgument(0), remoteCommand.getArgument(1), + remoteCommand.getArgument(2), strOutputValue, false, strError)) { strResult = strError; return CCommandHandler::EFailed; @@ -1553,22 +1796,21 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getConfigurationPar return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setConfigurationParameterCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + setConfigurationParameterCommandProcess(const IRemoteCommand &remoteCommand, string &strResult) { // Get value to set string strValue = remoteCommand.packArguments(3, remoteCommand.getArgumentCount() - 3); - bool bSuccess = accessConfigurationValue(remoteCommand.getArgument(0), - remoteCommand.getArgument(1), - remoteCommand.getArgument(2), - strValue, true, strResult); + bool bSuccess = + accessConfigurationValue(remoteCommand.getArgument(0), remoteCommand.getArgument(1), + remoteCommand.getArgument(2), strValue, true, strResult); return bSuccess ? CCommandHandler::EDone : CCommandHandler::EFailed; } CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showMappingCommandProcess( - const IRemoteCommand& remoteCommand, - string& strResult) + const IRemoteCommand &remoteCommand, string &strResult) { if (!getParameterMapping(remoteCommand.getArgument(0), strResult)) { @@ -1579,48 +1821,53 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::showMappingCommandP } /// Settings Import/Export -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::exportDomainsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::exportDomainsXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { string strFileName = remoteCommand.getArgument(0); - return exportDomainsXml(strFileName, false, true, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return exportDomainsXml(strFileName, false, true, strResult) ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::importDomainsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::importDomainsXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { - return importDomainsXml(remoteCommand.getArgument(0), false, true, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return importDomainsXml(remoteCommand.getArgument(0), false, true, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::exportDomainsWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + exportDomainsWithSettingsXMLCommandProcess(const IRemoteCommand &remoteCommand, + string &strResult) { string strFileName = remoteCommand.getArgument(0); - return exportDomainsXml(strFileName, true, true, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return exportDomainsXml(strFileName, true, true, strResult) ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::exportDomainWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& result) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + exportDomainWithSettingsXMLCommandProcess(const IRemoteCommand &remoteCommand, string &result) { string domainName = remoteCommand.getArgument(0); string fileName = remoteCommand.getArgument(1); - return exportSingleDomainXml(fileName, domainName, true, true, result) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return exportSingleDomainXml(fileName, domainName, true, true, result) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::importDomainsWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + importDomainsWithSettingsXMLCommandProcess(const IRemoteCommand &remoteCommand, + string &strResult) { - return importDomainsXml(remoteCommand.getArgument(0), true, true, strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return importDomainsXml(remoteCommand.getArgument(0), true, true, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::importDomainWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + importDomainWithSettingsXMLCommandProcess(const IRemoteCommand &remoteCommand, + string &strResult) { bool bOverwrite = false; @@ -1636,26 +1883,14 @@ CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::importDomainWithSet } } - return importSingleDomainXml(remoteCommand.getArgument(0), bOverwrite, true, true, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; -} - -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::exportSettingsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) -{ - return exportDomainsBinary(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; + return importSingleDomainXml(remoteCommand.getArgument(0), bOverwrite, true, true, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::importSettingsCommandProcess(const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + getDomainsWithSettingsXMLCommandProcess(const IRemoteCommand & /*command*/, string &strResult) { - return importDomainsBinary(remoteCommand.getArgument(0), strResult) ? CCommandHandler::EDone : CCommandHandler::EFailed; -} - -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::getDomainsWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) -{ - (void)remoteCommand; - if (!exportDomainsXml(strResult, true, false, strResult)) { return CCommandHandler::EFailed; @@ -1664,27 +1899,26 @@ CParameterMgr::CCommandHandler::CommandStatus return CCommandHandler::ESucceeded; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::getDomainWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getDomainWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &strResult) { string strDomainName = remoteCommand.getArgument(0); - return exportSingleDomainXml(strResult, strDomainName, true, false, strResult) ? - CCommandHandler::ESucceeded : CCommandHandler::EFailed; + return exportSingleDomainXml(strResult, strDomainName, true, false, strResult) + ? CCommandHandler::ESucceeded + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::setDomainsWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr:: + setDomainsWithSettingsXMLCommandProcess(const IRemoteCommand &remoteCommand, string &strResult) { - return importDomainsXml(remoteCommand.getArgument(0), true, false, strResult) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return importDomainsXml(remoteCommand.getArgument(0), true, false, strResult) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::setDomainWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& result) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::setDomainWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, string &result) { bool overwrite = false; @@ -1699,21 +1933,22 @@ CParameterMgr::CCommandHandler::CommandStatus } } - return importSingleDomainXml(remoteCommand.getArgument(0), overwrite, true, false, result) ? - CCommandHandler::EDone : CCommandHandler::EFailed; + return importSingleDomainXml(remoteCommand.getArgument(0), overwrite, true, false, result) + ? CCommandHandler::EDone + : CCommandHandler::EFailed; } -CParameterMgr::CCommandHandler::CommandStatus - CParameterMgr::getSystemClassXMLCommandProcess( - const IRemoteCommand& remoteCommand, string& strResult) +CParameterMgr::CCommandHandler::CommandStatus CParameterMgr::getSystemClassXMLCommandProcess( + const IRemoteCommand & /*command*/, string &strResult) { - (void)remoteCommand; - // Get Root element where to export from - const CSystemClass* pSystemClass = getSystemClass(); - - if (!exportElementToXMLString(pSystemClass, pSystemClass->getKind(), strResult)) { + const CSystemClass *pSystemClass = getSystemClass(); + // Use default access context for structure export + CParameterAccessContext accessContext(strResult); + if (!exportElementToXMLString(pSystemClass, pSystemClass->getXmlElementName(), + CXmlParameterSerializingContext{accessContext, strResult}, + strResult)) { return CCommandHandler::EFailed; } // Succeeded @@ -1721,7 +1956,8 @@ CParameterMgr::CCommandHandler::CommandStatus } // User set/get parameters in main BlackBoard -bool CParameterMgr::accessParameterValue(const string& strPath, string& strValue, bool bSet, string& strError) +bool CParameterMgr::accessParameterValue(const string &strPath, string &strValue, bool bSet, + string &strError) { // Forbid write access when not in TuningMode if (bSet && !checkTuningModeOn(strError)) { @@ -1730,7 +1966,8 @@ bool CParameterMgr::accessParameterValue(const string& strPath, string& strValue } // Define context - CParameterAccessContext parameterAccessContext(strError, _pMainParameterBlackboard, _bValueSpaceIsRaw, _bOutputRawFormatIsHex); + CParameterAccessContext parameterAccessContext(strError, _pMainParameterBlackboard, + _bValueSpaceIsRaw, _bOutputRawFormatIsHex); // Activate the auto synchronization with the hardware if (bSet) { @@ -1742,29 +1979,20 @@ bool CParameterMgr::accessParameterValue(const string& strPath, string& strValue } // User get parameter mapping -bool CParameterMgr::getParameterMapping(const string& strPath, string& strResult) const +bool CParameterMgr::getParameterMapping(const string &strPath, string &strResult) const { - CPathNavigator pathNavigator(strPath); - - // Nagivate through system class - if (!pathNavigator.navigateThrough(getConstSystemClass()->getName(), strResult)) { - - return false; - } - // Get the ConfigurableElement corresponding to strPath - const CConfigurableElement* pConfigurableElement = getConfigurableElement(strPath, strResult); + const CConfigurableElement *pConfigurableElement = getConfigurableElement(strPath, strResult); if (!pConfigurableElement) { return false; } // Find the list of the ancestors of the current ConfigurableElement that have a mapping - list<const CConfigurableElement*> configurableElementPath; - pConfigurableElement->getListOfElementsWithMapping(configurableElementPath); + auto configurableElementPath = pConfigurableElement->getConfigurableElementContext(); // Get the Subsystem containing the ConfigurableElement - const CSubsystem* pSubsystem = pConfigurableElement->getBelongingSubsystem(); + const CSubsystem *pSubsystem = pConfigurableElement->getBelongingSubsystem(); if (!pSubsystem) { strResult = "Unable to find the Subsystem containing the parameter"; @@ -1778,11 +2006,13 @@ bool CParameterMgr::getParameterMapping(const string& strPath, string& strResult } // User set/get parameters in specific Configuration BlackBoard -bool CParameterMgr::accessConfigurationValue(const string& strDomain, const string& strConfiguration, const string& strPath, string& strValue, bool bSet, string& strError) +bool CParameterMgr::accessConfigurationValue(const string &strDomain, + const string &strConfiguration, const string &strPath, + string &strValue, bool bSet, string &strError) { CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(strPath, &pLocatedElement, strError)) { @@ -1790,25 +2020,35 @@ bool CParameterMgr::accessConfigurationValue(const string& strDomain, const stri } // Convert element - const CConfigurableElement* pConfigurableElement = static_cast<const CConfigurableElement*>(pLocatedElement); + const CConfigurableElement *pConfigurableElement = + static_cast<const CConfigurableElement *>(pLocatedElement); - // Get the Configuration blackboard and the Base Offset of the configurable element in this blackboard - uint32_t uiBaseOffset; + // Get the Configuration blackboard and the Base Offset of the configurable element in this + // blackboard + size_t baseOffset; bool bIsLastApplied; - CParameterBlackboard* pConfigurationBlackboard = getConstConfigurableDomains()->findConfigurationBlackboard(strDomain, strConfiguration, pConfigurableElement, uiBaseOffset, bIsLastApplied, strError); + CParameterBlackboard *pConfigurationBlackboard = NULL; - if (!pConfigurationBlackboard) { + { + pConfigurationBlackboard = getConstConfigurableDomains()->findConfigurationBlackboard( + strDomain, strConfiguration, pConfigurableElement, baseOffset, bIsLastApplied, + strError); + if (!pConfigurationBlackboard) { - return false; + warning() << "Fail: " << strError; + return false; + } } - log_info("Element %s in Domain %s, offset: %d, base offset: %d", strPath.c_str(), strDomain.c_str(), pConfigurableElement->getOffset(), uiBaseOffset); + info() << "Element " << strPath << " in Domain " << strDomain + << ", offset: " << pConfigurableElement->getOffset() << ", base offset: " << baseOffset; /// Update the Configuration Blackboard // Define Configuration context using Base Offset and keep Auto Sync off to prevent access to HW - CParameterAccessContext parameterAccessContext(strError, pConfigurationBlackboard, _bValueSpaceIsRaw, _bOutputRawFormatIsHex, uiBaseOffset); + CParameterAccessContext parameterAccessContext( + strError, pConfigurationBlackboard, _bValueSpaceIsRaw, _bOutputRawFormatIsHex, baseOffset); // Deactivate the auto synchronization with the hardware during the Configuration Blackboard // access (only Main Blackboard shall be synchronized, Configurations Blackboards are copied @@ -1846,10 +2086,12 @@ bool CParameterMgr::accessConfigurationValue(const string& strDomain, const stri } // User set/get parameters -bool CParameterMgr::accessValue(CParameterAccessContext& parameterAccessContext, const string& strPath, string& strValue, bool bSet, string& strError) +bool CParameterMgr::accessValue(CParameterAccessContext ¶meterAccessContext, + const string &strPath, string &strValue, bool bSet, + string &strError) { // Lock state - CAutoLock autoLock(&_blackboardMutex); + lock_guard<mutex> autoLock(getBlackboardMutex()); CPathNavigator pathNavigator(strPath); @@ -1862,12 +2104,17 @@ bool CParameterMgr::accessValue(CParameterAccessContext& parameterAccessContext, } // Do the get - return getConstSystemClass()->accessValue(pathNavigator, strValue, bSet, parameterAccessContext); + return getConstSystemClass()->accessValue(pathNavigator, strValue, bSet, + parameterAccessContext); } // Tuning mode -bool CParameterMgr::setTuningMode(bool bOn, string& strError) +bool CParameterMgr::setTuningMode(bool bOn, string &strError) { + if (bOn == tuningModeOn()) { + strError = "Tuning mode is already in the state requested"; + return false; + } // Tuning allowed? if (bOn && !getConstFrameworkConfiguration()->isTuningAllowed()) { @@ -1876,17 +2123,14 @@ bool CParameterMgr::setTuningMode(bool bOn, string& strError) return false; } // Lock state - CAutoLock autoLock(&_blackboardMutex); + lock_guard<mutex> autoLock(getBlackboardMutex()); // Warn domains about exiting tuning mode - if (!bOn && _bTuningModeIsOn) { + if (!bOn) { // Ensure application of currently selected configurations // Force-apply configurations doApplyConfigurations(true); - - // Turn auto sync back on - _bAutoSyncOn = true; } // Store @@ -1924,17 +2168,13 @@ bool CParameterMgr::outputRawFormatIsHex() /// Sync // Automatic hardware synchronization control (during tuning session) -bool CParameterMgr::setAutoSync(bool bAutoSyncOn, string& strError) +bool CParameterMgr::setAutoSync(bool bAutoSyncOn, string &strError) { - // Check tuning mode - if (!checkTuningModeOn(strError)) { - - return false; - } // Warn domains about turning auto sync back on if (bAutoSyncOn && !_bAutoSyncOn) { - // Do the synchronization at system class level (could be optimized by keeping track of all modified parameters) + // Do the synchronization at system class level (could be optimized by keeping track of all + // modified parameters) if (!sync(strError)) { return false; @@ -1953,13 +2193,8 @@ bool CParameterMgr::autoSyncOn() const } // Manual hardware synchronization control (during tuning session) -bool CParameterMgr::sync(string& strError) +bool CParameterMgr::sync(string &strError) { - // Check tuning mode - if (!checkTuningModeOn(strError)) { - - return false; - } // Warn domains about turning auto sync back on if (_bAutoSyncOn) { @@ -1974,10 +2209,10 @@ bool CParameterMgr::sync(string& strError) getConstSystemClass()->fillSyncerSet(syncerSet); // Sync - list<string> lstrError; - if (! syncerSet.sync(*_pMainParameterBlackboard, false, &lstrError)){ + core::Results error; + if (!syncerSet.sync(*_pMainParameterBlackboard, false, &error)) { - CUtility::asString(lstrError, strError); + strError = utility::asString(error); return false; }; @@ -1985,8 +2220,9 @@ bool CParameterMgr::sync(string& strError) } // Configuration/Domains handling -bool CParameterMgr::createDomain(const string& strName, string& strError) +bool CParameterMgr::createDomain(const string &strName, string &strError) { + LOG_CONTEXT("Creating configurable domain " + strName); // Check tuning mode if (!checkTuningModeOn(strError)) { @@ -1994,190 +2230,280 @@ bool CParameterMgr::createDomain(const string& strName, string& strError) } // Delegate to configurable domains - return getConfigurableDomains()->createDomain(strName, strError); + return logResult(getConfigurableDomains()->createDomain(strName, strError), strError); } -bool CParameterMgr::deleteDomain(const string& strName, string& strError) +bool CParameterMgr::deleteDomain(const string &strName, string &strError) { + LOG_CONTEXT("Deleting configurable domain '" + strName + "'"); + // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail: " << strError; return false; } // Delegate to configurable domains - return getConfigurableDomains()->deleteDomain(strName, strError); + return logResult(getConfigurableDomains()->deleteDomain(strName, strError), strError); } -bool CParameterMgr::renameDomain(const string& strName, const string& strNewName, string& strError) +bool CParameterMgr::renameDomain(const string &strName, const string &strNewName, string &strError) { + LOG_CONTEXT("Renaming configurable domain '" + strName + "' to '" + strNewName + "'"); + // Delegate to configurable domains - return getConfigurableDomains()->renameDomain(strName, strNewName, strError); + return logResult(getConfigurableDomains()->renameDomain(strName, strNewName, strError), + strError); } -bool CParameterMgr::deleteAllDomains(string& strError) +bool CParameterMgr::deleteAllDomains(string &strError) { + LOG_CONTEXT("Deleting all configurable domains"); + // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail: " << strError; return false; } // Delegate to configurable domains getConfigurableDomains()->deleteAllDomains(); + info() << "Success"; return true; } -bool CParameterMgr::setSequenceAwareness(const string& strName, bool bSequenceAware, string& strResult) +bool CParameterMgr::setSequenceAwareness(const string &strName, bool bSequenceAware, + string &strResult) { + LOG_CONTEXT("Making domain '" + strName + "' sequence " + + (bSequenceAware ? "aware" : "unaware")); // Check tuning mode if (!checkTuningModeOn(strResult)) { + warning() << "Fail: " << strResult; return false; } - return getConfigurableDomains()->setSequenceAwareness(strName, bSequenceAware, strResult); + return logResult( + getConfigurableDomains()->setSequenceAwareness(strName, bSequenceAware, strResult), + strResult); } -bool CParameterMgr::getSequenceAwareness(const string& strName, bool& bSequenceAware, - string& strResult) +bool CParameterMgr::getSequenceAwareness(const string &strName, bool &bSequenceAware, + string &strResult) { return getConfigurableDomains()->getSequenceAwareness(strName, bSequenceAware, strResult); } -bool CParameterMgr::createConfiguration(const string& strDomain, const string& strConfiguration, string& strError) +bool CParameterMgr::createConfiguration(const string &strDomain, const string &strConfiguration, + string &strError) { + LOG_CONTEXT("Creating domain configuration '" + strConfiguration + "' into domain '" + + strDomain + "'"); // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail: " << strError; return false; } // Delegate to configurable domains - return getConfigurableDomains()->createConfiguration(strDomain, strConfiguration, _pMainParameterBlackboard, strError); + return logResult(getConfigurableDomains()->createConfiguration( + strDomain, strConfiguration, _pMainParameterBlackboard, strError), + strError); } -bool CParameterMgr::renameConfiguration(const string& strDomain, const string& strConfiguration, - const string& strNewConfiguration, string& strError) +bool CParameterMgr::renameConfiguration(const string &strDomain, const string &strConfiguration, + const string &strNewConfiguration, string &strError) { - return getConfigurableDomains()->renameConfiguration(strDomain, strConfiguration, - strNewConfiguration, strError); + LOG_CONTEXT("Renaming domain '" + strDomain + "''s configuration '" + strConfiguration + + "' to '" + strNewConfiguration + "'"); + + return logResult(getConfigurableDomains()->renameConfiguration(strDomain, strConfiguration, + strNewConfiguration, strError), + strError); } -bool CParameterMgr::deleteConfiguration(const string& strDomain, const string& strConfiguration, string& strError) +bool CParameterMgr::deleteConfiguration(const string &strDomain, const string &strConfiguration, + string &strError) { + LOG_CONTEXT("Deleting configuration '" + strConfiguration + "' from domain '" + strDomain + + "'"); + // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail:" << strError; return false; } // Delegate to configurable domains - return getConfigurableDomains()->deleteConfiguration(strDomain, strConfiguration, strError); + return logResult( + getConfigurableDomains()->deleteConfiguration(strDomain, strConfiguration, strError), + strError); } -bool CParameterMgr::restoreConfiguration(const string& strDomain, const string& strConfiguration, list<string>& lstrError) +bool CParameterMgr::restoreConfiguration(const string &strDomain, const string &strConfiguration, + core::Results &errors) { string strError; + LOG_CONTEXT("Restoring domain '" + strDomain + "''s configuration '" + strConfiguration + + "' to parameter blackboard"); // Check tuning mode if (!checkTuningModeOn(strError)) { - lstrError.push_back(strError); + errors.push_back(strError); + warning() << "Fail:" << strError; return false; } // Delegate to configurable domains - return getConstConfigurableDomains()->restoreConfiguration(strDomain, strConfiguration, _pMainParameterBlackboard, _bAutoSyncOn, lstrError); + return logResult( + getConstConfigurableDomains()->restoreConfiguration( + strDomain, strConfiguration, _pMainParameterBlackboard, _bAutoSyncOn, errors), + strError); } -bool CParameterMgr::saveConfiguration(const string& strDomain, const string& strConfiguration, string& strError) +bool CParameterMgr::saveConfiguration(const string &strDomain, const string &strConfiguration, + string &strError) { + LOG_CONTEXT("Saving domain '" + strDomain + "' configuration '" + strConfiguration + + "' from parameter blackboard"); // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail:" << strError; return false; } // Delegate to configurable domains - return getConfigurableDomains()->saveConfiguration(strDomain, strConfiguration, _pMainParameterBlackboard, strError); + return logResult(getConfigurableDomains()->saveConfiguration( + strDomain, strConfiguration, _pMainParameterBlackboard, strError), + strError); } // Configurable element - domain association -bool CParameterMgr::addConfigurableElementToDomain(const string& strDomain, const string& strConfigurableElementPath, string& strError) +bool CParameterMgr::addConfigurableElementToDomain(const string &strDomain, + const string &strConfigurableElementPath, + string &strError) { + LOG_CONTEXT("Adding configurable element '" + strConfigurableElementPath + "' to domain '" + + strDomain + "'"); // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail: " << strError; return false; } CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(strConfigurableElementPath, &pLocatedElement, strError)) { + warning() << "Fail: " << strError; return false; } // Convert element - CConfigurableElement* pConfigurableElement = static_cast<CConfigurableElement*>(pLocatedElement); + CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(pLocatedElement); // Delegate - return getConfigurableDomains()->addConfigurableElementToDomain(strDomain, pConfigurableElement, _pMainParameterBlackboard, strError); + core::Results infos; + bool isSuccess = getConfigurableDomains()->addConfigurableElementToDomain( + strDomain, pConfigurableElement, _pMainParameterBlackboard, infos); + + if (isSuccess) { + info() << infos; + } else { + warning() << infos; + } + + strError = utility::asString(infos); + return isSuccess; } -bool CParameterMgr::removeConfigurableElementFromDomain(const string& strDomain, const string& strConfigurableElementPath, string& strError) +bool CParameterMgr::removeConfigurableElementFromDomain(const string &strDomain, + const string &strConfigurableElementPath, + string &strError) { + LOG_CONTEXT("Removing configurable element '" + strConfigurableElementPath + "' from domain '" + + strDomain + "'"); + // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail:" << strError; return false; } CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(strConfigurableElementPath, &pLocatedElement, strError)) { + warning() << "Fail:" << strError; return false; } // Convert element - CConfigurableElement* pConfigurableElement = static_cast<CConfigurableElement*>(pLocatedElement); + CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(pLocatedElement); // Delegate - return getConfigurableDomains()->removeConfigurableElementFromDomain(strDomain, pConfigurableElement, strError); + return logResult(getConfigurableDomains()->removeConfigurableElementFromDomain( + strDomain, pConfigurableElement, strError), + strError); } -bool CParameterMgr::split(const string& strDomain, const string& strConfigurableElementPath, string& strError) +bool CParameterMgr::split(const string &strDomain, const string &strConfigurableElementPath, + string &strError) { + LOG_CONTEXT("Splitting configurable element '" + strConfigurableElementPath + "' domain '" + + strDomain + "'"); // Check tuning mode if (!checkTuningModeOn(strError)) { + warning() << "Fail:" << strError; return false; } CElementLocator elementLocator(getSystemClass()); - CElement* pLocatedElement = NULL; + CElement *pLocatedElement = NULL; if (!elementLocator.locate(strConfigurableElementPath, &pLocatedElement, strError)) { + warning() << "Fail: " << strError; return false; } // Convert element - CConfigurableElement* pConfigurableElement = static_cast<CConfigurableElement*>(pLocatedElement); + CConfigurableElement *pConfigurableElement = + static_cast<CConfigurableElement *>(pLocatedElement); // Delegate - return getConfigurableDomains()->split(strDomain, pConfigurableElement, strError); + core::Results infos; + bool isSuccess = getConfigurableDomains()->split(strDomain, pConfigurableElement, infos); + + if (isSuccess) { + info() << infos; + } else { + warning() << infos; + } + + strError = utility::asString(infos); + return isSuccess; } -bool CParameterMgr::setElementSequence(const string& strDomain, const string& strConfiguration, - const std::vector<string>& astrNewElementSequence, - string& strError) +bool CParameterMgr::setElementSequence(const string &strDomain, const string &strConfiguration, + const std::vector<string> &astrNewElementSequence, + string &strError) { // Check tuning mode if (!checkTuningModeOn(strError)) { @@ -2186,31 +2512,31 @@ bool CParameterMgr::setElementSequence(const string& strDomain, const string& st } return getConfigurableDomains()->setElementSequence(strDomain, strConfiguration, - astrNewElementSequence, strError); + astrNewElementSequence, strError); } -bool CParameterMgr::getApplicationRule(const string& strDomain, const string& strConfiguration, - string& strResult) +bool CParameterMgr::getApplicationRule(const string &strDomain, const string &strConfiguration, + string &strResult) { return getConfigurableDomains()->getApplicationRule(strDomain, strConfiguration, strResult); } -bool CParameterMgr::setApplicationRule(const string& strDomain, const string& strConfiguration, - const string& strApplicationRule, string& strError) +bool CParameterMgr::setApplicationRule(const string &strDomain, const string &strConfiguration, + const string &strApplicationRule, string &strError) { - return getConfigurableDomains()->setApplicationRule(strDomain, strConfiguration, - strApplicationRule, getConstSelectionCriteria()->getSelectionCriteriaDefinition(), - strError); + return getConfigurableDomains()->setApplicationRule( + strDomain, strConfiguration, strApplicationRule, + getConstSelectionCriteria()->getSelectionCriteriaDefinition(), strError); } -bool CParameterMgr::clearApplicationRule(const string& strDomain, const string& strConfiguration, - string& strError) +bool CParameterMgr::clearApplicationRule(const string &strDomain, const string &strConfiguration, + string &strError) { return getConfigurableDomains()->clearApplicationRule(strDomain, strConfiguration, strError); } -bool CParameterMgr::importDomainsXml(const string& xmlSource, bool withSettings, - bool fromFile, string& errorMsg) +bool CParameterMgr::importDomainsXml(const string &xmlSource, bool withSettings, bool fromFile, + string &errorMsg) { // Check tuning mode if (!checkTuningModeOn(errorMsg)) { @@ -2218,11 +2544,11 @@ bool CParameterMgr::importDomainsXml(const string& xmlSource, bool withSettings, return false; } - CAutoLog autoLog(this, string("Importing domains from ") + - (fromFile ? ("\"" + xmlSource + "\"") : "a user-provided buffer")); + LOG_CONTEXT("Importing domains from " + + (fromFile ? ("\"" + xmlSource + "\"") : "a user-provided buffer")); // Root element - CConfigurableDomains* pConfigurableDomains = getConfigurableDomains(); + CConfigurableDomains *pConfigurableDomains = getConfigurableDomains(); bool importSuccess = wrapLegacyXmlImport(xmlSource, fromFile, withSettings, *pConfigurableDomains, "SystemClassName", errorMsg); @@ -2236,20 +2562,20 @@ bool CParameterMgr::importDomainsXml(const string& xmlSource, bool withSettings, return importSuccess; } -bool CParameterMgr::importSingleDomainXml(const string& xmlSource, bool overwrite, - bool withSettings, bool fromFile, string& errorMsg) +bool CParameterMgr::importSingleDomainXml(const string &xmlSource, bool overwrite, + bool withSettings, bool fromFile, string &errorMsg) { if (!checkTuningModeOn(errorMsg)) { return false; } - CAutoLog autoLog(this, string("Importing a single domain from ") + - (fromFile ? ("\"" + xmlSource + "\"") : "a user-provided buffer")); + LOG_CONTEXT("Importing a single domain from " + + (fromFile ? ('"' + xmlSource + '"') : "a user-provided buffer")); // We initialize the domain with an empty name but since we have set the isDomainStandalone // context, the name will be retrieved during de-serialization - std::auto_ptr<CConfigurableDomain> standaloneDomain(new CConfigurableDomain()); + auto standaloneDomain = utility::make_unique<CConfigurableDomain>(); if (!wrapLegacyXmlImport(xmlSource, fromFile, withSettings, *standaloneDomain, "", errorMsg)) { return false; @@ -2264,44 +2590,39 @@ bool CParameterMgr::importSingleDomainXml(const string& xmlSource, bool overwrit return true; } -bool CParameterMgr::wrapLegacyXmlImport(const string& xmlSource, bool fromFile, - bool withSettings, CElement& element, - const string& nameAttributeName, string& errorMsg) +bool CParameterMgr::wrapLegacyXmlImport(const string &xmlSource, bool fromFile, bool withSettings, + CElement &element, const string &nameAttributeName, + string &errorMsg) { CXmlDomainImportContext xmlDomainImportContext(errorMsg, withSettings, *getSystemClass()); // Selection criteria definition for rule creation xmlDomainImportContext.setSelectionCriteriaDefinition( - getConstSelectionCriteria()->getSelectionCriteriaDefinition()); + getConstSelectionCriteria()->getSelectionCriteriaDefinition()); // It doesn't make sense to resolve XIncludes on an imported file because // we can't reliably decide of a "base url" - _xmlDoc *doc = CXmlDocSource::mkXmlDoc(xmlSource, fromFile, false, errorMsg); + _xmlDoc *doc = CXmlDocSource::mkXmlDoc(xmlSource, fromFile, false, xmlDomainImportContext); if (doc == NULL) { return false; } - return xmlParse(xmlDomainImportContext, &element, doc, "", EParameterConfigurationLibrary, nameAttributeName); + return xmlParse(xmlDomainImportContext, &element, doc, "", EParameterConfigurationLibrary, true, + nameAttributeName); } -bool CParameterMgr::serializeElement(std::ostream& output, - CXmlSerializingContext& xmlSerializingContext, - const CElement& element) const +bool CParameterMgr::serializeElement(std::ostream &output, + CXmlSerializingContext &xmlSerializingContext, + const CElement &element) const { if (!output.good()) { xmlSerializingContext.setError("Can't write XML: the output is in a bad state."); return false; } - // Get Schema file associated to root element - string xmlSchemaFilePath = _strSchemaFolderLocation + "/" + - element.getKind() + ".xsd"; - // Use a doc source by loading data from instantiated Configurable Domains CXmlMemoryDocSource memorySource(&element, _bValidateSchemasOnStart, - element.getKind(), - xmlSchemaFilePath, - "parameter-framework", + element.getXmlElementName(), "parameter-framework", getVersion()); // Use a doc sink to write the doc data in a stream @@ -2312,25 +2633,25 @@ bool CParameterMgr::serializeElement(std::ostream& output, return processSuccess; } -bool CParameterMgr::exportDomainsXml(string& xmlDest, bool withSettings, bool toFile, - string& errorMsg) const +bool CParameterMgr::exportDomainsXml(string &xmlDest, bool withSettings, bool toFile, + string &errorMsg) const { - CAutoLog autoLog(this, string("Exporting domains to ") + - (toFile ? ("\"" + xmlDest + "\"") : " a user-provided buffer")); + LOG_CONTEXT("Exporting domains to " + + (toFile ? ('"' + xmlDest + '"') : "a user-provided buffer")); - const CConfigurableDomains* configurableDomains = getConstConfigurableDomains(); + const CConfigurableDomains *configurableDomains = getConstConfigurableDomains(); return wrapLegacyXmlExport(xmlDest, toFile, withSettings, *configurableDomains, errorMsg); } -bool CParameterMgr::exportSingleDomainXml(string& xmlDest, const string& domainName, - bool withSettings, bool toFile, string& errorMsg) const +bool CParameterMgr::exportSingleDomainXml(string &xmlDest, const string &domainName, + bool withSettings, bool toFile, string &errorMsg) const { - CAutoLog autoLog(this, string("Exporting single domain '") + domainName + "' to " + - (toFile ? ("\"" + xmlDest + "\"") : " a user-provided buffer")); + LOG_CONTEXT("Exporting single domain '" + domainName + "' to " + + (toFile ? ('"' + xmlDest + '"') : "a user-provided buffer")); // Element to be serialized - const CConfigurableDomain* requestedDomain = + const CConfigurableDomain *requestedDomain = getConstConfigurableDomains()->findConfigurableDomain(domainName, errorMsg); if (requestedDomain == NULL) { @@ -2340,8 +2661,8 @@ bool CParameterMgr::exportSingleDomainXml(string& xmlDest, const string& domainN return wrapLegacyXmlExport(xmlDest, toFile, withSettings, *requestedDomain, errorMsg); } -bool CParameterMgr::wrapLegacyXmlExport(string& xmlDest, bool toFile, bool withSettings, - const CElement& element, string& errorMsg) const +bool CParameterMgr::wrapLegacyXmlExport(string &xmlDest, bool toFile, bool withSettings, + const CElement &element, string &errorMsg) const { CXmlDomainExportContext context(errorMsg, withSettings, _bValueSpaceIsRaw, _bOutputRawFormatIsHex); @@ -2353,23 +2674,28 @@ bool CParameterMgr::wrapLegacyXmlExport(string& xmlDest, bool toFile, bool withS } } -bool CParameterMgr::wrapLegacyXmlExportToFile(string& xmlDest, - const CElement& element, +bool CParameterMgr::wrapLegacyXmlExportToFile(string &xmlDest, const CElement &element, CXmlDomainExportContext &context) const { - std::ofstream output(xmlDest.c_str()); + try { + std::ofstream output; + // Force stream to throw instead of using fail/bad bit + // in order to retreive an error message. + output.exceptions(~std::ifstream::goodbit); - if (output.fail()) { - context.setError("Failed to open \"" + xmlDest + "\" for writing."); - return false; - } + output.open(xmlDest.c_str()); + bool status = serializeElement(output, context, element); + output.close(); // Explicit close to detect errors - return serializeElement(output, context, element); + return status; + } catch (std::ofstream::failure &e) { + context.setError("Failed to open \"" + xmlDest + "\" for writing: " + e.what()); + return false; + } } -bool CParameterMgr::wrapLegacyXmlExportToString(string& xmlDest, - const CElement& element, +bool CParameterMgr::wrapLegacyXmlExportToString(string &xmlDest, const CElement &element, CXmlDomainExportContext &context) const { std::ostringstream output; @@ -2383,35 +2709,8 @@ bool CParameterMgr::wrapLegacyXmlExportToString(string& xmlDest, return true; } -// Binary Import/Export -bool CParameterMgr::importDomainsBinary(const string& strFileName, string& strError) -{ - // Check tuning mode - if (!checkTuningModeOn(strError)) { - - return false; - } - - CAutoLog autoLog(this, string("Importing domains from binary file \"") + strFileName + "\""); - // Root element - CConfigurableDomains* pConfigurableDomains = getConfigurableDomains(); - - // Serialize in - return pConfigurableDomains->serializeSettings(strFileName, false, _uiStructureChecksum, strError); -} - -bool CParameterMgr::exportDomainsBinary(const string& strFileName, string& strError) -{ - CAutoLog autoLog(this, string("Exporting domains to binary file \"") + strFileName + "\""); - // Root element - CConfigurableDomains* pConfigurableDomains = getConfigurableDomains(); - - // Serialize out - return pConfigurableDomains->serializeSettings(strFileName, true, _uiStructureChecksum, strError); -} - // For tuning, check we're in tuning mode -bool CParameterMgr::checkTuningModeOn(string& strError) const +bool CParameterMgr::checkTuningModeOn(string &strError) const { // Tuning Mode on? if (!_bTuningModeIsOn) { @@ -2424,13 +2723,13 @@ bool CParameterMgr::checkTuningModeOn(string& strError) const } // Tuning mutex dynamic parameter handling -pthread_mutex_t* CParameterMgr::getBlackboardMutex() +std::mutex &CParameterMgr::getBlackboardMutex() { - return &_blackboardMutex; + return _blackboardMutex; } // Blackboard reference (dynamic parameter handling) -CParameterBlackboard* CParameterMgr::getParameterBlackboard() +CParameterBlackboard *CParameterMgr::getParameterBlackboard() { return _pMainParameterBlackboard; } @@ -2439,46 +2738,76 @@ CParameterBlackboard* CParameterMgr::getParameterBlackboard() void CParameterMgr::feedElementLibraries() { // Global Configuration handling - CElementLibrary* pFrameworkConfigurationLibrary = new CElementLibrary; - - pFrameworkConfigurationLibrary->addElementBuilder("ParameterFrameworkConfiguration", new TElementBuilderTemplate<CParameterFrameworkConfiguration>()); - pFrameworkConfigurationLibrary->addElementBuilder("SubsystemPlugins", new TKindElementBuilderTemplate<CSubsystemPlugins>()); - pFrameworkConfigurationLibrary->addElementBuilder("Location", new TKindElementBuilderTemplate<CPluginLocation>()); - pFrameworkConfigurationLibrary->addElementBuilder("StructureDescriptionFileLocation", new TKindElementBuilderTemplate<CFrameworkConfigurationLocation>()); - pFrameworkConfigurationLibrary->addElementBuilder("SettingsConfiguration", new TKindElementBuilderTemplate<CFrameworkConfigurationGroup>()); - pFrameworkConfigurationLibrary->addElementBuilder("ConfigurableDomainsFileLocation", new TKindElementBuilderTemplate<CFrameworkConfigurationLocation>()); - pFrameworkConfigurationLibrary->addElementBuilder("BinarySettingsFileLocation", new TKindElementBuilderTemplate<CFrameworkConfigurationLocation>()); + CElementLibrary *pFrameworkConfigurationLibrary = new CElementLibrary; + + pFrameworkConfigurationLibrary->addElementBuilder( + "ParameterFrameworkConfiguration", + new TElementBuilderTemplate<CParameterFrameworkConfiguration>()); + pFrameworkConfigurationLibrary->addElementBuilder( + "SubsystemPlugins", new TKindElementBuilderTemplate<CSubsystemPlugins>()); + pFrameworkConfigurationLibrary->addElementBuilder( + "Location", new TKindElementBuilderTemplate<CPluginLocation>()); + pFrameworkConfigurationLibrary->addElementBuilder( + "StructureDescriptionFileLocation", + new TKindElementBuilderTemplate<CFrameworkConfigurationLocation>()); + pFrameworkConfigurationLibrary->addElementBuilder( + "SettingsConfiguration", new TKindElementBuilderTemplate<CFrameworkConfigurationGroup>()); + pFrameworkConfigurationLibrary->addElementBuilder( + "ConfigurableDomainsFileLocation", + new TKindElementBuilderTemplate<CFrameworkConfigurationLocation>()); _pElementLibrarySet->addElementLibrary(pFrameworkConfigurationLibrary); // Parameter creation - CElementLibrary* pParameterCreationLibrary = new CElementLibrary; - - pParameterCreationLibrary->addElementBuilder("Subsystem", new CSubsystemElementBuilder(getSystemClass()->getSubsystemLibrary())); - pParameterCreationLibrary->addElementBuilder("ComponentType", new TNamedElementBuilderTemplate<CComponentType>()); - pParameterCreationLibrary->addElementBuilder("Component", new TNamedElementBuilderTemplate<CComponentInstance>()); - pParameterCreationLibrary->addElementBuilder("BitParameter", new TNamedElementBuilderTemplate<CBitParameterType>()); - pParameterCreationLibrary->addElementBuilder("BitParameterBlock", new TNamedElementBuilderTemplate<CBitParameterBlockType>()); - pParameterCreationLibrary->addElementBuilder("StringParameter", new TNamedElementBuilderTemplate<CStringParameterType>()); - pParameterCreationLibrary->addElementBuilder("ParameterBlock", new TNamedElementBuilderTemplate<CParameterBlockType>()); - pParameterCreationLibrary->addElementBuilder("BooleanParameter", new TNamedElementBuilderTemplate<CBooleanParameterType>()); - pParameterCreationLibrary->addElementBuilder("IntegerParameter", new TNamedElementBuilderTemplate<CIntegerParameterType>()); - pParameterCreationLibrary->addElementBuilder("LinearAdaptation", new TElementBuilderTemplate<CLinearParameterAdaptation>()); - pParameterCreationLibrary->addElementBuilder("LogarithmicAdaptation", new TElementBuilderTemplate<CLogarithmicParameterAdaptation>()); - pParameterCreationLibrary->addElementBuilder("EnumParameter", new TNamedElementBuilderTemplate<CEnumParameterType>()); - pParameterCreationLibrary->addElementBuilder("ValuePair", new TElementBuilderTemplate<CEnumValuePair>()); - pParameterCreationLibrary->addElementBuilder("FixedPointParameter", new TNamedElementBuilderTemplate<CFixedPointParameterType>()); - pParameterCreationLibrary->addElementBuilder("SubsystemInclude", new CFileIncluderElementBuilder(_bValidateSchemasOnStart)); + CElementLibrary *pParameterCreationLibrary = new CElementLibrary; + + pParameterCreationLibrary->addElementBuilder( + "Subsystem", new CSubsystemElementBuilder(getSystemClass()->getSubsystemLibrary())); + pParameterCreationLibrary->addElementBuilder( + "ComponentType", new TNamedElementBuilderTemplate<CComponentType>()); + pParameterCreationLibrary->addElementBuilder( + "Component", new TNamedElementBuilderTemplate<CComponentInstance>()); + pParameterCreationLibrary->addElementBuilder( + "BitParameter", new TNamedElementBuilderTemplate<CBitParameterType>()); + pParameterCreationLibrary->addElementBuilder( + "BitParameterBlock", new TNamedElementBuilderTemplate<CBitParameterBlockType>()); + pParameterCreationLibrary->addElementBuilder( + "StringParameter", new TNamedElementBuilderTemplate<CStringParameterType>()); + pParameterCreationLibrary->addElementBuilder( + "ParameterBlock", new TNamedElementBuilderTemplate<CParameterBlockType>()); + pParameterCreationLibrary->addElementBuilder( + "BooleanParameter", new TNamedElementBuilderTemplate<CBooleanParameterType>()); + pParameterCreationLibrary->addElementBuilder( + "IntegerParameter", new TNamedElementBuilderTemplate<CIntegerParameterType>()); + pParameterCreationLibrary->addElementBuilder( + "LinearAdaptation", new TElementBuilderTemplate<CLinearParameterAdaptation>()); + pParameterCreationLibrary->addElementBuilder( + "LogarithmicAdaptation", new TElementBuilderTemplate<CLogarithmicParameterAdaptation>()); + pParameterCreationLibrary->addElementBuilder( + "EnumParameter", new TNamedElementBuilderTemplate<CEnumParameterType>()); + pParameterCreationLibrary->addElementBuilder("ValuePair", + new TElementBuilderTemplate<CEnumValuePair>()); + pParameterCreationLibrary->addElementBuilder( + "FixedPointParameter", new TNamedElementBuilderTemplate<CFixedPointParameterType>()); + pParameterCreationLibrary->addElementBuilder( + "FloatingPointParameter", new TNamedElementBuilderTemplate<CFloatingPointParameterType>); + pParameterCreationLibrary->addElementBuilder( + "SubsystemInclude", + new CFileIncluderElementBuilder(_bValidateSchemasOnStart, getSchemaUri())); _pElementLibrarySet->addElementLibrary(pParameterCreationLibrary); // Parameter Configuration Domains creation - CElementLibrary* pParameterConfigurationLibrary = new CElementLibrary; + CElementLibrary *pParameterConfigurationLibrary = new CElementLibrary; - pParameterConfigurationLibrary->addElementBuilder("ConfigurableDomain", new TElementBuilderTemplate<CConfigurableDomain>()); - pParameterConfigurationLibrary->addElementBuilder("Configuration", new TNamedElementBuilderTemplate<CDomainConfiguration>()); - pParameterConfigurationLibrary->addElementBuilder("CompoundRule", new TElementBuilderTemplate<CCompoundRule>()); - pParameterConfigurationLibrary->addElementBuilder("SelectionCriterionRule", new TElementBuilderTemplate<CSelectionCriterionRule>()); + pParameterConfigurationLibrary->addElementBuilder( + "ConfigurableDomain", new TElementBuilderTemplate<CConfigurableDomain>()); + pParameterConfigurationLibrary->addElementBuilder( + "Configuration", new TNamedElementBuilderTemplate<CDomainConfiguration>()); + pParameterConfigurationLibrary->addElementBuilder("CompoundRule", + new TElementBuilderTemplate<CCompoundRule>()); + pParameterConfigurationLibrary->addElementBuilder( + "SelectionCriterionRule", new TElementBuilderTemplate<CSelectionCriterionRule>()); _pElementLibrarySet->addElementLibrary(pParameterConfigurationLibrary); } @@ -2493,139 +2822,135 @@ void CParameterMgr::setForceNoRemoteInterface(bool bForceNoRemoteInterface) _bForceNoRemoteInterface = bForceNoRemoteInterface; } -// Remote Processor Server connection handling -bool CParameterMgr::handleRemoteProcessingInterface(string& strError) +CParameterMgr::CommandHandler CParameterMgr::createCommandHandler() { - CAutoLog autoLog(this, "Handling remote processing interface"); + auto commandHandler = utility::make_unique<CCommandHandler>(this); - if (_bForceNoRemoteInterface) { - // The user requested not to start the remote interface - return true; + // Add command parsers + for (const auto &remoteCommandParserItem : gastRemoteCommandParserItems) { + commandHandler->addCommandParser( + remoteCommandParserItem._pcCommandName, remoteCommandParserItem._pfnParser, + remoteCommandParserItem._minArgumentCount, remoteCommandParserItem._pcHelp, + remoteCommandParserItem._pcDescription); } - // Start server if tuning allowed - if (getConstFrameworkConfiguration()->isTuningAllowed()) { - - log_info("Loading remote processor library"); - - // Load library - _pvLibRemoteProcessorHandle = dlopen("libremote-processor.so", RTLD_NOW); - - if (!_pvLibRemoteProcessorHandle) { - - // Return error - const char* pcError = dlerror(); - - if (pcError) { - - strError = pcError; - } else { - - strError = "Unable to load libremote-processor.so library"; - } - - return false; - } - - CreateRemoteProcessorServer pfnCreateRemoteProcessorServer = (CreateRemoteProcessorServer)dlsym(_pvLibRemoteProcessorHandle, "createRemoteProcessorServer"); - - if (!pfnCreateRemoteProcessorServer) { + return commandHandler; +} - strError = "libremote-process.so does not contain createRemoteProcessorServer symbol."; +bool CParameterMgr::isRemoteInterfaceRequired() +{ + // The remote interface should only be started if the client didn't + // explicitly forbid it and if the configuration file allows it. + return (not _bForceNoRemoteInterface) and getConstFrameworkConfiguration()->isTuningAllowed(); +} - return false; - } +// Remote Processor Server connection handling +bool CParameterMgr::handleRemoteProcessingInterface(string &strError) +{ + LOG_CONTEXT("Handling remote processing interface"); - // Create server - _pRemoteProcessorServer = pfnCreateRemoteProcessorServer(getConstFrameworkConfiguration()->getServerPort(), _pCommandHandler); + if (not isRemoteInterfaceRequired()) { + return true; + } - log_info("Starting remote processor server on port %d", getConstFrameworkConfiguration()->getServerPort()); - // Start - if (!_pRemoteProcessorServer->start(strError)) { + auto port = getConstFrameworkConfiguration()->getServerPort(); - ostringstream oss; - oss << "ParameterMgr: Unable to start remote processor server on port " - << getConstFrameworkConfiguration()->getServerPort(); - strError = oss.str() + ": " + strError; + try { + // The ownership of remoteComandHandler is given to Bg remote processor server. + _pRemoteProcessorServer = new BackgroundRemoteProcessorServer(port, createCommandHandler()); + } catch (std::runtime_error &e) { + strError = string("ParameterMgr: Unable to create Remote Processor Server: ") + e.what(); + return false; + } - return false; - } + if (_pRemoteProcessorServer == NULL) { + strError = "ParameterMgr: Unable to create Remote Processor Server"; + return false; } + if (!_pRemoteProcessorServer->start(strError)) { + ostringstream oss; + oss << "ParameterMgr: Unable to start remote processor server on port " << port; + strError = oss.str() + ": " + strError; + return false; + } + info() << "Remote Processor Server started on port " << port; return true; } // Children typwise access -CParameterFrameworkConfiguration* CParameterMgr::getFrameworkConfiguration() +CParameterFrameworkConfiguration *CParameterMgr::getFrameworkConfiguration() { - return static_cast<CParameterFrameworkConfiguration*>(getChild(EFrameworkConfiguration)); + return static_cast<CParameterFrameworkConfiguration *>(getChild(EFrameworkConfiguration)); } -const CParameterFrameworkConfiguration* CParameterMgr::getConstFrameworkConfiguration() +const CParameterFrameworkConfiguration *CParameterMgr::getConstFrameworkConfiguration() { return getFrameworkConfiguration(); } -CSelectionCriteria* CParameterMgr::getSelectionCriteria() +CSelectionCriteria *CParameterMgr::getSelectionCriteria() { - return static_cast<CSelectionCriteria*>(getChild(ESelectionCriteria)); + return static_cast<CSelectionCriteria *>(getChild(ESelectionCriteria)); } -const CSelectionCriteria* CParameterMgr::getConstSelectionCriteria() +const CSelectionCriteria *CParameterMgr::getConstSelectionCriteria() { - return static_cast<const CSelectionCriteria*>(getChild(ESelectionCriteria)); + return static_cast<const CSelectionCriteria *>(getChild(ESelectionCriteria)); } -CSystemClass* CParameterMgr::getSystemClass() +CSystemClass *CParameterMgr::getSystemClass() { - return static_cast<CSystemClass*>(getChild(ESystemClass)); + return static_cast<CSystemClass *>(getChild(ESystemClass)); } -const CSystemClass* CParameterMgr::getConstSystemClass() const +const CSystemClass *CParameterMgr::getConstSystemClass() const { - return static_cast<const CSystemClass*>(getChild(ESystemClass)); + return static_cast<const CSystemClass *>(getChild(ESystemClass)); } // Configurable Domains -CConfigurableDomains* CParameterMgr::getConfigurableDomains() +CConfigurableDomains *CParameterMgr::getConfigurableDomains() { - return static_cast<CConfigurableDomains*>(getChild(EConfigurableDomains)); + return static_cast<CConfigurableDomains *>(getChild(EConfigurableDomains)); } -const CConfigurableDomains* CParameterMgr::getConstConfigurableDomains() +const CConfigurableDomains *CParameterMgr::getConstConfigurableDomains() { - return static_cast<const CConfigurableDomains*>(getChild(EConfigurableDomains)); + return static_cast<const CConfigurableDomains *>(getChild(EConfigurableDomains)); } -const CConfigurableDomains* CParameterMgr::getConstConfigurableDomains() const +const CConfigurableDomains *CParameterMgr::getConstConfigurableDomains() const { - return static_cast<const CConfigurableDomains*>(getChild(EConfigurableDomains)); + return static_cast<const CConfigurableDomains *>(getChild(EConfigurableDomains)); } // Apply configurations void CParameterMgr::doApplyConfigurations(bool bForce) { + LOG_CONTEXT("Applying configurations"); + CSyncerSet syncerSet; + core::Results infos; // Check subsystems that need resync - getSystemClass()->checkForSubsystemsToResync(syncerSet); + getSystemClass()->checkForSubsystemsToResync(syncerSet, infos); // Ensure application of currently selected configurations - getConfigurableDomains()->apply(_pMainParameterBlackboard, syncerSet, bForce); + getConfigurableDomains()->apply(_pMainParameterBlackboard, syncerSet, bForce, infos); + info() << infos; - // Reset the modified status of the current criteria to indicate that a new configuration has been applied + // Reset the modified status of the current criteria to indicate that a new configuration has + // been applied getSelectionCriteria()->resetModifiedStatus(); } // Export to XML string -bool CParameterMgr::exportElementToXMLString(const IXmlSource* pXmlSource, - const string& strRootElementType, - string& strResult) const +bool CParameterMgr::exportElementToXMLString(const IXmlSource *pXmlSource, + const string &strRootElementType, + CXmlSerializingContext &&xmlSerializingContext, + string &strResult) const { - string strError; - - CXmlSerializingContext xmlSerializingContext(strError); - // Use a doc source by loading data from instantiated Configurable Domains CXmlMemoryDocSource memorySource(pXmlSource, false, strRootElementType); @@ -2636,11 +2961,30 @@ bool CParameterMgr::exportElementToXMLString(const IXmlSource* pXmlSource, // Do the export bool bProcessSuccess = streamSink.process(memorySource, xmlSerializingContext); - if (bProcessSuccess) { - strResult = output.str(); + strResult = output.str(); + + return bProcessSuccess; +} + +bool CParameterMgr::logResult(bool isSuccess, const std::string &result) +{ + std::string log = result.empty() ? "" : ": " + result; + + if (isSuccess) { + info() << "Success" << log; } else { - strResult = strError; + warning() << "Fail" << log; } - return bProcessSuccess; + return isSuccess; +} + +log::details::Info CParameterMgr::info() +{ + return _logger.info(); +} + +log::details::Warning CParameterMgr::warning() +{ + return _logger.warning(); } diff --git a/parameter/ParameterMgr.h b/parameter/ParameterMgr.h index cd2f664..784f55f 100644 --- a/parameter/ParameterMgr.h +++ b/parameter/ParameterMgr.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,10 +29,9 @@ */ #pragma once -#include <pthread.h> +#include <mutex> #include <map> #include <vector> -#include <list> #include "RemoteCommandHandlerTemplate.h" #include "PathNavigator.h" #include "SelectionCriterionType.h" @@ -41,17 +40,21 @@ #include "XmlDocSink.h" #include "XmlDocSource.h" #include "XmlDomainExportContext.h" +#include "Results.h" +#include "ElementHandle.h" +#include <log/LogWrapper.h> +#include <log/Context.h> -#include <string> -#include <ostream> #include <istream> +#include <memory> +#include <ostream> +#include <string> class CElementLibrarySet; class CSubsystemLibrary; class CSystemClass; class CSelectionCriteria; class CParameterFrameworkConfiguration; -class CSystemClassConfiguration; class CParameterBlackboard; class CConfigurableDomains; class IRemoteProcessorServerInterface; @@ -62,56 +65,28 @@ class CConfigurableElement; class CParameterMgr : private CElement { - enum ChildElement { + enum ChildElement + { EFrameworkConfiguration, ESelectionCriteria, ESystemClass, EConfigurableDomains }; - enum ElementLibrary { + enum ElementLibrary + { EFrameworkConfigurationLibrary, EParameterCreationLibrary, EParameterConfigurationLibrary }; - // Remote command parsers - typedef TRemoteCommandHandlerTemplate<CParameterMgr> CCommandHandler; - - typedef CCommandHandler::CommandStatus (CParameterMgr::*RemoteCommandParser)(const IRemoteCommand& remoteCommand, std::string& strResult); - - // Parser descriptions - struct SRemoteCommandParserItem - { - const char* _pcCommandName; - CParameterMgr::RemoteCommandParser _pfnParser; - uint32_t _uiMinArgumentCount; - const char* _pcHelp; - const char* _pcDescription; - }; - // Version - static const uint32_t guiEditionMajor = 2; - static const uint32_t guiEditionMinor = 6; - static const uint32_t guiRevision = 0; - // Parameter handle friendship - friend class CParameterHandle; -public: - // Logger interface - class ILogger - { - public: - virtual void log(bool bIsWarning, const std::string& strLog) = 0; - protected: - virtual ~ILogger() {} - }; + friend class ElementHandle; +public: // Construction - CParameterMgr(const std::string& strConfigurationFilePath); + CParameterMgr(const std::string &strConfigurationFilePath, core::log::ILogger &logger); virtual ~CParameterMgr(); - // Logging - void setLogger(ILogger* pLogger); - /** Load plugins, structures and settings from the config file given. * * @param[out] strError is a std::string describing the error if an error occurred @@ -119,19 +94,32 @@ public: * * @return true if no error occurred, false otherwise. */ - bool load(std::string& strError); + bool load(std::string &strError); + + // Remote command parsers + using CommandHandler = std::unique_ptr<TRemoteCommandHandlerTemplate<CParameterMgr>>; + + /** Create and return a command handler for this ParameterMgr instance + * + * @returns a Command Handler + */ + CommandHandler createCommandHandler(); // Selection Criteria - CSelectionCriterionType* createSelectionCriterionType(bool bIsInclusive); - CSelectionCriterion* createSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pSelectionCriterionType); + CSelectionCriterionType *createSelectionCriterionType(bool bIsInclusive); + CSelectionCriterion *createSelectionCriterion( + const std::string &strName, const CSelectionCriterionType *pSelectionCriterionType); // Selection criterion retrieval - CSelectionCriterion* getSelectionCriterion(const std::string& strName); + CSelectionCriterion *getSelectionCriterion(const std::string &strName); // Configuration application void applyConfigurations(); - /** - * Returns the CConfigurableElement corresponding to the path given in argument. + /** const version of getConfigurableElement */ + const CConfigurableElement *getConfigurableElement(const std::string &strPath, + std::string &strError) const; + + /** Returns the CConfigurableElement corresponding to the path given in argument. * * @param[in] strPath A std::string representing a path to an element. * @param[out] strError Error message @@ -139,10 +127,22 @@ public: * @return A const pointer to the corresponding CConfigurableElement. * On error, NULL is returned and the error is explained in strError. */ - const CConfigurableElement* getConfigurableElement(const std::string& strPath, - std::string& strError) const; + CConfigurableElement *getConfigurableElement(const std::string &strPath, std::string &strError); // Dynamic parameter handling - CParameterHandle* createParameterHandle(const std::string& strPath, std::string& strError); + CParameterHandle *createParameterHandle(const std::string &strPath, std::string &strError); + + /** Creates a handle to a configurable element. + * + * The returned object is owned by the client who is responsible to delete it. + * + * @param[in] path A string representing a path to a configurable element. + * @param[out] error On error: an human readable error message + * On success: undefined + * + * @return An element handle on success + * nullptr on error + */ + ElementHandle *createElementHandle(const std::string &path, std::string &error); /** Is the remote interface forcefully disabled ? */ @@ -178,19 +178,19 @@ public: * * @return failure on failed settings load policy state. */ - bool getFailureOnFailedSettingsLoad(); + bool getFailureOnFailedSettingsLoad() const; - /** Get the path to the directory containing the XML Schemas + /** Get the XML Schemas URI * - * @returns the directory containing the XML Schemas + * @returns the XML Schemas URI */ - const std::string& getSchemaFolderLocation() const; + const std::string &getSchemaUri() const; - /** Override the directory containing the XML Schemas + /** Override the XML Schemas URI * - * @param[in] strSchemaFolderLocation directory containing the XML Schemas + * @param[in] schemaUri XML Schemas URI */ - void setSchemaFolderLocation(const std::string& strSchemaFolderLocation); + void setSchemaUri(const std::string &schemaUri); /** Should .xml files be validated on start ? * @@ -211,8 +211,16 @@ public: bool getValidateSchemasOnStart() const; //////////// Tuning ///////////// - // Tuning mode - bool setTuningMode(bool bOn, std::string& strError); + /** + * Activate / deactivate the tuning mode. + * + * @param[in] bOn true if tuning mode activation is requested, false for desactivation + * @param[out] strError human readable error + * @return true if request is successful, false if the Parameter Manager is already in the mode + * requested or in case of error. + * If false, strError is set with the associated human readable error. + */ + bool setTuningMode(bool bOn, std::string &strError); bool tuningModeOn() const; // Current value space for user set/get value interpretation @@ -224,12 +232,13 @@ public: bool outputRawFormatIsHex(); // Automatic hardware synchronization control (during tuning session) - bool setAutoSync(bool bAutoSyncOn, std::string& strError); + bool setAutoSync(bool bAutoSyncOn, std::string &strError); bool autoSyncOn() const; - bool sync(std::string& strError); + bool sync(std::string &strError); // User set/get parameters - bool accessParameterValue(const std::string& strPath, std::string& strValue, bool bSet, std::string& strError); + bool accessParameterValue(const std::string &strPath, std::string &strValue, bool bSet, + std::string &strError); /** * Returns the element mapping corresponding to the path given in parameter. * @@ -238,42 +247,61 @@ public: * * @return true if a mapping was found for this element */ - bool getParameterMapping(const std::string& strPath, std::string& strValue) const; - bool accessConfigurationValue(const std::string &strDomain, const std::string &stConfiguration, const std::string& strPath, std::string& strValue, bool bSet, std::string& strError); + bool getParameterMapping(const std::string &strPath, std::string &strValue) const; + bool accessConfigurationValue(const std::string &strDomain, const std::string &stConfiguration, + const std::string &strPath, std::string &strValue, bool bSet, + std::string &strError); ////////// Configuration/Domains handling ////////////// // Creation/Deletion - bool createDomain(const std::string& strName, std::string& strError); - bool renameDomain(const std::string& strName, const std::string& strNewName, - std::string& strError); - bool deleteDomain(const std::string& strName, std::string& strError); - bool deleteAllDomains(std::string& strError); - bool setSequenceAwareness(const std::string& strName, bool bSequenceAware, - std::string& strResult); - bool getSequenceAwareness(const std::string& strName, bool& bSequenceAware, - std::string& strResult); - bool createConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool deleteConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool renameConfiguration(const std::string& strDomain, const std::string& strConfiguration, const std::string& strNewConfiguration, std::string& strError); - - // Save/Restore - bool restoreConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::list<std::string>& strError); - bool saveConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); + bool createDomain(const std::string &strName, std::string &strError); + bool renameDomain(const std::string &strName, const std::string &strNewName, + std::string &strError); + bool deleteDomain(const std::string &strName, std::string &strError); + bool deleteAllDomains(std::string &strError); + bool setSequenceAwareness(const std::string &strName, bool bSequenceAware, + std::string &strResult); + bool getSequenceAwareness(const std::string &strName, bool &bSequenceAware, + std::string &strResult); + bool createConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool deleteConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool renameConfiguration(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strNewConfiguration, std::string &strError); + + /** Restore a configuration + * + * @param[in] strDomain the domain name + * @param[in] strConfiguration the configuration name + * @param[out] errors errors encountered during restoration + * @return true if success false otherwise + */ + bool restoreConfiguration(const std::string &strDomain, const std::string &strConfiguration, + core::Results &errors); + + bool saveConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); // Configurable element - domain association - bool addConfigurableElementToDomain(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool removeConfigurableElementFromDomain(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool split(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool setElementSequence(const std::string& strDomain, const std::string& strConfiguration, - const std::vector<std::string>& astrNewElementSequence, - std::string& strError); - - bool getApplicationRule(const std::string& strDomain, const std::string& strConfiguration, - std::string& strResult); - bool setApplicationRule(const std::string& strDomain, const std::string& strConfiguration, - const std::string& strApplicationRule, std::string& strError); - bool clearApplicationRule(const std::string& strDomain, const std::string& strConfiguration, - std::string& strError); + bool addConfigurableElementToDomain(const std::string &strDomain, + const std::string &strConfigurableElementPath, + std::string &strError); + bool removeConfigurableElementFromDomain(const std::string &strDomain, + const std::string &strConfigurableElementPath, + std::string &strError); + bool split(const std::string &strDomain, const std::string &strConfigurableElementPath, + std::string &strError); + bool setElementSequence(const std::string &strDomain, const std::string &strConfiguration, + const std::vector<std::string> &astrNewElementSequence, + std::string &strError); + + bool getApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strResult); + bool setApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strApplicationRule, std::string &strError); + bool clearApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); /** * Method that imports Configurable Domains from an Xml source. @@ -287,8 +315,8 @@ public: * * @return false if any error occures */ - bool importDomainsXml(const std::string& xmlSource, bool withSettings, bool fromFile, - std::string& errorMsg); + bool importDomainsXml(const std::string &xmlSource, bool withSettings, bool fromFile, + std::string &errorMsg); /** * Method that imports a single Configurable Domain from an Xml source. @@ -304,8 +332,8 @@ public: * * @return false if any error occurs */ - bool importSingleDomainXml(const std::string& xmlSource, bool overwrite, bool withSettings, - bool fromFile, std::string& errorMsg); + bool importSingleDomainXml(const std::string &xmlSource, bool overwrite, bool withSettings, + bool fromFile, std::string &errorMsg); /** * Method that exports Configurable Domains to an Xml destination. @@ -319,8 +347,8 @@ public: * * @return false if any error occurs, true otherwise. */ - bool exportDomainsXml(std::string& xmlDest, bool withSettings, bool toFile, - std::string& errorMsg) const; + bool exportDomainsXml(std::string &xmlDest, bool withSettings, bool toFile, + std::string &errorMsg) const; /** * Method that exports a given Configurable Domain to an Xml destination. @@ -335,112 +363,192 @@ public: * * @return false if any error occurs, true otherwise. */ - bool exportSingleDomainXml(std::string& xmlDest, const std::string& domainName, - bool withSettings, bool toFile, std::string& errorMsg) const; - - // Binary Import/Export - bool importDomainsBinary(const std::string& strFileName, std::string& strError); - bool exportDomainsBinary(const std::string& strFileName, std::string& strError); + bool exportSingleDomainXml(std::string &xmlDest, const std::string &domainName, + bool withSettings, bool toFile, std::string &errorMsg) const; /** * Method that exports an Xml description of the passed element into a string * * @param[in] pXmlSource The source element to export * @param[in] strRootElementType The XML root element name of the exported instance document - * @param[out] strResult contains the xml description or the error description in case false is returned + * @param[in] xmlSerializingContext the context to use for serialization + * Is an rvalue as it must be destructed after this function + * call to set the error. + * Additionally, using it for an other serialization would + * override the error. + * @param[out] strResult contains the xml description or the error description in case false is + * returned * - * @return true for success, false if any error occurs during the creation of the xml description (validation or encoding) + * @return true for success, false if any error occurs during the creation of the xml + * description (validation or encoding) */ - bool exportElementToXMLString(const IXmlSource* pXmlSource, - const std::string& strRootElementType, - std::string& strResult) const; + bool exportElementToXMLString(const IXmlSource *pXmlSource, + const std::string &strRootElementType, + CXmlSerializingContext &&xmlSerializingContext, + std::string &strResult) const; // CElement virtual std::string getKind() const; private: - CParameterMgr(const CParameterMgr&); - CParameterMgr& operator=(const CParameterMgr&); + CParameterMgr(const CParameterMgr &); + CParameterMgr &operator=(const CParameterMgr &); // Init - virtual bool init(std::string& strError); - - // Logging (done by root) - virtual void doLog(bool bIsWarning, const std::string& strLog) const; - virtual void nestLog() const; - virtual void unnestLog() const; + virtual bool init(std::string &strError); // Version std::string getVersion() const; + // This using is here for internal reasons: CommandHandler is public and is + // a unique_ptr but we want the type that's inside. And for legacy reason + // because that's the original name before a rework; this directive avoids + // renaming a lot of stuff. + using CCommandHandler = CommandHandler::element_type; + using RemoteCommandParser = CCommandHandler::CommandStatus (CParameterMgr::*)( + const IRemoteCommand &remoteCommand, std::string &strResult); + + // Parser descriptions + struct SRemoteCommandParserItem + { + const char *_pcCommandName; + CParameterMgr::RemoteCommandParser _pfnParser; + size_t _minArgumentCount; + const char *_pcHelp; + const char *_pcDescription; + }; + ////////////////:: Remote command parsers /// Version - CCommandHandler::CommandStatus versionCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus versionCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Status - CCommandHandler::CommandStatus statusCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus statusCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Tuning Mode - CCommandHandler::CommandStatus setTuningModeCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getTuningModeCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus setTuningModeCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getTuningModeCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Value Space - CCommandHandler::CommandStatus setValueSpaceCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getValueSpaceCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus setValueSpaceCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getValueSpaceCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Output Raw Format - CCommandHandler::CommandStatus setOutputRawFormatCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getOutputRawFormatCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus setOutputRawFormatCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus getOutputRawFormatCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); /// Sync - CCommandHandler::CommandStatus setAutoSyncCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getAutoSyncCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus syncCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus setAutoSyncCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getAutoSyncCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus syncCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Criteria - CCommandHandler::CommandStatus listCriteriaCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus listCriteriaCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Domains - CCommandHandler::CommandStatus listDomainsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus createDomainCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus deleteDomainCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus deleteAllDomainsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus renameDomainCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus setSequenceAwarenessCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getSequenceAwarenessCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listDomainElementsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus addElementCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus removeElementCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus splitDomainCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus listDomainsCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus createDomainCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus deleteDomainCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus deleteAllDomainsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus renameDomainCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus setSequenceAwarenessCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus getSequenceAwarenessCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus listDomainElementsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus addElementCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus removeElementCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus splitDomainCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Configurations - CCommandHandler::CommandStatus listConfigurationsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus dumpDomainsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus createConfigurationCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus deleteConfigurationCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus renameConfigurationCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus saveConfigurationCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus restoreConfigurationCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus setElementSequenceCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getElementSequenceCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus setRuleCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus clearRuleCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getRuleCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus listConfigurationsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus dumpDomainsCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus createConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus deleteConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus renameConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus saveConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus restoreConfigurationCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus setElementSequenceCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus getElementSequenceCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus setRuleCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus clearRuleCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getRuleCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Elements/Parameters - CCommandHandler::CommandStatus listElementsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listParametersCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus dumpElementCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getElementSizeCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus showPropertiesCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getParameterCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus setParameterCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus getConfigurationParameterCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus setConfigurationParameterCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listBelongingDomainsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listAssociatedDomainsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus showMappingCommandProcess(const IRemoteCommand& remoteCommand, - std::string& strResult); + CCommandHandler::CommandStatus listElementsCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus listParametersCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getElementStructureXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus getElementBytesCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus setElementBytesCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus getElementXMLCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus setElementXMLCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus dumpElementCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getElementSizeCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus showPropertiesCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getParameterCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus setParameterCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); + CCommandHandler::CommandStatus getConfigurationParameterCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus setConfigurationParameterCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus listBelongingDomainsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus listAssociatedDomainsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus showMappingCommandProcess(const IRemoteCommand &remoteCommand, + std::string &strResult); /// Browse - CCommandHandler::CommandStatus listAssociatedElementsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listConflictingElementsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus listRogueElementsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus listAssociatedElementsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus listConflictingElementsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus listRogueElementsCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); /// Settings Import/Export - CCommandHandler::CommandStatus exportDomainsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus importDomainsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus exportDomainsWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus importDomainsWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus exportDomainsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus importDomainsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus exportDomainsWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); + CCommandHandler::CommandStatus importDomainsWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); /** * Command handler method for exportDomainWithSettingsXML command. * @@ -450,10 +558,10 @@ private: * @return CCommandHandler::ESucceeded if command succeeded or CCommandHandler::EFailed * in the other case */ - CCommandHandler::CommandStatus exportDomainWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& result); - CCommandHandler::CommandStatus importDomainWithSettingsXMLCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus exportSettingsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); - CCommandHandler::CommandStatus importSettingsCommandProcess(const IRemoteCommand& remoteCommand, std::string& strResult); + CCommandHandler::CommandStatus exportDomainWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &result); + CCommandHandler::CommandStatus importDomainWithSettingsXMLCommandProcess( + const IRemoteCommand &remoteCommand, std::string &strResult); /** * Command handler method for getDomainsWithSettings command. @@ -465,7 +573,7 @@ private: * in the other case */ CCommandHandler::CommandStatus getDomainsWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, std::string& strResult); + const IRemoteCommand &remoteCommand, std::string &strResult); /** * Command handler method for getDomainWithSettings command. @@ -477,7 +585,7 @@ private: * in the other case */ CCommandHandler::CommandStatus getDomainWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, std::string& strResult); + const IRemoteCommand &remoteCommand, std::string &strResult); /** * Command handler method for setDomainsWithSettings command. @@ -489,7 +597,7 @@ private: * in the other case */ CCommandHandler::CommandStatus setDomainsWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, std::string& strResult); + const IRemoteCommand &remoteCommand, std::string &strResult); /** * Command handler method for setDomainWithSettings command. @@ -501,7 +609,7 @@ private: * in the other case */ CCommandHandler::CommandStatus setDomainWithSettingsXMLCommandProcess( - const IRemoteCommand& remoteCommand, std::string& result); + const IRemoteCommand &remoteCommand, std::string &result); /** * Command handler method for getSystemClass command. @@ -513,49 +621,104 @@ private: * in the other case */ CCommandHandler::CommandStatus getSystemClassXMLCommandProcess( - const IRemoteCommand& remoteCommand, std::string& strResult); + const IRemoteCommand &remoteCommand, std::string &strResult); // Max command usage length, use for formatting void setMaxCommandUsageLength(); // For tuning, check we're in tuning mode - bool checkTuningModeOn(std::string& strError) const; + bool checkTuningModeOn(std::string &strError) const; // Blackboard (dynamic parameter handling) - pthread_mutex_t* getBlackboardMutex(); + std::mutex &getBlackboardMutex(); // Blackboard reference (dynamic parameter handling) - CParameterBlackboard* getParameterBlackboard(); + CParameterBlackboard *getParameterBlackboard(); // Parameter access - bool accessValue(CParameterAccessContext& parameterAccessContext, const std::string& strPath, std::string& strValue, bool bSet, std::string& strError); - bool doSetValue(const std::string& strPath, const std::string& strValue, bool bRawValueSpace, bool bDynamicAccess, std::string& strError) const; - bool doGetValue(const std::string& strPath, std::string& strValue, bool bRawValueSpace, bool bHexOutputRawFormat, bool bDynamicAccess, std::string& strError) const; + bool accessValue(CParameterAccessContext ¶meterAccessContext, const std::string &strPath, + std::string &strValue, bool bSet, std::string &strError); + bool doSetValue(const std::string &strPath, const std::string &strValue, bool bRawValueSpace, + bool bDynamicAccess, std::string &strError) const; + bool doGetValue(const std::string &strPath, std::string &strValue, bool bRawValueSpace, + bool bHexOutputRawFormat, bool bDynamicAccess, std::string &strError) const; // Framework global configuration loading - bool loadFrameworkConfiguration(std::string& strError); + bool loadFrameworkConfiguration(std::string &strError); + + /** Load required subsystems + * + * @param[out] error error description if there is one + * @return true if succeed false otherwise + */ + bool loadSubsystems(std::string &error); // System class Structure loading - bool loadStructure(std::string& strError); + bool loadStructure(std::string &strError); // System class Structure loading - bool loadSettings(std::string& strError); - bool loadSettingsFromConfigFile(std::string& strError); + bool loadSettings(std::string &strError); + bool loadSettingsFromConfigFile(std::string &strError); + + /** Get settings from a configurable element in binary format. + * + * @param[in] element configurable element. + * @param[out] settings current element settings (in mainblackboard) in binary format + * + * @return true on success, false on error + */ + void getSettingsAsBytes(const CConfigurableElement &element, + std::vector<uint8_t> &settings) const; + + /** Assign settings to a configurable element in binary format. + * + * @param[in] element configurable element. + * @param[in] settings the settings as byte array (binary). + * @param[out] error error message filled in case of error + * + * @return true in case of success, false oherwise, in which case error is filled with error + * message. + */ + bool setSettingsAsBytes(const CConfigurableElement &element, + const std::vector<uint8_t> &settings, std::string &error); + + /** Assign settings to a configurable element in XML format. + * + * @param[in] configurableElement The element to set. + * @param[in] settings The settings to set. + * @param[out] error human readable error message filled in case of error, + * undefined in case of success. + * @return true in case of success, false otherwise + */ + bool setSettingsAsXML(CConfigurableElement *configurableElement, const std::string &settings, + std::string &error); + + /** Get settings from a configurable element in XML format. + * + * @param[in] configurableElement The element to get settings from. + * @param[out] result on success: the exported setttings in XML + * on error: human readable error message + * + * @return true in case of success, false otherwise. + */ + bool getSettingsAsXML(const CConfigurableElement *configurableElement, + std::string &result) const; /** Parse an XML stream into an element * * @param[in] elementSerializingContext serializing context * @param[out] pRootElement the receiving element * @param[in] input the input XML stream - * @param[in] strXmlFolder the folder containing the XML input file (if applicable) or "" + * @param[in] baseUri the XML input file URI or "" * @param[in] eElementLibrary which element library to be used + * @param[in] replace Should the element be overridden or modified in place * @param[in] strNameAttributeName the name of the element's XML "name" attribute * * @returns true if parsing succeeded, false otherwise */ - bool xmlParse(CXmlElementSerializingContext& elementSerializingContext, CElement* pRootElement, - _xmlDoc* doc, const std::string& strXmlFolder, - ElementLibrary eElementLibrary, const std::string& strNameAttributeName = "Name"); + bool xmlParse(CXmlElementSerializingContext &elementSerializingContext, CElement *pRootElement, + _xmlDoc *doc, const std::string &baseUri, ElementLibrary eElementLibrary, + bool replace = true, const std::string &strNameAttributeName = "Name"); /** Wrapper for converting public APIs semantics to internal API * @@ -582,9 +745,9 @@ private: * * @returns true if the import succeeded, false otherwise */ - bool wrapLegacyXmlImport(const std::string& xmlSource, bool fromFile, bool withSettings, - CElement& element, const std::string& nameAttributeName, - std::string& errorMsg); + bool wrapLegacyXmlImport(const std::string &xmlSource, bool fromFile, bool withSettings, + CElement &element, const std::string &nameAttributeName, + std::string &errorMsg); /** * Export an element object to an Xml destination. @@ -596,8 +759,8 @@ private: * * @return false if any error occurs, true otherwise. */ - bool serializeElement(std::ostream& output, CXmlSerializingContext& xmlSerializingContext, - const CElement& element) const; + bool serializeElement(std::ostream &output, CXmlSerializingContext &xmlSerializingContext, + const CElement &element) const; /** Wrapper for converting public APIs semantics to internal API * @@ -622,42 +785,39 @@ private: * * @returns true if the export succeeded, false otherwise */ - bool wrapLegacyXmlExport(std::string& xmlDest, bool toFile, bool withSettings, - const CElement& element, std::string& errorMsg) const; + bool wrapLegacyXmlExport(std::string &xmlDest, bool toFile, bool withSettings, + const CElement &element, std::string &errorMsg) const; /** Wrapper for converting public APIs semantics to internal API * * @see wrapLegacyXmlExport */ - bool wrapLegacyXmlExportToFile(std::string& xmlDest, - const CElement& element, + bool wrapLegacyXmlExportToFile(std::string &xmlDest, const CElement &element, CXmlDomainExportContext &context) const; /** Wrapper for converting public APIs semantics to internal API * * @see wrapLegacyXmlExport */ - bool wrapLegacyXmlExportToString(std::string& xmlDest, - const CElement& element, + bool wrapLegacyXmlExportToString(std::string &xmlDest, const CElement &element, CXmlDomainExportContext &context) const; - // Framework Configuration - CParameterFrameworkConfiguration* getFrameworkConfiguration(); - const CParameterFrameworkConfiguration* getConstFrameworkConfiguration(); + CParameterFrameworkConfiguration *getFrameworkConfiguration(); + const CParameterFrameworkConfiguration *getConstFrameworkConfiguration(); // Selection Criteria - CSelectionCriteria* getSelectionCriteria(); - const CSelectionCriteria* getConstSelectionCriteria(); + CSelectionCriteria *getSelectionCriteria(); + const CSelectionCriteria *getConstSelectionCriteria(); // System Class - CSystemClass* getSystemClass(); - const CSystemClass* getConstSystemClass() const; + CSystemClass *getSystemClass(); + const CSystemClass *getConstSystemClass() const; // Configurable Domains - CConfigurableDomains* getConfigurableDomains(); - const CConfigurableDomains* getConstConfigurableDomains(); - const CConfigurableDomains* getConstConfigurableDomains() const; + CConfigurableDomains *getConfigurableDomains(); + const CConfigurableDomains *getConstConfigurableDomains(); + const CConfigurableDomains *getConstConfigurableDomains() const; // Apply configurations void doApplyConfigurations(bool bForce); @@ -666,85 +826,83 @@ private: void feedElementLibraries(); // Remote Processor Server connection handling - bool handleRemoteProcessingInterface(std::string& strError); + bool isRemoteInterfaceRequired(); + bool handleRemoteProcessingInterface(std::string &strError); + + /** Log the result of a function + * + * @param[in] isSuccess indicates if the previous function has succeed + * @param[in] result function provided result string + * @return isSuccess parameter + */ + bool logResult(bool isSuccess, const std::string &result); + + /** Info logger call helper */ + inline core::log::details::Info info(); + + /** Warning logger call helper */ + inline core::log::details::Warning warning(); // Tuning - bool _bTuningModeIsOn; + bool _bTuningModeIsOn{false}; // Value Space - bool _bValueSpaceIsRaw; + bool _bValueSpaceIsRaw{false}; // Output Raw Format - bool _bOutputRawFormatIsHex; + bool _bOutputRawFormatIsHex{false}; // Automatic synchronization to HW during Tuning session - bool _bAutoSyncOn; + bool _bAutoSyncOn{true}; // Current Parameter Settings - CParameterBlackboard* _pMainParameterBlackboard; + CParameterBlackboard *_pMainParameterBlackboard; // Dynamic object creation - CElementLibrarySet* _pElementLibrarySet; + CElementLibrarySet *_pElementLibrarySet; // XML parsing, object creation handling - std::string _strXmlConfigurationFilePath; // Configuration file path - std::string _strXmlConfigurationFolderPath; // Root folder for configuration file - std::string _strSchemaFolderLocation; // Place where schemas stand + std::string _xmlConfigurationUri; + std::string _schemaUri; // Place where schemas stand // Subsystem plugin location - const CSubsystemPlugins* _pSubsystemPlugins; - - /** - * Remote processor library handle - */ - void* _pvLibRemoteProcessorHandle; - - // Whole system structure checksum - uint8_t _uiStructureChecksum; - - // Command Handler - CCommandHandler* _pCommandHandler; + const CSubsystemPlugins *_pSubsystemPlugins{nullptr}; // Remote Processor Server - IRemoteProcessorServerInterface* _pRemoteProcessorServer; + IRemoteProcessorServerInterface *_pRemoteProcessorServer{nullptr}; // Parser description array static const SRemoteCommandParserItem gastRemoteCommandParserItems[]; - // Parser description array size - static const uint32_t guiNbRemoteCommandParserItems; - // Maximum command usage length - uint32_t _uiMaxCommandUsageLength; + size_t _maxCommandUsageLength{0}; // Blackboard access mutex - pthread_mutex_t _blackboardMutex; + std::mutex _blackboardMutex; - // Logging - ILogger* _pLogger; - mutable uint32_t _uiLogDepth; + /** Application main logger based on the one provided by the client */ + mutable core::log::Logger _logger; /** If set to false, the remote interface won't be started no matter what. * If set to true - the default - it has no impact on the policy for * starting the remote interface. */ - bool _bForceNoRemoteInterface; + bool _bForceNoRemoteInterface{false}; /** If set to true, missing subsystem will abort parameterMgr start. * If set to false, missing subsystem will fallback on virtual subsystem. */ - bool _bFailOnMissingSubsystem; + bool _bFailOnMissingSubsystem{true}; /** If set to true, unparsable or discording domains will abort parameterMgr start. * If set to false, unparsable or discording domains * will continue the parameterMgr start with no domains. */ - bool _bFailOnFailedSettingsLoad; + bool _bFailOnFailedSettingsLoad{true}; /** * If set to true, parameterMgr will report an error * when being unable to validate .xml files * If set to false, no .xml/xsd validation will happen (default behaviour) */ - bool _bValidateSchemasOnStart; + bool _bValidateSchemasOnStart{false}; }; - diff --git a/parameter/ParameterMgrFullConnector.cpp b/parameter/ParameterMgrFullConnector.cpp index 30d2780..81577a9 100644 --- a/parameter/ParameterMgrFullConnector.cpp +++ b/parameter/ParameterMgrFullConnector.cpp @@ -31,126 +31,41 @@ #include "ParameterMgr.h" #include "ParameterMgrLogger.h" +#include "CommandHandlerWrapper.h" + #include <list> using std::string; -CParameterMgrFullConnector::CParameterMgrFullConnector(const string& strConfigurationFilePath) : - _pParameterMgr(new CParameterMgr(strConfigurationFilePath)), _pLogger(NULL) -{ - _pParameterMgrLogger = new CParameterMgrLogger<CParameterMgrFullConnector>(*this); - _pParameterMgr->setLogger(_pParameterMgrLogger); -} - -CParameterMgrFullConnector::~CParameterMgrFullConnector() -{ - delete _pParameterMgr; - delete _pParameterMgrLogger; -} - - -bool CParameterMgrFullConnector::start(string& strError) -{ - // Create data structure & Init flow - return _pParameterMgr->load(strError); -} - -void CParameterMgrFullConnector::setLogger(CParameterMgrFullConnector::ILogger* pLogger) -{ - _pLogger = pLogger; -} - -// Private logging -void CParameterMgrFullConnector::doLog(bool bIsWarning, const string& strLog) -{ - if (_pLogger) { - - _pLogger->log(bIsWarning, strLog); - } -} - -CParameterHandle* CParameterMgrFullConnector::createParameterHandle(const string& strPath, - string& strError) -{ - return _pParameterMgr->createParameterHandle(strPath, strError); -} - -ISelectionCriterionTypeInterface* CParameterMgrFullConnector::createSelectionCriterionType( - bool bIsInclusive) -{ - return _pParameterMgr->createSelectionCriterionType(bIsInclusive); -} - -ISelectionCriterionInterface* CParameterMgrFullConnector::createSelectionCriterion( - const string& strName, - const ISelectionCriterionTypeInterface* pSelectionCriterionType) -{ - return _pParameterMgr->createSelectionCriterion(strName, - static_cast<const CSelectionCriterionType*>(pSelectionCriterionType)); -} - -ISelectionCriterionInterface* CParameterMgrFullConnector::getSelectionCriterion( - const string& strName) +CParameterMgrFullConnector::CParameterMgrFullConnector(const string &strConfigurationFilePath) + : CParameterMgrPlatformConnector(strConfigurationFilePath) { - return _pParameterMgr->getSelectionCriterion(strName); } -bool CParameterMgrFullConnector::getForceNoRemoteInterface() const +CommandHandlerInterface *CParameterMgrFullConnector::createCommandHandler() { - return _pParameterMgr->getForceNoRemoteInterface(); -} - -void CParameterMgrFullConnector::setForceNoRemoteInterface(bool bForceNoRemoteInterface) -{ - _pParameterMgr->setForceNoRemoteInterface(bForceNoRemoteInterface); -} - -void CParameterMgrFullConnector::applyConfigurations() -{ - return _pParameterMgr->applyConfigurations(); + return new CommandHandlerWrapper(_pParameterMgr->createCommandHandler()); } void CParameterMgrFullConnector::setFailureOnMissingSubsystem(bool bFail) { - _pParameterMgr->setFailureOnMissingSubsystem(bFail); -} - -bool CParameterMgrFullConnector::getFailureOnMissingSubsystem() const -{ - return _pParameterMgr->getFailureOnMissingSubsystem(); + std::string error; + setFailureOnMissingSubsystem(bFail, error); } void CParameterMgrFullConnector::setFailureOnFailedSettingsLoad(bool bFail) { - _pParameterMgr->setFailureOnFailedSettingsLoad(bFail); -} - -bool CParameterMgrFullConnector::getFailureOnFailedSettingsLoad() -{ - return _pParameterMgr->getFailureOnFailedSettingsLoad(); -} - -const string& CParameterMgrFullConnector::getSchemaFolderLocation() const -{ - return _pParameterMgr->getSchemaFolderLocation(); -} - -void CParameterMgrFullConnector::setSchemaFolderLocation(const string& strSchemaFolderLocation) -{ - _pParameterMgr->setSchemaFolderLocation(strSchemaFolderLocation); + std::string error; + setFailureOnFailedSettingsLoad(bFail, error); } void CParameterMgrFullConnector::setValidateSchemasOnStart(bool bValidate) { - _pParameterMgr->setValidateSchemasOnStart(bValidate); -} - -bool CParameterMgrFullConnector::getValidateSchemasOnStart() const -{ - return _pParameterMgr->getValidateSchemasOnStart(); + std::string error; + setValidateSchemasOnStart(bValidate, error); } -bool CParameterMgrFullConnector::setTuningMode(bool bOn, string& strError) +bool CParameterMgrFullConnector::setTuningMode(bool bOn, string &strError) { return _pParameterMgr->setTuningMode(bOn, strError); } @@ -162,7 +77,7 @@ bool CParameterMgrFullConnector::isTuningModeOn() const void CParameterMgrFullConnector::setValueSpace(bool bIsRaw) { - return _pParameterMgr->setValueSpace(bIsRaw); + _pParameterMgr->setValueSpace(bIsRaw); } bool CParameterMgrFullConnector::isValueSpaceRaw() const @@ -172,7 +87,7 @@ bool CParameterMgrFullConnector::isValueSpaceRaw() const void CParameterMgrFullConnector::setOutputRawFormat(bool bIsHex) { - return _pParameterMgr->setOutputRawFormat(bIsHex); + _pParameterMgr->setOutputRawFormat(bIsHex); } bool CParameterMgrFullConnector::isOutputRawFormatHex() const @@ -180,7 +95,7 @@ bool CParameterMgrFullConnector::isOutputRawFormatHex() const return _pParameterMgr->outputRawFormatIsHex(); } -bool CParameterMgrFullConnector::setAutoSync(bool bAutoSyncOn, string& strError) +bool CParameterMgrFullConnector::setAutoSync(bool bAutoSyncOn, string &strError) { return _pParameterMgr->setAutoSync(bAutoSyncOn, strError); } @@ -190,185 +105,182 @@ bool CParameterMgrFullConnector::isAutoSyncOn() const return _pParameterMgr->autoSyncOn(); } -bool CParameterMgrFullConnector::sync(string& strError) +bool CParameterMgrFullConnector::sync(string &strError) { return _pParameterMgr->sync(strError); } -bool CParameterMgrFullConnector::accessParameterValue(const string& strPath, string& strValue, - bool bSet, string& strError) +bool CParameterMgrFullConnector::accessParameterValue(const string &strPath, string &strValue, + bool bSet, string &strError) { return _pParameterMgr->accessParameterValue(strPath, strValue, bSet, strError); } bool CParameterMgrFullConnector::accessConfigurationValue(const string &strDomain, const string &strConfiguration, - const string& strPath, string& strValue, - bool bSet, string& strError) + const string &strPath, string &strValue, + bool bSet, string &strError) { return _pParameterMgr->accessConfigurationValue(strDomain, strConfiguration, strPath, strValue, - bSet, strError); + bSet, strError); } -bool CParameterMgrFullConnector::getParameterMapping(const string& strPath, string& strValue) const +bool CParameterMgrFullConnector::getParameterMapping(const string &strPath, string &strValue) const { return _pParameterMgr->getParameterMapping(strPath, strValue); } -bool CParameterMgrFullConnector::createDomain(const string& strName, string& strError) +bool CParameterMgrFullConnector::createDomain(const string &strName, string &strError) { return _pParameterMgr->createDomain(strName, strError); } -bool CParameterMgrFullConnector::deleteDomain(const string& strName, string& strError) +bool CParameterMgrFullConnector::deleteDomain(const string &strName, string &strError) { return _pParameterMgr->deleteDomain(strName, strError); } -bool CParameterMgrFullConnector::renameDomain(const string& strName, const string& strNewName, - string& strError) +bool CParameterMgrFullConnector::renameDomain(const string &strName, const string &strNewName, + string &strError) { return _pParameterMgr->renameDomain(strName, strNewName, strError); } -bool CParameterMgrFullConnector::deleteAllDomains(string& strError) +bool CParameterMgrFullConnector::deleteAllDomains(string &strError) { return _pParameterMgr->deleteAllDomains(strError); } -bool CParameterMgrFullConnector::createConfiguration(const string& strDomain, - const string& strConfiguration, - string& strError) +bool CParameterMgrFullConnector::createConfiguration(const string &strDomain, + const string &strConfiguration, + string &strError) { return _pParameterMgr->createConfiguration(strDomain, strConfiguration, strError); } -bool CParameterMgrFullConnector::deleteConfiguration(const string& strDomain, - const string& strConfiguration, - string& strError) +bool CParameterMgrFullConnector::deleteConfiguration(const string &strDomain, + const string &strConfiguration, + string &strError) { return _pParameterMgr->deleteConfiguration(strDomain, strConfiguration, strError); } -bool CParameterMgrFullConnector::renameConfiguration(const string& strDomain, - const string& strConfiguration, - const string& strNewConfiguration, - string& strError) +bool CParameterMgrFullConnector::renameConfiguration(const string &strDomain, + const string &strConfiguration, + const string &strNewConfiguration, + string &strError) { return _pParameterMgr->renameConfiguration(strDomain, strConfiguration, strNewConfiguration, - strError); + strError); } -bool CParameterMgrFullConnector::saveConfiguration(const string& strDomain, - const string& strConfiguration, string& strError) +bool CParameterMgrFullConnector::saveConfiguration(const string &strDomain, + const string &strConfiguration, string &strError) { return _pParameterMgr->saveConfiguration(strDomain, strConfiguration, strError); } -bool CParameterMgrFullConnector::restoreConfiguration(const string& strDomain, - const string& strConfiguration, - std::list<string>& lstrError) +bool CParameterMgrFullConnector::restoreConfiguration(const string &strDomain, + const string &strConfiguration, + Results &errors) { - return _pParameterMgr->restoreConfiguration(strDomain, strConfiguration, lstrError); + return _pParameterMgr->restoreConfiguration(strDomain, strConfiguration, errors); } -bool CParameterMgrFullConnector::setSequenceAwareness(const string& strName, bool bSequenceAware, - string& strResult) +bool CParameterMgrFullConnector::setSequenceAwareness(const string &strName, bool bSequenceAware, + string &strResult) { return _pParameterMgr->setSequenceAwareness(strName, bSequenceAware, strResult); } -bool CParameterMgrFullConnector::getSequenceAwareness(const string& strName, bool& bSequenceAware, - string& strResult) +bool CParameterMgrFullConnector::getSequenceAwareness(const string &strName, bool &bSequenceAware, + string &strResult) { return _pParameterMgr->getSequenceAwareness(strName, bSequenceAware, strResult); } -bool CParameterMgrFullConnector::addConfigurableElementToDomain(const string& strDomain, - const string& strConfigurableElementPath, string& strError) +bool CParameterMgrFullConnector::addConfigurableElementToDomain( + const string &strDomain, const string &strConfigurableElementPath, string &strError) { return _pParameterMgr->addConfigurableElementToDomain(strDomain, strConfigurableElementPath, - strError); + strError); } -bool CParameterMgrFullConnector::removeConfigurableElementFromDomain(const string& strDomain, - const string& strConfigurableElementPath, string& strError) +bool CParameterMgrFullConnector::removeConfigurableElementFromDomain( + const string &strDomain, const string &strConfigurableElementPath, string &strError) { - return _pParameterMgr->removeConfigurableElementFromDomain(strDomain, - strConfigurableElementPath, strError); + return _pParameterMgr->removeConfigurableElementFromDomain( + strDomain, strConfigurableElementPath, strError); } -bool CParameterMgrFullConnector::split(const string& strDomain, - const string& strConfigurableElementPath, string& strError) +bool CParameterMgrFullConnector::split(const string &strDomain, + const string &strConfigurableElementPath, string &strError) { return _pParameterMgr->split(strDomain, strConfigurableElementPath, strError); } -bool CParameterMgrFullConnector::setElementSequence(const string& strDomain, - const string& strConfiguration, - const std::vector<string>& astrNewElementSequence, - string& strError) +bool CParameterMgrFullConnector::setElementSequence( + const string &strDomain, const string &strConfiguration, + const std::vector<string> &astrNewElementSequence, string &strError) { return _pParameterMgr->setElementSequence(strDomain, strConfiguration, astrNewElementSequence, - strError); + strError); } -bool CParameterMgrFullConnector::setApplicationRule(const string& strDomain, - const string& strConfiguration, - const string& strApplicationRule, - string& strError) +bool CParameterMgrFullConnector::setApplicationRule(const string &strDomain, + const string &strConfiguration, + const string &strApplicationRule, + string &strError) { return _pParameterMgr->setApplicationRule(strDomain, strConfiguration, strApplicationRule, - strError); + strError); } - -bool CParameterMgrFullConnector::getApplicationRule(const string& strDomain, - const string& strConfiguration, - string& strResult) +bool CParameterMgrFullConnector::getApplicationRule(const string &strDomain, + const string &strConfiguration, + string &strResult) { return _pParameterMgr->getApplicationRule(strDomain, strConfiguration, strResult); } -bool CParameterMgrFullConnector::clearApplicationRule(const string& strDomain, - const string& strConfiguration, - string& strError) +bool CParameterMgrFullConnector::clearApplicationRule(const string &strDomain, + const string &strConfiguration, + string &strError) { return _pParameterMgr->clearApplicationRule(strDomain, strConfiguration, strError); } - -bool CParameterMgrFullConnector::importDomainsXml(const string& strXmlSource, bool bWithSettings, - bool bFromFile, string& strError) +bool CParameterMgrFullConnector::importDomainsXml(const string &strXmlSource, bool bWithSettings, + bool bFromFile, string &strError) { return _pParameterMgr->importDomainsXml(strXmlSource, bWithSettings, bFromFile, strError); } -bool CParameterMgrFullConnector::exportDomainsXml(string& strXmlDest, bool bWithSettings, - bool bToFile, string& strError) const +bool CParameterMgrFullConnector::exportDomainsXml(string &strXmlDest, bool bWithSettings, + bool bToFile, string &strError) const { return _pParameterMgr->exportDomainsXml(strXmlDest, bWithSettings, bToFile, strError); } // deprecated, use the other version of importSingleDomainXml instead -bool CParameterMgrFullConnector::importSingleDomainXml(const string& strXmlSource, bool bOverwrite, - string& strError) +bool CParameterMgrFullConnector::importSingleDomainXml(const string &strXmlSource, bool bOverwrite, + string &strError) { return importSingleDomainXml(strXmlSource, bOverwrite, true, false, strError); } -bool CParameterMgrFullConnector::importSingleDomainXml(const string& xmlSource, bool overwrite, +bool CParameterMgrFullConnector::importSingleDomainXml(const string &xmlSource, bool overwrite, bool withSettings, bool fromFile, - string& errorMsg) + string &errorMsg) { return _pParameterMgr->importSingleDomainXml(xmlSource, overwrite, withSettings, fromFile, errorMsg); } -bool CParameterMgrFullConnector::exportSingleDomainXml(string& strXmlDest, - const string& strDomainName, +bool CParameterMgrFullConnector::exportSingleDomainXml(string &strXmlDest, + const string &strDomainName, bool bWithSettings, bool bToFile, - string& strError) const + string &strError) const { return _pParameterMgr->exportSingleDomainXml(strXmlDest, strDomainName, bWithSettings, bToFile, - strError); + strError); } diff --git a/parameter/ParameterMgrLogger.h b/parameter/ParameterMgrLogger.h index 0e42d8a..aafb76a 100644 --- a/parameter/ParameterMgrLogger.h +++ b/parameter/ParameterMgrLogger.h @@ -30,28 +30,24 @@ #pragma once #include "ParameterMgrLoggerForward.h" -#include "ParameterMgr.h" +#include <log/ILogger.h> +#include <NonCopyable.hpp> #include <string> -/* Wrap a class to expose its logging [log(bool, string&)] capabilities +/* Wrap a class to expose its logging [info, warning] capabilities * through ILogger. */ -template<class T> -class CParameterMgrLogger : public CParameterMgr::ILogger +template <class T> +class CParameterMgrLogger : public core::log::ILogger, private utility::NonCopyable { public: - CParameterMgrLogger(T& parameterMgrConnector) : - _parameterMgrConnector(parameterMgrConnector) - { - } + CParameterMgrLogger(T ¶meterMgrConnector) : _parameterMgrConnector(parameterMgrConnector) {} - virtual void log(bool bIsWarning, const std::string& strLog) - { - _parameterMgrConnector.doLog(bIsWarning, strLog); - } + virtual void info(const std::string &log) { _parameterMgrConnector.info(log); } + + virtual void warning(const std::string &log) { _parameterMgrConnector.warning(log); } private: // Log destination - T& _parameterMgrConnector; + T &_parameterMgrConnector; }; - diff --git a/parameter/ParameterMgrPlatformConnector.cpp b/parameter/ParameterMgrPlatformConnector.cpp index d49003d..8eff7c9 100644 --- a/parameter/ParameterMgrPlatformConnector.cpp +++ b/parameter/ParameterMgrPlatformConnector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -36,12 +36,11 @@ using std::string; // Construction CParameterMgrPlatformConnector::CParameterMgrPlatformConnector( - const string& strConfigurationFilePath) : - _pParameterMgr(new CParameterMgr(strConfigurationFilePath)), _bStarted(false), _pLogger(NULL) + const string &strConfigurationFilePath) + : _pParameterMgrLogger(new CParameterMgrLogger<CParameterMgrPlatformConnector>(*this)), + _pParameterMgr(new CParameterMgr(strConfigurationFilePath, *_pParameterMgrLogger)), + _bStarted(false), _pLogger(NULL) { - // Logging - _pParameterMgrLogger = new CParameterMgrLogger<CParameterMgrPlatformConnector>(*this); - _pParameterMgr->setLogger(_pParameterMgrLogger); } CParameterMgrPlatformConnector::~CParameterMgrPlatformConnector() @@ -51,22 +50,26 @@ CParameterMgrPlatformConnector::~CParameterMgrPlatformConnector() } // Selection Criteria interface. Beware returned objects are lent, clients shall not delete them! -ISelectionCriterionTypeInterface* CParameterMgrPlatformConnector::createSelectionCriterionType(bool bIsInclusive) +ISelectionCriterionTypeInterface *CParameterMgrPlatformConnector::createSelectionCriterionType( + bool bIsInclusive) { assert(!_bStarted); return _pParameterMgr->createSelectionCriterionType(bIsInclusive); } -ISelectionCriterionInterface* CParameterMgrPlatformConnector::createSelectionCriterion(const string& strName, const ISelectionCriterionTypeInterface* pSelectionCriterionType) +ISelectionCriterionInterface *CParameterMgrPlatformConnector::createSelectionCriterion( + const string &strName, const ISelectionCriterionTypeInterface *pSelectionCriterionType) { assert(!_bStarted); - return _pParameterMgr->createSelectionCriterion(strName, static_cast<const CSelectionCriterionType*>(pSelectionCriterionType)); + return _pParameterMgr->createSelectionCriterion( + strName, static_cast<const CSelectionCriterionType *>(pSelectionCriterionType)); } // Selection criterion retrieval -ISelectionCriterionInterface* CParameterMgrPlatformConnector::getSelectionCriterion(const string& strName) const +ISelectionCriterionInterface *CParameterMgrPlatformConnector::getSelectionCriterion( + const string &strName) const { return _pParameterMgr->getSelectionCriterion(strName); } @@ -80,15 +83,22 @@ void CParameterMgrPlatformConnector::applyConfigurations() } // Dynamic parameter handling -CParameterHandle* CParameterMgrPlatformConnector::createParameterHandle(const string& strPath, string& strError) const +CParameterHandle *CParameterMgrPlatformConnector::createParameterHandle(const string &strPath, + string &strError) const { assert(_bStarted); return _pParameterMgr->createParameterHandle(strPath, strError); } +ElementHandle *CParameterMgrPlatformConnector::createElementHandle(const string &strPath, + string &strError) const +{ + return _pParameterMgr->createElementHandle(strPath, strError); +} + // Logging -void CParameterMgrPlatformConnector::setLogger(CParameterMgrPlatformConnector::ILogger* pLogger) +void CParameterMgrPlatformConnector::setLogger(CParameterMgrPlatformConnector::ILogger *pLogger) { _pLogger = pLogger; } @@ -115,13 +125,13 @@ bool CParameterMgrPlatformConnector::setFailureOnMissingSubsystem(bool bFail, st return true; } -bool CParameterMgrPlatformConnector::getFailureOnMissingSubsystem() +bool CParameterMgrPlatformConnector::getFailureOnMissingSubsystem() const { return _pParameterMgr->getFailureOnMissingSubsystem(); } -bool CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad( - bool bFail, std::string& strError) +bool CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad(bool bFail, + std::string &strError) { if (_bStarted) { @@ -133,23 +143,23 @@ bool CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad( return true; } -bool CParameterMgrPlatformConnector::getFailureOnFailedSettingsLoad() +bool CParameterMgrPlatformConnector::getFailureOnFailedSettingsLoad() const { return _pParameterMgr->getFailureOnFailedSettingsLoad(); } -const string& CParameterMgrPlatformConnector::getSchemaFolderLocation() const +const string &CParameterMgrPlatformConnector::getSchemaUri() const { - return _pParameterMgr->getSchemaFolderLocation(); + return _pParameterMgr->getSchemaUri(); } -void CParameterMgrPlatformConnector::setSchemaFolderLocation(const string& strSchemaFolderLocation) +void CParameterMgrPlatformConnector::setSchemaUri(const string &schemaUri) { - _pParameterMgr->setSchemaFolderLocation(strSchemaFolderLocation); + _pParameterMgr->setSchemaUri(schemaUri); } -bool CParameterMgrPlatformConnector::setValidateSchemasOnStart( - bool bValidate, std::string& strError) +bool CParameterMgrPlatformConnector::setValidateSchemasOnStart(bool bValidate, + std::string &strError) { if (_bStarted) { @@ -161,13 +171,13 @@ bool CParameterMgrPlatformConnector::setValidateSchemasOnStart( return true; } -bool CParameterMgrPlatformConnector::getValidateSchemasOnStart() +bool CParameterMgrPlatformConnector::getValidateSchemasOnStart() const { return _pParameterMgr->getValidateSchemasOnStart(); } // Start -bool CParameterMgrPlatformConnector::start(string& strError) +bool CParameterMgrPlatformConnector::start(string &strError) { // Create data structure if (!_pParameterMgr->load(strError)) { @@ -187,10 +197,18 @@ bool CParameterMgrPlatformConnector::isStarted() const } // Private logging -void CParameterMgrPlatformConnector::doLog(bool bIsWarning, const string& strLog) +void CParameterMgrPlatformConnector::info(const string &log) +{ + if (_pLogger) { + + _pLogger->info(log); + } +} + +void CParameterMgrPlatformConnector::warning(const string &log) { if (_pLogger) { - _pLogger->log(bIsWarning, strLog); + _pLogger->warning(log); } } diff --git a/parameter/ParameterType.cpp b/parameter/ParameterType.cpp index eb9fd3d..5472f27 100644 --- a/parameter/ParameterType.cpp +++ b/parameter/ParameterType.cpp @@ -31,7 +31,8 @@ #include "Parameter.h" #include "ArrayParameter.h" #include "ParameterAccessContext.h" -#include "Utility.h" + +#include <climits> #define base CTypeElement @@ -39,30 +40,25 @@ using std::string; const std::string CParameterType::gUnitPropertyName = "Unit"; -CParameterType::CParameterType(const string& strName) : base(strName), _uiSize(0) -{ -} - -CParameterType::~CParameterType() +CParameterType::CParameterType(const string &strName) : base(strName) { } // Object creation -void CParameterType::populate(CElement* pElement) const +void CParameterType::populate(CElement * /*elem*/) const { - (void)pElement; // Prevent further digging for instantiaton since we're leaf on the strcture tree } // Size -void CParameterType::setSize(uint32_t uiSize) +void CParameterType::setSize(size_t size) { - _uiSize = uiSize; + _size = size; } -uint32_t CParameterType::getSize() const +size_t CParameterType::getSize() const { - return _uiSize; + return _size; } // Unit @@ -71,44 +67,46 @@ string CParameterType::getUnit() const return _strUnit; } -void CParameterType::setUnit(const std::string& strUnit) +void CParameterType::setUnit(const std::string &strUnit) { _strUnit = strUnit; } // From IXmlSink -bool CParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { - setUnit(xmlElement.getAttributeString(gUnitPropertyName)); + xmlElement.getAttribute(gUnitPropertyName, _strUnit); return base::fromXml(xmlElement, serializingContext); } // From IXmlSource -void CParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { base::toXml(xmlElement, serializingContext); setXmlUnitAttribute(xmlElement); } -void CParameterType::setXmlUnitAttribute(CXmlElement& xmlElement) const +void CParameterType::setXmlUnitAttribute(CXmlElement &xmlElement) const { - const string& unit = getUnit(); + const string &unit = getUnit(); if (!unit.empty()) { - xmlElement.setAttributeString(gUnitPropertyName, unit); + xmlElement.setAttribute(gUnitPropertyName, unit); } } // XML Serialization value space handling // Value space handling for configuration import/export -void CParameterType::handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const +void CParameterType::handleValueSpaceAttribute( + CXmlElement & /*xmlConfigurableElementSettingsElement*/, + CConfigurationAccessContext & /*ctx*/) const { - (void)xmlConfigurableElementSettingsElement; - (void)configurationAccessContext; // Do nothing by default } // Element properties -void CParameterType::showProperties(string& strResult) const +void CParameterType::showProperties(string &strResult) const { base::showProperties(strResult); @@ -118,7 +116,7 @@ void CParameterType::showProperties(string& strResult) const } // Scalar size - strResult += "Scalar size: " + CUtility::toString(getSize()) + " byte(s) \n"; + strResult += "Scalar size: " + std::to_string(getSize()) + " byte(s) \n"; } // Default value handling (simulation only) @@ -128,7 +126,7 @@ uint32_t CParameterType::getDefaultValue() const } // Parameter instantiation -CInstanceConfigurableElement* CParameterType::doInstantiate() const +CInstanceConfigurableElement *CParameterType::doInstantiate() const { if (isScalar()) { // Scalar parameter @@ -139,27 +137,27 @@ CInstanceConfigurableElement* CParameterType::doInstantiate() const } } -void CParameterType::signExtend(int32_t& iData) const +void CParameterType::signExtend(int32_t &iData) const { doSignExtend(iData); } -void CParameterType::signExtend(int64_t& iData) const +void CParameterType::signExtend(int64_t &iData) const { doSignExtend(iData); } // Generic sign extension template <typename type> -void CParameterType::doSignExtend(type& data) const +void CParameterType::doSignExtend(type &data) const { - uint32_t uiSizeInBits = getSize() * 8; - uint32_t uiShift = 8 * sizeof(data) - uiSizeInBits; - - if (uiShift) { - - data = (data << uiShift) >> uiShift; - } + size_t shift = CHAR_BIT * (sizeof(data) - getSize()); + // FIXME: If `data` has a signed type and nonnegative value, + // and `data × 2^shift` is representable in the result type, + // then that is the resulting value; + // otherwise, **the behavior is undefined**. + // ISO C99 (6.5.7/4) & ISO C++11 [expr.shift] + data = (data << shift) >> shift; } // Check data has no bit set outside available range (32 bits) @@ -183,33 +181,29 @@ bool CParameterType::doIsEncodable(type data, bool bIsSigned) const return true; } - uint32_t uiShift = getSize() * 8; + size_t shift = getSize() * 8; if (!bIsSigned) { // Check high bits are clean - return !(data >> uiShift); + return !(data >> shift); } else { // Negative value? - bool bIsValueExpectedNegative = (data & (1 << (uiShift - 1))) != 0; + bool bIsValueExpectedNegative = (data & (type(1) << (shift - 1))) != 0; // Check high bits are clean - return bIsValueExpectedNegative ? !(~data >> uiShift) : !(data >> uiShift); + return bIsValueExpectedNegative ? !(~data >> shift) : !(data >> shift); } } // Remove all bits set outside available range uint32_t CParameterType::makeEncodable(uint32_t uiData) const { - if (getSize() == sizeof(uint32_t)) { - - return uiData; - } - uint32_t uiSizeInBits = getSize() * 8; + size_t sizeInBits = getSize() * 8; - uint32_t uiMask = (1 << uiSizeInBits) - 1; + uint32_t uiMask = (1 << sizeInBits) - 1; return uiData & uiMask; } @@ -217,95 +211,65 @@ uint32_t CParameterType::makeEncodable(uint32_t uiData) const // Conversions (dynamic access) // Value access // Boolean -bool CParameterType::toBlackboard(bool bUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::toBlackboard(bool /*bUserValue*/, uint32_t & /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)bUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); - return false; } -bool CParameterType::fromBlackboard(bool& bUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::fromBlackboard(bool & /*bUserValue*/, uint32_t /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)bUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); - return false; } // Integer -bool CParameterType::toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::toBlackboard(uint32_t /*uiUserValue*/, uint32_t & /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)uiUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); - return false; } -bool CParameterType::fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::fromBlackboard(uint32_t & /*uiUserValue*/, uint32_t /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)uiUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); - return false; } // Signed Integer -bool CParameterType::toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::toBlackboard(int32_t /*iUserValue*/, uint32_t & /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)iUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); return false; } -bool CParameterType::fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::fromBlackboard(int32_t & /*iUserValue*/, uint32_t /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)iUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); return false; } // Double -bool CParameterType::toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::toBlackboard(double /*dUserValue*/, uint32_t & /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)dUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); return false; } -bool CParameterType::fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +bool CParameterType::fromBlackboard(double & /*dUserValue*/, uint32_t /*uiValue*/, + CParameterAccessContext ¶meterAccessContext) const { - (void)dUserValue; - (void)uiValue; - (void)parameterAccessContext; - parameterAccessContext.setError("Unsupported conversion"); return false; } - - diff --git a/parameter/ParameterType.h b/parameter/ParameterType.h index cf58f7b..5cb32d9 100644 --- a/parameter/ParameterType.h +++ b/parameter/ParameterType.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,6 +29,8 @@ */ #pragma once +#include "parameter_export.h" + #include <stdint.h> #include <limits> @@ -39,48 +41,70 @@ class CParameterAccessContext; class CConfigurationAccessContext; -class CParameterType : public CTypeElement +class PARAMETER_EXPORT CParameterType : public CTypeElement { public: - CParameterType(const std::string& strName); - virtual ~CParameterType(); + CParameterType(const std::string &strName); + virtual ~CParameterType() = default; // Size - uint32_t getSize() const; + size_t getSize() const; // Unit std::string getUnit() const; - void setUnit(const std::string& strUnit); + void setUnit(const std::string &strUnit); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; /// Conversions // String - virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const = 0; - virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const = 0; + virtual bool toBlackboard(const std::string &strValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const = 0; + virtual bool fromBlackboard(std::string &strValue, const uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const = 0; // Boolean - virtual bool toBlackboard(bool bUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(bool& bUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(bool bUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(bool &bUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Integer - virtual bool toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(uint32_t uiUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(uint32_t &uiUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Signed Integer - virtual bool toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(int32_t iUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(int32_t &iUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; // Double - virtual bool toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const; - virtual bool fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const; + virtual bool toBlackboard(double dUserValue, uint32_t &uiValue, + CParameterAccessContext ¶meterAccessContext) const; + virtual bool fromBlackboard(double &dUserValue, uint32_t uiValue, + CParameterAccessContext ¶meterAccessContext) const; - // XML Serialization value space handling - // Value space handling for configuration import/export - virtual void handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const; + /** Value space handling for settings import/export from/to XML + * + * During export, this method set the "ValueSpace" attribute of the future + * XML element according to the export context. + * + * During import, this method reads the "ValueSpace" attribute of the XML + * element being imported and sets the access context's value space + * accordingly. + * + * @param[in,out] xmlConfigurableElementSettingsElement the element being imported or exported + * @param[in,out] configurationAccessContext the import or export context + */ + virtual void handleValueSpaceAttribute( + CXmlElement &xmlConfigurableElementSettingsElement, + CConfigurationAccessContext &configurationAccessContext) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // Default value handling (simulation only) virtual uint32_t getDefaultValue() const; @@ -88,22 +112,22 @@ public: /** * Sign extension (32 bits) * - * @param[in:out] iData the data which will be sign extended + * @param[in,out] iData the data which will be sign extended */ - void signExtend(int32_t& iData) const; + void signExtend(int32_t &iData) const; /** * Sign extension (64 bits) * - * @param[in:out] iData the data which will be sign extended + * @param[in,out] iData the data which will be sign extended */ - void signExtend(int64_t& iData) const; + void signExtend(int64_t &iData) const; protected: // Object creation - virtual void populate(CElement* pElement) const; + virtual void populate(CElement *pElement) const; // Size - void setSize(uint32_t uiSize); + void setSize(size_t size); // Check data has no bit set outside available range (based on byte size) and // check data is consistent with available range, with respect to its sign @@ -116,24 +140,26 @@ protected: template <typename type> type getMaxValue() const { - return getSize() < sizeof(type) ? - (static_cast<type>(1) << (getSize() * std::numeric_limits<unsigned char>::digits - 1)) - 1 : - std::numeric_limits<type>::max(); + return getSize() < sizeof(type) + ? (static_cast<type>(1) + << (getSize() * std::numeric_limits<unsigned char>::digits - 1)) - + 1 + : std::numeric_limits<type>::max(); } private: - void setXmlUnitAttribute(CXmlElement& xmlElement) const; + void setXmlUnitAttribute(CXmlElement &xmlElement) const; // Instantiation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Generic Access template <typename type> - void doSignExtend(type& data) const; + void doSignExtend(type &data) const; template <typename type> bool doIsEncodable(type data, bool bIsSigned) const; // Size in bytes - uint32_t _uiSize; + size_t _size{0}; // Unit std::string _strUnit; diff --git a/parameter/PathNavigator.cpp b/parameter/PathNavigator.cpp index 47fc5c5..36deaea 100644 --- a/parameter/PathNavigator.cpp +++ b/parameter/PathNavigator.cpp @@ -30,12 +30,12 @@ #include "PathNavigator.h" #include "Tokenizer.h" -CPathNavigator::CPathNavigator(const std::string& strPath) : _uiCurrentIndex(0) +CPathNavigator::CPathNavigator(const std::string &strPath) { init(strPath); } -void CPathNavigator::init(const std::string& strPath) +void CPathNavigator::init(const std::string &strPath) { Tokenizer tokenizer(strPath, "/"); @@ -50,7 +50,7 @@ bool CPathNavigator::isPathValid() const } // Navigate through -bool CPathNavigator::navigateThrough(const std::string& strItemName, std::string& strError) +bool CPathNavigator::navigateThrough(const std::string &strItemName, std::string &strError) { if (!_bValid) { @@ -59,20 +59,20 @@ bool CPathNavigator::navigateThrough(const std::string& strItemName, std::string return false; } - std::string* pStrChildName = next(); + std::string *pStrChildName = next(); if (!pStrChildName) { - strError = "Path not complete: " + getCurrentPath() + - ", trying to access to " + strItemName; + strError = + "Path not complete: " + getCurrentPath() + ", trying to access to " + strItemName; return false; } if (*pStrChildName != strItemName) { - strError = "Path not found: " + getCurrentPath() + - ", expected: " + strItemName + " but found: " + *pStrChildName; + strError = "Path not found: " + getCurrentPath() + ", expected: " + strItemName + + " but found: " + *pStrChildName; return false; } @@ -80,11 +80,11 @@ bool CPathNavigator::navigateThrough(const std::string& strItemName, std::string return true; } -std::string* CPathNavigator::next() +std::string *CPathNavigator::next() { - if (_uiCurrentIndex < _astrItems.size()) { + if (_currentIndex < _astrItems.size()) { - return &_astrItems[_uiCurrentIndex++]; + return &_astrItems[_currentIndex++]; } return NULL; @@ -94,25 +94,23 @@ std::string CPathNavigator::getCurrentPath() const { std::string strPath = "/"; - if (!_uiCurrentIndex) { + if (!_currentIndex) { return strPath; } - uint32_t uiItem; + size_t item; + for (item = 0; item < _currentIndex - 1; item++) { - for (uiItem = 0; uiItem < _uiCurrentIndex - 1; uiItem++) { - - strPath += _astrItems[uiItem] + "/"; + strPath += _astrItems[item] + "/"; } - strPath += _astrItems[uiItem]; + strPath += _astrItems[item]; return strPath; } - -bool CPathNavigator::checkPathFormat(const std::string& strUpl) +bool CPathNavigator::checkPathFormat(const std::string &strUpl) { return strUpl[0] == '/'; } diff --git a/parameter/PathNavigator.h b/parameter/PathNavigator.h index 3db709a..e8df53d 100644 --- a/parameter/PathNavigator.h +++ b/parameter/PathNavigator.h @@ -36,25 +36,25 @@ class CPathNavigator { public: - CPathNavigator(const std::string& strPath); + CPathNavigator(const std::string &strPath); // Path validity bool isPathValid() const; // Navigate through - bool navigateThrough(const std::string& strItemName, std::string& strError); + bool navigateThrough(const std::string &strItemName, std::string &strError); // Nagivate - std::string* next(); + std::string *next(); // Current path std::string getCurrentPath() const; private: - void init(const std::string& strPath); - static bool checkPathFormat(const std::string& strUpl); + void init(const std::string &strPath); + static bool checkPathFormat(const std::string &strUpl); bool _bValid; std::vector<std::string> _astrItems; - uint32_t _uiCurrentIndex; + size_t _currentIndex{0}; }; diff --git a/parameter/Plugin.h b/parameter/Plugin.h new file mode 100644 index 0000000..137d96c --- /dev/null +++ b/parameter/Plugin.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +/** @file + * + * This file is intended to be used by the plugins. + * + * The compilation unit defining the entry point (aka the Subsystem Builder) + * should include this file a define a function corresponding to the one + * declared below. + */ + +#include <SubsystemLibrary.h> + +extern "C" { +#if defined(__clang__) || defined(__GNUC__) +__attribute__((visibility("default"))) +#elif defined(_MSC_VER) +__declspec(dllexport) +#endif + void PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1(CSubsystemLibrary*, core::log::Logger&); +} diff --git a/parameter/PluginLocation.cpp b/parameter/PluginLocation.cpp index 92f2ce9..1c98ce3 100644 --- a/parameter/PluginLocation.cpp +++ b/parameter/PluginLocation.cpp @@ -31,27 +31,25 @@ #define base CKindElement -CPluginLocation::CPluginLocation(const std::string& strName, const std::string& strKind) : base(strName, strKind) +CPluginLocation::CPluginLocation(const std::string &strName, const std::string &strKind) + : base(strName, strKind) { - } -const std::string& CPluginLocation::getFolder() const +const std::string &CPluginLocation::getFolder() const { return _strFolder; } -const std::list<std::string>& CPluginLocation::getPluginList() const +const std::list<std::string> &CPluginLocation::getPluginList() const { return _pluginList; } -bool CPluginLocation::fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) +bool CPluginLocation::fromXml(const CXmlElement &xmlElement, CXmlSerializingContext & /*ctx*/) { - (void) serializingContext; - // Retrieve folder - _strFolder = xmlElement.getAttributeString("Folder"); + xmlElement.getAttribute("Folder", _strFolder); // Get Info from children CXmlElement::CChildIterator childIterator(xmlElement); @@ -61,7 +59,7 @@ bool CPluginLocation::fromXml(const CXmlElement &xmlElement, CXmlSerializingCont while (childIterator.next(xmlPluginElement)) { // Fill Plugin List - _pluginList.push_back(xmlPluginElement.getAttributeString("Name")); + _pluginList.push_back(xmlPluginElement.getNameAttribute()); } // Don't dig diff --git a/parameter/PluginLocation.h b/parameter/PluginLocation.h index 3a8e131..2a663d2 100644 --- a/parameter/PluginLocation.h +++ b/parameter/PluginLocation.h @@ -36,19 +36,18 @@ class CPluginLocation : public CKindElement { public: - CPluginLocation(const std::string& strName, const std::string& strKind); + CPluginLocation(const std::string &strName, const std::string &strKind); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // Folder - const std::string& getFolder() const; + const std::string &getFolder() const; // Plugin list - const std::list<std::string>& getPluginList() const; + const std::list<std::string> &getPluginList() const; private: std::string _strFolder; std::list<std::string> _pluginList; - }; diff --git a/parameter/AutoLock.h b/parameter/Results.h index ab24a94..3f7a13c 100644 --- a/parameter/AutoLock.h +++ b/parameter/Results.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,22 +29,13 @@ */ #pragma once -#include <pthread.h> +#include <list> +#include <string> -class CAutoLock +namespace core { -public: - CAutoLock(pthread_mutex_t* pMutex) : _pMutex(pMutex) - { - pthread_mutex_lock(_pMutex); - } - ~CAutoLock() - { - pthread_mutex_unlock(_pMutex); - } - -private: - pthread_mutex_t* _pMutex; -}; +/** String list type which can hold list of error/info */ +typedef std::list<std::string> Results; +} /** core namespace */ diff --git a/parameter/Rule.h b/parameter/Rule.h index 42f420d..6affb26 100644 --- a/parameter/Rule.h +++ b/parameter/Rule.h @@ -40,10 +40,10 @@ class CRule : public CElement public: // Parse - virtual bool parse(CRuleParser& ruleParser, std::string& strError) = 0; + virtual bool parse(CRuleParser &ruleParser, std::string &strError) = 0; // Dump - virtual void dump(std::string& strResult) const = 0; + virtual std::string dump() const = 0; // Rule check virtual bool matches() const = 0; diff --git a/parameter/RuleParser.cpp b/parameter/RuleParser.cpp index e77b3c8..72424d2 100644 --- a/parameter/RuleParser.cpp +++ b/parameter/RuleParser.cpp @@ -30,27 +30,25 @@ #include "RuleParser.h" #include "CompoundRule.h" #include "SelectionCriterionRule.h" +#include "AlwaysAssert.hpp" #include <assert.h> using std::string; // Matches -const char* CRuleParser::_acDelimiters[CRuleParser::ENbStatuses] = { - "{", // EInit - "{} ", // EBeginCompoundRule - ",}", // EEndCompoundRule - ",}", // ECriterionRule - "{ ", // EContinue - "" // EDone +const char *CRuleParser::_acDelimiters[CRuleParser::ENbStatuses] = { + "{", // EInit + "{} ", // EBeginCompoundRule + ",}", // EEndCompoundRule + ",}", // ECriterionRule + "{ ", // EContinue + "" // EDone }; -CRuleParser::CRuleParser(const string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition) : - _strApplicationRule(strApplicationRule), - _pSelectionCriteriaDefinition(pSelectionCriteriaDefinition), - _uiCurrentPos(0), - _uiCurrentDeepness(0), - _eStatus(CRuleParser::EInit), - _pRootRule(NULL) +CRuleParser::CRuleParser(const string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition) + : _strApplicationRule(strApplicationRule), + _pSelectionCriteriaDefinition(pSelectionCriteriaDefinition) { } @@ -60,7 +58,7 @@ CRuleParser::~CRuleParser() } // Parse -bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) +bool CRuleParser::parse(CCompoundRule *pParentRule, string &strError) { while (true) { // Iterate till next relevant delimiter @@ -68,11 +66,11 @@ bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) return false; } - switch(_eStatus) { + switch (_eStatus) { case EBeginCompoundRule: { // Create new compound rule - CCompoundRule* pCompoundRule = new CCompoundRule; + CCompoundRule *pCompoundRule = new CCompoundRule; // Parse if (!pCompoundRule->parse(*this, strError)) { @@ -106,7 +104,7 @@ bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) break; case ECriterionRule: { // Create new criterion rule - CSelectionCriterionRule* pCriterionRule = new CSelectionCriterionRule; + CSelectionCriterionRule *pCriterionRule = new CSelectionCriterionRule; // Parse if (!pCriterionRule->parse(*this, strError)) { @@ -116,6 +114,7 @@ bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) return false; } + ALWAYS_ASSERT(pParentRule != NULL, "Invalid parent rule given to rule parser"); // Chain pParentRule->addChild(pCriterionRule); @@ -134,7 +133,6 @@ bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) return false; } - } default: assert(0); @@ -146,11 +144,11 @@ bool CRuleParser::parse(CCompoundRule* pParentRule, string& strError) } // Iterate -bool CRuleParser::iterate(string& strError) +bool CRuleParser::iterate(string &strError) { string::size_type delimiter; - assert(_uiCurrentPos <= _strApplicationRule.length()); + ALWAYS_ASSERT(_uiCurrentPos <= _strApplicationRule.length(), "Current Position outside range"); // Consume spaces if ((delimiter = _strApplicationRule.find_first_not_of(" ", _uiCurrentPos)) != string::npos) { @@ -160,20 +158,22 @@ bool CRuleParser::iterate(string& strError) } // Parse - if ((_uiCurrentPos != _strApplicationRule.length()) && ((delimiter = _strApplicationRule.find_first_of(_acDelimiters[_eStatus], _uiCurrentPos)) != string::npos)) { + if ((_uiCurrentPos != _strApplicationRule.length()) && + ((delimiter = _strApplicationRule.find_first_of(_acDelimiters[_eStatus], _uiCurrentPos)) != + string::npos)) { - switch(_strApplicationRule[delimiter]) { + switch (_strApplicationRule[delimiter]) { case '{': _eStatus = EBeginCompoundRule; // Extract type _strRuleType = _strApplicationRule.substr(_uiCurrentPos, delimiter - _uiCurrentPos); - _uiCurrentDeepness++; + _currentDeepness++; break; case '}': _eStatus = EEndCompoundRule; - if (!_uiCurrentDeepness--) { + if (!_currentDeepness--) { strError = "Missing opening brace"; @@ -193,7 +193,7 @@ bool CRuleParser::iterate(string& strError) _uiCurrentPos = delimiter + 1; } else { - if (_uiCurrentDeepness) { + if (_currentDeepness) { strError = "Missing closing brace"; @@ -214,21 +214,21 @@ bool CRuleParser::iterate(string& strError) } // Rule type -const string& CRuleParser::getType() const +const string &CRuleParser::getType() const { return _strRuleType; } // Criteria defintion -const CSelectionCriteriaDefinition* CRuleParser::getSelectionCriteriaDefinition() const +const CSelectionCriteriaDefinition *CRuleParser::getSelectionCriteriaDefinition() const { return _pSelectionCriteriaDefinition; } // Root rule -CCompoundRule* CRuleParser::grabRootRule() +CCompoundRule *CRuleParser::grabRootRule() { - CCompoundRule* pRootRule = _pRootRule; + CCompoundRule *pRootRule = _pRootRule; assert(pRootRule); @@ -238,7 +238,7 @@ CCompoundRule* CRuleParser::grabRootRule() } // Next word -bool CRuleParser::next(string& strNext, string& strError) +bool CRuleParser::next(string &strNext, string &strError) { string::size_type delimiter; diff --git a/parameter/RuleParser.h b/parameter/RuleParser.h index 803ea3e..74c1863 100644 --- a/parameter/RuleParser.h +++ b/parameter/RuleParser.h @@ -38,7 +38,8 @@ class CSelectionCriteriaDefinition; class CRuleParser { public: - enum Status { + enum Status + { EInit, EBeginCompoundRule, EEndCompoundRule, @@ -49,46 +50,46 @@ public: ENbStatuses }; - CRuleParser(const std::string& strApplicationRule, const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition); + CRuleParser(const std::string &strApplicationRule, + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition); ~CRuleParser(); // Parse - bool parse(CCompoundRule* pParentRule, std::string& strError); + bool parse(CCompoundRule *pParentRule, std::string &strError); // Iterate - bool iterate(std::string& strError); + bool iterate(std::string &strError); // Next word - bool next(std::string& strNext, std::string& strError); + bool next(std::string &strNext, std::string &strError); // Rule type - const std::string& getType() const; + const std::string &getType() const; // Criteria defintion - const CSelectionCriteriaDefinition* getSelectionCriteriaDefinition() const; + const CSelectionCriteriaDefinition *getSelectionCriteriaDefinition() const; // Root rule - CCompoundRule* grabRootRule(); -private: + CCompoundRule *grabRootRule(); - CRuleParser(const CRuleParser&); - CRuleParser& operator=(const CRuleParser&); +private: + CRuleParser(const CRuleParser &); + CRuleParser &operator=(const CRuleParser &); // Rule definition std::string _strApplicationRule; // Criteria defintion - const CSelectionCriteriaDefinition* _pSelectionCriteriaDefinition; + const CSelectionCriteriaDefinition *_pSelectionCriteriaDefinition; /** String iterator */ - std::string::size_type _uiCurrentPos; + std::string::size_type _uiCurrentPos{0}; // Deepness - uint32_t _uiCurrentDeepness; + size_t _currentDeepness{0}; // Current Type std::string _strRuleType; // Status - Status _eStatus; + Status _eStatus{EInit}; // Root rule - CCompoundRule* _pRootRule; + CCompoundRule *_pRootRule{nullptr}; // Matches - static const char* _acDelimiters[ENbStatuses]; + static const char *_acDelimiters[ENbStatuses]; }; - diff --git a/parameter/SelectionCriteria.cpp b/parameter/SelectionCriteria.cpp index 87ad76e..0939e60 100644 --- a/parameter/SelectionCriteria.cpp +++ b/parameter/SelectionCriteria.cpp @@ -45,26 +45,29 @@ std::string CSelectionCriteria::getKind() const } // Selection Criteria/Type creation -CSelectionCriterionType* CSelectionCriteria::createSelectionCriterionType(bool bIsInclusive) +CSelectionCriterionType *CSelectionCriteria::createSelectionCriterionType(bool bIsInclusive) { return getSelectionCriterionLibrary()->createSelectionCriterionType(bIsInclusive); } -CSelectionCriterion* CSelectionCriteria::createSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pSelectionCriterionType) +CSelectionCriterion *CSelectionCriteria::createSelectionCriterion( + const std::string &strName, const CSelectionCriterionType *pType, core::log::Logger &logger) { - return getSelectionCriteriaDefinition()->createSelectionCriterion(strName, pSelectionCriterionType); + return getSelectionCriteriaDefinition()->createSelectionCriterion(strName, pType, logger); } // Selection criterion retrieval -CSelectionCriterion* CSelectionCriteria::getSelectionCriterion(const std::string& strName) +CSelectionCriterion *CSelectionCriteria::getSelectionCriterion(const std::string &strName) { return getSelectionCriteriaDefinition()->getSelectionCriterion(strName); } // List available criteria -void CSelectionCriteria::listSelectionCriteria(std::list<std::string>& lstrResult, bool bWithTypeInfo, bool bHumanReadable) const +void CSelectionCriteria::listSelectionCriteria(std::list<std::string> &lstrResult, + bool bWithTypeInfo, bool bHumanReadable) const { - getSelectionCriteriaDefinition()->listSelectionCriteria(lstrResult, bWithTypeInfo, bHumanReadable); + getSelectionCriteriaDefinition()->listSelectionCriteria(lstrResult, bWithTypeInfo, + bHumanReadable); } // Reset the modified status of the children @@ -74,17 +77,18 @@ void CSelectionCriteria::resetModifiedStatus() } // Children access -CSelectionCriterionLibrary* CSelectionCriteria::getSelectionCriterionLibrary() +CSelectionCriterionLibrary *CSelectionCriteria::getSelectionCriterionLibrary() { - return static_cast<CSelectionCriterionLibrary*>(getChild(ESelectionCriterionLibrary)); + return static_cast<CSelectionCriterionLibrary *>(getChild(ESelectionCriterionLibrary)); } -CSelectionCriteriaDefinition* CSelectionCriteria::getSelectionCriteriaDefinition() +CSelectionCriteriaDefinition *CSelectionCriteria::getSelectionCriteriaDefinition() { - return static_cast<CSelectionCriteriaDefinition*>(getChild(ESelectionCriteriaDefinition)); + return static_cast<CSelectionCriteriaDefinition *>(getChild(ESelectionCriteriaDefinition)); } -const CSelectionCriteriaDefinition* CSelectionCriteria::getSelectionCriteriaDefinition() const +const CSelectionCriteriaDefinition *CSelectionCriteria::getSelectionCriteriaDefinition() const { - return static_cast<const CSelectionCriteriaDefinition*>(getChild(ESelectionCriteriaDefinition)); + return static_cast<const CSelectionCriteriaDefinition *>( + getChild(ESelectionCriteriaDefinition)); } diff --git a/parameter/SelectionCriteria.h b/parameter/SelectionCriteria.h index 122b8a2..22f4de1 100644 --- a/parameter/SelectionCriteria.h +++ b/parameter/SelectionCriteria.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -33,6 +33,7 @@ #include "Element.h" #include "SelectionCriterionType.h" #include "SelectionCriterion.h" +#include <log/Logger.h> #include <string> @@ -42,32 +43,38 @@ class ISelectionCriterionObserver; class CSelectionCriteria : public CElement { - enum ChildElementType { + enum ChildElementType + { ESelectionCriterionLibrary, ESelectionCriteriaDefinition }; + public: CSelectionCriteria(); // Selection Criteria/Type creation - CSelectionCriterionType* createSelectionCriterionType(bool bIsInclusive); - CSelectionCriterion* createSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pSelectionCriterionType); + CSelectionCriterionType *createSelectionCriterionType(bool bIsInclusive); + CSelectionCriterion *createSelectionCriterion(const std::string &strName, + const CSelectionCriterionType *pType, + core::log::Logger &logger); // Selection criterion retrieval - CSelectionCriterion* getSelectionCriterion(const std::string& strName); + CSelectionCriterion *getSelectionCriterion(const std::string &strName); // Selection Criterion definition - const CSelectionCriteriaDefinition* getSelectionCriteriaDefinition() const; + const CSelectionCriteriaDefinition *getSelectionCriteriaDefinition() const; // List available criteria - void listSelectionCriteria(std::list<std::string>& strResult, bool bWithTypeInfo, bool bHumanReadable) const; + void listSelectionCriteria(std::list<std::string> &strResult, bool bWithTypeInfo, + bool bHumanReadable) const; // Base virtual std::string getKind() const; // Reset the modified status of the children void resetModifiedStatus(); + private: // Children access - CSelectionCriterionLibrary* getSelectionCriterionLibrary(); - CSelectionCriteriaDefinition* getSelectionCriteriaDefinition(); + CSelectionCriterionLibrary *getSelectionCriterionLibrary(); + CSelectionCriteriaDefinition *getSelectionCriteriaDefinition(); }; diff --git a/parameter/SelectionCriteriaDefinition.cpp b/parameter/SelectionCriteriaDefinition.cpp index d7c4228..12f1aa2 100644 --- a/parameter/SelectionCriteriaDefinition.cpp +++ b/parameter/SelectionCriteriaDefinition.cpp @@ -30,19 +30,16 @@ #include "SelectionCriteriaDefinition.h" #include "SelectionCriterion.h" -CSelectionCriteriaDefinition::CSelectionCriteriaDefinition() -{ -} - std::string CSelectionCriteriaDefinition::getKind() const { return "SelectionCriteriaDefinition"; } // Selection Criterion creation -CSelectionCriterion* CSelectionCriteriaDefinition::createSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pSelectionCriterionType) +CSelectionCriterion *CSelectionCriteriaDefinition::createSelectionCriterion( + const std::string &strName, const CSelectionCriterionType *pType, core::log::Logger &logger) { - CSelectionCriterion* pSelectionCriterion = new CSelectionCriterion(strName, pSelectionCriterionType); + CSelectionCriterion *pSelectionCriterion = new CSelectionCriterion(strName, pType, logger); addChild(pSelectionCriterion); @@ -50,18 +47,21 @@ CSelectionCriterion* CSelectionCriteriaDefinition::createSelectionCriterion(cons } // Selection Criterion access -const CSelectionCriterion* CSelectionCriteriaDefinition::getSelectionCriterion(const std::string& strName) const +const CSelectionCriterion *CSelectionCriteriaDefinition::getSelectionCriterion( + const std::string &strName) const { - return static_cast<const CSelectionCriterion*>(findChild(strName)); + return static_cast<const CSelectionCriterion *>(findChild(strName)); } -CSelectionCriterion* CSelectionCriteriaDefinition::getSelectionCriterion(const std::string& strName) +CSelectionCriterion *CSelectionCriteriaDefinition::getSelectionCriterion(const std::string &strName) { - return static_cast<CSelectionCriterion*>(findChild(strName)); + return static_cast<CSelectionCriterion *>(findChild(strName)); } // List available criteria -void CSelectionCriteriaDefinition::listSelectionCriteria(std::list<std::string>& lstrResult, bool bWithTypeInfo, bool bHumanReadable) const +void CSelectionCriteriaDefinition::listSelectionCriteria(std::list<std::string> &lstrResult, + bool bWithTypeInfo, + bool bHumanReadable) const { // Propagate size_t uiNbChildren = getNbChildren(); @@ -69,9 +69,11 @@ void CSelectionCriteriaDefinition::listSelectionCriteria(std::list<std::string>& for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CSelectionCriterion* pSelectionCriterion = static_cast<const CSelectionCriterion*>(getChild(uiChild)); + const CSelectionCriterion *pSelectionCriterion = + static_cast<const CSelectionCriterion *>(getChild(uiChild)); - lstrResult.push_back(pSelectionCriterion->getFormattedDescription(bWithTypeInfo, bHumanReadable)); + lstrResult.push_back( + pSelectionCriterion->getFormattedDescription(bWithTypeInfo, bHumanReadable)); } } @@ -81,11 +83,11 @@ void CSelectionCriteriaDefinition::resetModifiedStatus() // Propagate size_t uiNbChildren = getNbChildren(); size_t uiChild; - CSelectionCriterion* pSelectionCriterion; + CSelectionCriterion *pSelectionCriterion; for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - pSelectionCriterion = static_cast<CSelectionCriterion*>(getChild(uiChild)); + pSelectionCriterion = static_cast<CSelectionCriterion *>(getChild(uiChild)); pSelectionCriterion->resetModifiedStatus(); } diff --git a/parameter/SelectionCriteriaDefinition.h b/parameter/SelectionCriteriaDefinition.h index 617b379..a8fa75a 100644 --- a/parameter/SelectionCriteriaDefinition.h +++ b/parameter/SelectionCriteriaDefinition.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,23 +31,25 @@ #include "Element.h" #include "SelectionCriterion.h" +#include <log/Logger.h> class ISelectionCriterionObserver; class CSelectionCriteriaDefinition : public CElement { public: - CSelectionCriteriaDefinition(); - // Selection Criterion creation - CSelectionCriterion* createSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pSelectionCriterionType); + CSelectionCriterion *createSelectionCriterion(const std::string &strName, + const CSelectionCriterionType *pType, + core::log::Logger &logger); // Selection Criterion access - const CSelectionCriterion* getSelectionCriterion(const std::string& strName) const; - CSelectionCriterion* getSelectionCriterion(const std::string& strName); + const CSelectionCriterion *getSelectionCriterion(const std::string &strName) const; + CSelectionCriterion *getSelectionCriterion(const std::string &strName); // List available criteria - void listSelectionCriteria(std::list<std::string>& lstrResult, bool bWithTypeInfo, bool bHumanReadable) const; + void listSelectionCriteria(std::list<std::string> &lstrResult, bool bWithTypeInfo, + bool bHumanReadable) const; // Base virtual std::string getKind() const; @@ -55,4 +57,3 @@ public: // Reset the modified status of the children void resetModifiedStatus(); }; - diff --git a/parameter/SelectionCriterion.cpp b/parameter/SelectionCriterion.cpp index e45c993..f99abec 100644 --- a/parameter/SelectionCriterion.cpp +++ b/parameter/SelectionCriterion.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,12 +29,17 @@ */ #include "SelectionCriterion.h" -#include "AutoLog.h" #include "Utility.h" +#include <log/Logger.h> #define base CElement -CSelectionCriterion::CSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pType) : base(strName), _iState(0), _pType(pType), _uiNbModifications(0) +using namespace core; + +CSelectionCriterion::CSelectionCriterion(const std::string &strName, + const CSelectionCriterionType *pType, + core::log::Logger &logger) + : base(strName), _pType(pType), _logger(logger) { } @@ -62,13 +67,17 @@ void CSelectionCriterion::setCriterionState(int iState) _iState = iState; - log_info("Selection criterion changed event: %s", getFormattedDescription(false, false).c_str()); + _logger.info() << "Selection criterion changed event: " + << getFormattedDescription(false, false); - // Check if the previous criterion value has been taken into account (i.e. at least one Configuration was applied + // Check if the previous criterion value has been taken into account (i.e. at least one + // Configuration was applied // since the last criterion change) if (_uiNbModifications != 0) { - log_warning("Selection criterion \"%s\" has been modified %d time(s) without any configuration application", getName().c_str(), _uiNbModifications); + _logger.warning() << "Selection criterion '" << getName() << "' has been modified " + << _uiNbModifications + << " time(s) without any configuration application"; } // Track the number of modifications for this criterion @@ -88,7 +97,7 @@ std::string CSelectionCriterion::getCriterionName() const } // Type -const ISelectionCriterionTypeInterface* CSelectionCriterion::getCriterionType() const +const ISelectionCriterionTypeInterface *CSelectionCriterion::getCriterionType() const { return _pType; } @@ -117,7 +126,8 @@ bool CSelectionCriterion::excludes(int iState) const } /// User request -std::string CSelectionCriterion::getFormattedDescription(bool bWithTypeInfo, bool bHumanReadable) const +std::string CSelectionCriterion::getFormattedDescription(bool bWithTypeInfo, + bool bHumanReadable) const { std::string strFormattedDescription; @@ -126,7 +136,7 @@ std::string CSelectionCriterion::getFormattedDescription(bool bWithTypeInfo, boo if (bWithTypeInfo) { // Display type info - CUtility::appendTitle(strFormattedDescription, getName() + ":"); + utility::appendTitle(strFormattedDescription, getName() + ":"); // States strFormattedDescription += "Possible states "; @@ -155,27 +165,26 @@ std::string CSelectionCriterion::getFormattedDescription(bool bWithTypeInfo, boo if (bWithTypeInfo) { // Type Kind strFormattedDescription += ", type kind: "; - strFormattedDescription += _pType->isTypeInclusive() ? "inclusive" : "exclusive"; + strFormattedDescription += _pType->isTypeInclusive() ? "inclusive" : "exclusive"; } // Current State - strFormattedDescription += ", current state: " + - _pType->getFormattedState(_iState); + strFormattedDescription += ", current state: " + _pType->getFormattedState(_iState); - if (bWithTypeInfo) { + if (bWithTypeInfo) { // States - strFormattedDescription += ", states: " + - _pType->listPossibleValues(); + strFormattedDescription += ", states: " + _pType->listPossibleValues(); } } return strFormattedDescription; } // XML export -void CSelectionCriterion::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CSelectionCriterion::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Current Value - xmlElement.setAttributeString("Value", _pType->getFormattedState(_iState)); + xmlElement.setAttribute("Value", _pType->getFormattedState(_iState)); // Serialize Type node _pType->toXml(xmlElement, serializingContext); diff --git a/parameter/SelectionCriterion.h b/parameter/SelectionCriterion.h index cf99035..76ec0ff 100644 --- a/parameter/SelectionCriterion.h +++ b/parameter/SelectionCriterion.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -32,13 +32,18 @@ #include "Element.h" #include "SelectionCriterionType.h" #include "SelectionCriterionInterface.h" +#include <log/Logger.h> +#include <NonCopyable.hpp> #include <string> -class CSelectionCriterion : public CElement, public ISelectionCriterionInterface +class CSelectionCriterion : public CElement, + public ISelectionCriterionInterface, + private utility::NonCopyable { public: - CSelectionCriterion(const std::string& strName, const CSelectionCriterionType* pType); + CSelectionCriterion(const std::string &strName, const CSelectionCriterionType *pType, + core::log::Logger &logger); /// From ISelectionCriterionInterface // State @@ -47,7 +52,7 @@ public: // Name virtual std::string getCriterionName() const; // Type - virtual const ISelectionCriterionTypeInterface* getCriterionType() const; + virtual const ISelectionCriterionTypeInterface *getCriterionType() const; // Modified status bool hasBeenModified() const; void resetModifiedStatus(); @@ -71,13 +76,17 @@ public: * @param[in] serializingContext The serializing context * */ - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; + private: // Current state - int _iState; + int _iState{0}; // Type - const CSelectionCriterionType* _pType; - // Counter to know how many modifications have been applied to this criterion - uint8_t _uiNbModifications; -}; + const CSelectionCriterionType *_pType; + /** Counter to know how many modifications have been applied to this criterion */ + uint32_t _uiNbModifications{0}; + + /** Application logger */ + core::log::Logger &_logger; +}; diff --git a/parameter/SelectionCriterionLibrary.cpp b/parameter/SelectionCriterionLibrary.cpp index 6910e41..fc9e943 100644 --- a/parameter/SelectionCriterionLibrary.cpp +++ b/parameter/SelectionCriterionLibrary.cpp @@ -31,19 +31,15 @@ #define base CElement -CSelectionCriterionLibrary::CSelectionCriterionLibrary() -{ -} - std::string CSelectionCriterionLibrary::getKind() const { return "SelectionCriterionLibrary"; } // Type creation -CSelectionCriterionType* CSelectionCriterionLibrary::createSelectionCriterionType(bool bIsInclusive) +CSelectionCriterionType *CSelectionCriterionLibrary::createSelectionCriterionType(bool bIsInclusive) { - CSelectionCriterionType* pSelectionCriterionType = new CSelectionCriterionType(bIsInclusive); + CSelectionCriterionType *pSelectionCriterionType = new CSelectionCriterionType(bIsInclusive); addChild(pSelectionCriterionType); diff --git a/parameter/SelectionCriterionLibrary.h b/parameter/SelectionCriterionLibrary.h index bb19777..a152258 100644 --- a/parameter/SelectionCriterionLibrary.h +++ b/parameter/SelectionCriterionLibrary.h @@ -35,10 +35,8 @@ class CSelectionCriterionLibrary : public CElement { public: - CSelectionCriterionLibrary(); - // Type creation - CSelectionCriterionType* createSelectionCriterionType(bool bIsInclusive); + CSelectionCriterionType *createSelectionCriterionType(bool bIsInclusive); // CElement virtual std::string getKind() const; diff --git a/parameter/SelectionCriterionRule.cpp b/parameter/SelectionCriterionRule.cpp index c376bb3..8c22045 100644 --- a/parameter/SelectionCriterionRule.cpp +++ b/parameter/SelectionCriterionRule.cpp @@ -40,16 +40,9 @@ using std::string; -const CSelectionCriterionRule::SMatchingRuleDescription CSelectionCriterionRule::_astMatchesWhen[CSelectionCriterionRule::ENbMatchesWhen] = { - { "Is", true }, - { "IsNot", true }, - { "Includes", false }, - { "Excludes", false } -}; - -CSelectionCriterionRule::CSelectionCriterionRule() : _pSelectionCriterion(NULL), _eMatchesWhen(CSelectionCriterionRule::EIs), _iMatchValue(0) -{ -} +const CSelectionCriterionRule::SMatchingRuleDescription + CSelectionCriterionRule::_astMatchesWhen[CSelectionCriterionRule::ENbMatchesWhen] = { + {"Is", true}, {"IsNot", true}, {"Includes", false}, {"Excludes", false}}; // Class kind string CSelectionCriterionRule::getKind() const @@ -58,19 +51,18 @@ string CSelectionCriterionRule::getKind() const } // Content dumping -void CSelectionCriterionRule::logValue(string& strValue, CErrorContext& errorContext) const +string CSelectionCriterionRule::logValue(utility::ErrorContext & /*cxt*/) const { - (void)errorContext; - // Dump rule - dump(strValue); + return dump(); } // Parse -bool CSelectionCriterionRule::parse(CRuleParser& ruleParser, string& strError) +bool CSelectionCriterionRule::parse(CRuleParser &ruleParser, string &strError) { // Criterion - _pSelectionCriterion = ruleParser.getSelectionCriteriaDefinition()->getSelectionCriterion(ruleParser.getType()); + _pSelectionCriterion = + ruleParser.getSelectionCriteriaDefinition()->getSelectionCriterion(ruleParser.getType()); // Check existence if (!_pSelectionCriterion) { @@ -116,18 +108,15 @@ bool CSelectionCriterionRule::parse(CRuleParser& ruleParser, string& strError) } // Dump -void CSelectionCriterionRule::dump(string& strResult) const +string CSelectionCriterionRule::dump() const { - // Criterion - strResult += _pSelectionCriterion->getName(); - strResult += " "; - // Verb - strResult += _astMatchesWhen[_eMatchesWhen].pcMatchesWhen; - strResult += " "; // Value - string strValue; - _pSelectionCriterion->getCriterionType()->getLiteralValue(_iMatchValue, strValue); - strResult += strValue; + string value; + _pSelectionCriterion->getCriterionType()->getLiteralValue(_iMatchValue, value); + + // "<Name> <Verb> <Value>" + return string(_pSelectionCriterion->getName()) + " " + + _astMatchesWhen[_eMatchesWhen].pcMatchesWhen + " " + value; } // Rule check @@ -135,7 +124,7 @@ bool CSelectionCriterionRule::matches() const { assert(_pSelectionCriterion); - switch(_eMatchesWhen) { + switch (_eMatchesWhen) { case EIs: return _pSelectionCriterion->is(_iMatchValue); case EIsNot: @@ -151,41 +140,52 @@ bool CSelectionCriterionRule::matches() const } // From IXmlSink -bool CSelectionCriterionRule::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CSelectionCriterionRule::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Retrieve actual context - CXmlDomainImportContext& xmlDomainImportContext = static_cast<CXmlDomainImportContext&>(serializingContext); + CXmlDomainImportContext &xmlDomainImportContext = + static_cast<CXmlDomainImportContext &>(serializingContext); // Get selection criterion - string strSelectionCriterion = xmlElement.getAttributeString("SelectionCriterion"); + string strSelectionCriterion; + xmlElement.getAttribute("SelectionCriterion", strSelectionCriterion); - _pSelectionCriterion = xmlDomainImportContext.getSelectionCriteriaDefinition()->getSelectionCriterion(strSelectionCriterion); + _pSelectionCriterion = + xmlDomainImportContext.getSelectionCriteriaDefinition()->getSelectionCriterion( + strSelectionCriterion); // Check existence if (!_pSelectionCriterion) { - xmlDomainImportContext.setError("Couldn't find selection criterion " + strSelectionCriterion + " in " + getKind() + " " + xmlElement.getPath()); + xmlDomainImportContext.setError("Couldn't find selection criterion " + + strSelectionCriterion + " in " + getKind() + " " + + xmlElement.getPath()); return false; } // Get MatchesWhen - string strMatchesWhen = xmlElement.getAttributeString("MatchesWhen"); + string strMatchesWhen; + xmlElement.getAttribute("MatchesWhen", strMatchesWhen); string strError; if (!setMatchesWhen(strMatchesWhen, strError)) { - xmlDomainImportContext.setError("Wrong MatchesWhen attribute " + strMatchesWhen + " in " + getKind() + " " + xmlElement.getPath() + ": " + strError); + xmlDomainImportContext.setError("Wrong MatchesWhen attribute " + strMatchesWhen + " in " + + getKind() + " " + xmlElement.getPath() + ": " + strError); return false; } // Get Value - string strValue = xmlElement.getAttributeString("Value"); + string strValue; + xmlElement.getAttribute("Value", strValue); if (!_pSelectionCriterion->getCriterionType()->getNumericalValue(strValue, _iMatchValue)) { - xmlDomainImportContext.setError("Wrong Value attribute value " + strValue + " in " + getKind() + " " + xmlElement.getPath()); + xmlDomainImportContext.setError("Wrong Value attribute value " + strValue + " in " + + getKind() + " " + xmlElement.getPath()); return false; } @@ -195,44 +195,42 @@ bool CSelectionCriterionRule::fromXml(const CXmlElement& xmlElement, CXmlSeriali } // From IXmlSource -void CSelectionCriterionRule::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CSelectionCriterionRule::toXml(CXmlElement &xmlElement, CXmlSerializingContext & /*ctx*/) const { - (void)serializingContext; - assert(_pSelectionCriterion); // Set selection criterion - xmlElement.setAttributeString("SelectionCriterion", _pSelectionCriterion->getName()); + xmlElement.setAttribute("SelectionCriterion", _pSelectionCriterion->getName()); // Set MatchesWhen - xmlElement.setAttributeString("MatchesWhen", _astMatchesWhen[_eMatchesWhen].pcMatchesWhen); + xmlElement.setAttribute("MatchesWhen", _astMatchesWhen[_eMatchesWhen].pcMatchesWhen); // Set Value string strValue; - _pSelectionCriterion->getCriterionType()->getLiteralValue(_iMatchValue, strValue); + _pSelectionCriterion->getCriterionType()->getLiteralValue(_iMatchValue, strValue); - xmlElement.setAttributeString("Value", strValue); + xmlElement.setAttribute("Value", strValue); } // XML MatchesWhen attribute parsing -bool CSelectionCriterionRule::setMatchesWhen(const string& strMatchesWhen, string& strError) +bool CSelectionCriterionRule::setMatchesWhen(const string &strMatchesWhen, string &strError) { - uint32_t uiMatchesWhen; - - for (uiMatchesWhen = 0; uiMatchesWhen < ENbMatchesWhen; uiMatchesWhen++) { + for (size_t matchesWhen = 0; matchesWhen < ENbMatchesWhen; matchesWhen++) { - const SMatchingRuleDescription* pstMatchingRuleDescription = &_astMatchesWhen[uiMatchesWhen]; + const SMatchingRuleDescription *pstMatchingRuleDescription = &_astMatchesWhen[matchesWhen]; if (strMatchesWhen == pstMatchingRuleDescription->pcMatchesWhen) { // Found it! // Get Type - const ISelectionCriterionTypeInterface* pSelectionCriterionType = _pSelectionCriterion->getCriterionType(); + const ISelectionCriterionTypeInterface *pSelectionCriterionType = + _pSelectionCriterion->getCriterionType(); // Check compatibility if relevant - if (!pSelectionCriterionType->isTypeInclusive() && !pstMatchingRuleDescription->bExclusiveTypeCompatible) { + if (!pSelectionCriterionType->isTypeInclusive() && + !pstMatchingRuleDescription->bExclusiveTypeCompatible) { strError = "Value incompatible with exclusive kind of type"; @@ -240,7 +238,7 @@ bool CSelectionCriterionRule::setMatchesWhen(const string& strMatchesWhen, strin } // Store - _eMatchesWhen = (MatchesWhen)uiMatchesWhen; + _eMatchesWhen = (MatchesWhen)matchesWhen; return true; } diff --git a/parameter/SelectionCriterionRule.h b/parameter/SelectionCriterionRule.h index 70bddc2..c51bfa2 100644 --- a/parameter/SelectionCriterionRule.h +++ b/parameter/SelectionCriterionRule.h @@ -38,7 +38,8 @@ class CSelectionCriterion; class CSelectionCriterionRule : public CRule { // Matching rules - enum MatchesWhen { + enum MatchesWhen + { EIs, EIsNot, EIncludes, @@ -49,47 +50,46 @@ class CSelectionCriterionRule : public CRule // Matching rule description struct SMatchingRuleDescription { - const char* pcMatchesWhen; + const char *pcMatchesWhen; bool bExclusiveTypeCompatible; }; public: - CSelectionCriterionRule(); - // Parse - virtual bool parse(CRuleParser& ruleParser, std::string& strError); + virtual bool parse(CRuleParser &ruleParser, std::string &strError); // Dump - virtual void dump(std::string& strResult) const; + std::string dump() const override; // Rule check virtual bool matches() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // Class kind virtual std::string getKind() const; + protected: // Content dumping - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; + std::string logValue(utility::ErrorContext &errorContext) const override; + private: // XML MatchesWhen attribute parsing - bool setMatchesWhen(const std::string& strMatchesWhen, std::string& strError); + bool setMatchesWhen(const std::string &strMatchesWhen, std::string &strError); // Selection criterion - const CSelectionCriterion* _pSelectionCriterion; + const CSelectionCriterion *_pSelectionCriterion{nullptr}; // MatchesWhen - MatchesWhen _eMatchesWhen; + MatchesWhen _eMatchesWhen{EIs}; // Value - int32_t _iMatchValue; + int32_t _iMatchValue{0}; // Used for XML MatchesWhen attribute parsing static const SMatchingRuleDescription _astMatchesWhen[ENbMatchesWhen]; }; - diff --git a/parameter/SelectionCriterionType.cpp b/parameter/SelectionCriterionType.cpp index ce633c6..3354702 100644 --- a/parameter/SelectionCriterionType.cpp +++ b/parameter/SelectionCriterionType.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,6 +29,8 @@ */ #include "SelectionCriterionType.h" #include "Tokenizer.h" +#include <sstream> +#include <climits> #define base CElement @@ -49,12 +51,16 @@ std::string CSelectionCriterionType::getKind() const } // From ISelectionCriterionTypeInterface -bool CSelectionCriterionType::addValuePair(int iValue, const std::string& strValue) +bool CSelectionCriterionType::addValuePair(int iValue, const std::string &strValue, + std::string &strError) { // Check 1 bit set only for inclusive types if (_bInclusive && (!iValue || (iValue & (iValue - 1)))) { - log_warning("Rejecting value pair association: 0x%X - %s for Selection Criterion Type %s", iValue, strValue.c_str(), getName().c_str()); + std::ostringstream error; + error << "Rejecting value pair association: 0x" << std::hex << iValue << " - " << strValue + << " for Selection Criterion Type " << getName(); + strError = error.str(); return false; } @@ -62,16 +68,29 @@ bool CSelectionCriterionType::addValuePair(int iValue, const std::string& strVal // Check already inserted if (_numToLitMap.find(strValue) != _numToLitMap.end()) { - log_warning("Rejecting value pair association (literal already present): 0x%X - %s for Selection Criterion Type %s", iValue, strValue.c_str(), getName().c_str()); + std::ostringstream error; + error << "Rejecting value pair association (literal already present): 0x" << std::hex + << iValue << " - " << strValue << " for Selection Criterion Type " << getName(); + strError = error.str(); return false; } + for (NumToLitMapConstIt it = _numToLitMap.begin(); it != _numToLitMap.end(); ++it) { + if (it->second == iValue) { + std::ostringstream error; + error << "Rejecting value pair association (numerical already present):" + << " 0x" << std::hex << iValue << " - " << strValue + << " for Selection Criterion Type " << getName(); + strError = error.str(); + return false; + } + } _numToLitMap[strValue] = iValue; return true; } -bool CSelectionCriterionType::getNumericalValue(const std::string& strValue, int& iValue) const +bool CSelectionCriterionType::getNumericalValue(const std::string &strValue, int &iValue) const { if (_bInclusive) { @@ -96,7 +115,8 @@ bool CSelectionCriterionType::getNumericalValue(const std::string& strValue, int return getAtomicNumericalValue(strValue, iValue); } -bool CSelectionCriterionType::getAtomicNumericalValue(const std::string& strValue, int& iValue) const +bool CSelectionCriterionType::getAtomicNumericalValue(const std::string &strValue, + int &iValue) const { NumToLitMapConstIt it = _numToLitMap.find(strValue); @@ -109,7 +129,7 @@ bool CSelectionCriterionType::getAtomicNumericalValue(const std::string& strValu return false; } -bool CSelectionCriterionType::getLiteralValue(int iValue, std::string& strValue) const +bool CSelectionCriterionType::getLiteralValue(int iValue, std::string &strValue) const { NumToLitMapConstIt it; @@ -163,12 +183,11 @@ std::string CSelectionCriterionType::getFormattedState(int iValue) const if (_bInclusive) { // Need to go through all set bit - uint32_t uiBit; bool bFirst = true; - for (uiBit = 0; uiBit < sizeof(iValue) * 8; uiBit++) { + for (size_t bit = 0; bit < sizeof(iValue) * CHAR_BIT; bit++) { - int iSingleBitValue = iValue & (1 << uiBit); + int iSingleBitValue = iValue & (1 << bit); // Check if current bit is set if (!iSingleBitValue) { @@ -209,10 +228,11 @@ std::string CSelectionCriterionType::getFormattedState(int iValue) const } // From IXmlSource -void CSelectionCriterionType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CSelectionCriterionType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // Type Kind - xmlElement.setAttributeString("Kind", isTypeInclusive() ? "Inclusive" : "Exclusive"); + xmlElement.setAttribute("Kind", isTypeInclusive() ? "Inclusive" : "Exclusive"); // Value pairs as children NumToLitMapConstIt it; @@ -223,9 +243,9 @@ void CSelectionCriterionType::toXml(CXmlElement& xmlElement, CXmlSerializingCont xmlElement.createChild(childValuePairElement, "ValuePair"); // Literal - childValuePairElement.setAttributeString("Literal", it->first); + childValuePairElement.setAttribute("Literal", it->first); // Numerical - childValuePairElement.setAttributeSignedInteger("Numerical", it->second); + childValuePairElement.setAttribute("Numerical", it->second); } base::toXml(xmlElement, serializingContext); diff --git a/parameter/SelectionCriterionType.h b/parameter/SelectionCriterionType.h index ef4176a..5c13c8f 100644 --- a/parameter/SelectionCriterionType.h +++ b/parameter/SelectionCriterionType.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -42,7 +42,7 @@ public: CSelectionCriterionType(bool bIsInclusive); // From ISelectionCriterionTypeInterface - virtual bool addValuePair(int iValue, const std::string& strValue); + virtual bool addValuePair(int iValue, const std::string &strValue, std::string &strError); /** * Retrieve the numerical value from the std::string representation of the criterion type. * @@ -53,8 +53,8 @@ public: * * @return true if integer value retrieved from the std::string one, false otherwise. */ - virtual bool getNumericalValue(const std::string& strValue, int& iValue) const; - virtual bool getLiteralValue(int iValue, std::string& strValue) const; + virtual bool getNumericalValue(const std::string &strValue, int &iValue) const; + virtual bool getLiteralValue(int iValue, std::string &strValue) const; virtual bool isTypeInclusive() const; // Value list @@ -70,10 +70,11 @@ public: * @param[in] serializingContext The serializing context * */ - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // From CElement virtual std::string getKind() const; + private: /** * Retrieve the numerical value from the std::string representation of the criterion type. @@ -84,10 +85,9 @@ private: * * @return true if integer value retrieved from the std::string one, false otherwise. */ - bool getAtomicNumericalValue(const std::string& strValue, int& iValue) const; + bool getAtomicNumericalValue(const std::string &strValue, int &iValue) const; bool _bInclusive; std::map<std::string, int> _numToLitMap; static const std::string _strDelimiter; /**< Inclusive criterion type delimiter. */ }; - diff --git a/parameter/SimulatedBackSynchronizer.cpp b/parameter/SimulatedBackSynchronizer.cpp index 5f60aba..ca48ae3 100644 --- a/parameter/SimulatedBackSynchronizer.cpp +++ b/parameter/SimulatedBackSynchronizer.cpp @@ -32,7 +32,8 @@ #define base CBackSynchronizer -CSimulatedBackSynchronizer::CSimulatedBackSynchronizer(const CConfigurableElement* pConfigurableElement, CParameterBlackboard* pParameterBlackboard) +CSimulatedBackSynchronizer::CSimulatedBackSynchronizer( + const CConfigurableElement *pConfigurableElement, CParameterBlackboard *pParameterBlackboard) : base(pConfigurableElement), _parameterAccessContext(_strError) { _parameterAccessContext.setParameterBlackboard(pParameterBlackboard); @@ -42,11 +43,11 @@ CSimulatedBackSynchronizer::CSimulatedBackSynchronizer(const CConfigurableElemen void CSimulatedBackSynchronizer::sync() { // Set default values to simulate back synchronization - std::list<const CConfigurableElement*>::const_iterator it; + std::list<const CConfigurableElement *>::const_iterator it; for (it = _needingBackSyncList.begin(); it != _needingBackSyncList.end(); ++it) { - const CConfigurableElement* pConfigurableElement = *it; + const CConfigurableElement *pConfigurableElement = *it; pConfigurableElement->setDefaultValues(_parameterAccessContext); } diff --git a/parameter/SimulatedBackSynchronizer.h b/parameter/SimulatedBackSynchronizer.h index 6acf090..f561b89 100644 --- a/parameter/SimulatedBackSynchronizer.h +++ b/parameter/SimulatedBackSynchronizer.h @@ -39,14 +39,15 @@ class CParameterBlackboard; class CSimulatedBackSynchronizer : public CBackSynchronizer { public: - CSimulatedBackSynchronizer(const CConfigurableElement* pConfigurableElement, CParameterBlackboard* pParameterBlackboard); + CSimulatedBackSynchronizer(const CConfigurableElement *pConfigurableElement, + CParameterBlackboard *pParameterBlackboard); // Back synchronization virtual void sync(); + private: // Fake error for parameter context creation std::string _strError; // Parameter context CParameterAccessContext _parameterAccessContext; }; - diff --git a/parameter/StringParameter.cpp b/parameter/StringParameter.cpp index 8ba5b16..0651bf6 100644 --- a/parameter/StringParameter.cpp +++ b/parameter/StringParameter.cpp @@ -37,7 +37,8 @@ using std::string; -CStringParameter::CStringParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement) +CStringParameter::CStringParameter(const string &strName, const CTypeElement *pTypeElement) + : base(strName, pTypeElement) { } @@ -46,44 +47,48 @@ CInstanceConfigurableElement::Type CStringParameter::getType() const return EStringParameter; } -uint32_t CStringParameter::getFootPrint() const +size_t CStringParameter::getFootPrint() const { return getSize(); } -uint32_t CStringParameter::getSize() const +size_t CStringParameter::getSize() const { - return static_cast<const CStringParameterType*>(getTypeElement())->getMaxLength() + 1; + return static_cast<const CStringParameterType *>(getTypeElement())->getMaxLength() + 1; } // Used for simulation and virtual subsystems -void CStringParameter::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CStringParameter::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); pBlackboard->writeString("", getOffset()); } // Actual parameter access (tuning) -bool CStringParameter::doSetValue(const string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +bool CStringParameter::doSetValue(const string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { if (strValue.length() >= getSize()) { - - parameterAccessContext.setError("Maximum length exceeded"); + using std::to_string; + parameterAccessContext.setError("Can not set a string of length " + + to_string(strValue.length()) + ": maximum length is " + + std::to_string(getSize() - 1)); return false; } // Write blackboard - CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard(); + CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard(); - pBlackboard->writeString(strValue, uiOffset); + pBlackboard->writeString(strValue, offset); return true; } -void CStringParameter::doGetValue(string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const +void CStringParameter::doGetValue(string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const { - parameterAccessContext.getParameterBlackboard()->readString(strValue, uiOffset); + parameterAccessContext.getParameterBlackboard()->readString(strValue, offset); } diff --git a/parameter/StringParameter.h b/parameter/StringParameter.h index 6a60e9f..6adede9 100644 --- a/parameter/StringParameter.h +++ b/parameter/StringParameter.h @@ -36,22 +36,24 @@ class CStringParameter : public CBaseParameter { public: - CStringParameter(const std::string& strName, const CTypeElement* pTypeElement); + CStringParameter(const std::string &strName, const CTypeElement *pTypeElement); // Instantiation, allocation - virtual uint32_t getFootPrint() const; + virtual size_t getFootPrint() const; // Type virtual Type getType() const; + protected: // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; // Actual value access (tuning) - virtual bool doSetValue(const std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; - virtual void doGetValue(std::string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const; + virtual bool doSetValue(const std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; + virtual void doGetValue(std::string &strValue, size_t offset, + CParameterAccessContext ¶meterAccessContext) const; // Size - uint32_t getSize() const; + size_t getSize() const; }; - diff --git a/parameter/StringParameterType.cpp b/parameter/StringParameterType.cpp index 321dc97..df9230d 100644 --- a/parameter/StringParameterType.cpp +++ b/parameter/StringParameterType.cpp @@ -35,7 +35,7 @@ using std::string; -CStringParameterType::CStringParameterType(const string& strName) : base(strName), _uiMaxLength(0) +CStringParameterType::CStringParameterType(const string &strName) : base(strName) { } @@ -46,42 +46,44 @@ string CStringParameterType::getKind() const } // Element properties -void CStringParameterType::showProperties(string& strResult) const +void CStringParameterType::showProperties(string &strResult) const { base::showProperties(strResult); // Max length strResult += "Max length: "; - strResult += CUtility::toString(_uiMaxLength); + strResult += std::to_string(_maxLength); strResult += "\n"; } // From IXmlSink -bool CStringParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CStringParameterType::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // MaxLength - _uiMaxLength = xmlElement.getAttributeInteger("MaxLength"); + xmlElement.getAttribute("MaxLength", _maxLength); // Base return base::fromXml(xmlElement, serializingContext); } -CInstanceConfigurableElement* CStringParameterType::doInstantiate() const +CInstanceConfigurableElement *CStringParameterType::doInstantiate() const { return new CStringParameter(getName(), this); } // Max length -uint32_t CStringParameterType::getMaxLength() const +size_t CStringParameterType::getMaxLength() const { - return _uiMaxLength; + return _maxLength; } // From IXmlSource -void CStringParameterType::toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const +void CStringParameterType::toXml(CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) const { // MaxLength - xmlElement.setAttributeInteger("MaxLength", _uiMaxLength); + xmlElement.setAttribute("MaxLength", _maxLength); base::toXml(xmlElement, serializingContext); } diff --git a/parameter/StringParameterType.h b/parameter/StringParameterType.h index e1b2513..9d8786f 100644 --- a/parameter/StringParameterType.h +++ b/parameter/StringParameterType.h @@ -38,26 +38,27 @@ class CStringParameterType : public CTypeElement { public: - CStringParameterType(const std::string& strName); + CStringParameterType(const std::string &strName); // Max length - uint32_t getMaxLength() const; + size_t getMaxLength() const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // CElement virtual std::string getKind() const; + private: // Instantiation - virtual CInstanceConfigurableElement* doInstantiate() const; + virtual CInstanceConfigurableElement *doInstantiate() const; // Max length in bytes - uint32_t _uiMaxLength; + size_t _maxLength{0}; }; diff --git a/parameter/Subsystem.cpp b/parameter/Subsystem.cpp index 6b0264b..43e633d 100644 --- a/parameter/Subsystem.cpp +++ b/parameter/Subsystem.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -35,17 +35,17 @@ #include "ConfigurationAccessContext.h" #include "SubsystemObjectCreator.h" #include "MappingData.h" -#include "Utility.h" #include <assert.h> #include <sstream> -#define base CConfigurableElementWithMapping +#define base CConfigurableElement using std::string; using std::list; -using std::ostringstream; -CSubsystem::CSubsystem(const string& strName) : base(strName), _pComponentLibrary(new CComponentLibrary), _pInstanceDefinition(new CInstanceDefinition), _bBigEndian(false), _pMappingData(NULL) +CSubsystem::CSubsystem(const string &strName, core::log::Logger &logger) + : base(strName), _pComponentLibrary(new CComponentLibrary), + _pInstanceDefinition(new CInstanceDefinition), _logger(logger) { // Note: A subsystem contains instance components // InstanceDefintion and ComponentLibrary objects are then not chosen to be children @@ -54,20 +54,17 @@ CSubsystem::CSubsystem(const string& strName) : base(strName), _pComponentLibrar CSubsystem::~CSubsystem() { - // Remove subsystem objects - SubsystemObjectListIterator subsystemObjectIt; + // FIXME use unique_ptr, would make this method empty - for (subsystemObjectIt = _subsystemObjectList.begin(); subsystemObjectIt != _subsystemObjectList.end(); ++subsystemObjectIt) { + for (auto *subsystemObject : _subsystemObjectList) { - delete *subsystemObjectIt; + delete subsystemObject; } // Remove susbsystem creators - uint32_t uiIndex; + for (auto *subsystemObjectCreator : _subsystemObjectCreatorArray) { - for (uiIndex = 0; uiIndex < _subsystemObjectCreatorArray.size(); uiIndex++) { - - delete _subsystemObjectCreatorArray[uiIndex]; + delete subsystemObjectCreator; } // Order matters! @@ -82,12 +79,6 @@ string CSubsystem::getKind() const return "Subsystem"; } -// Susbsystem Endianness -bool CSubsystem::isBigEndian() const -{ - return _bBigEndian; -} - // Susbsystem sanity bool CSubsystem::isAlive() const { @@ -95,22 +86,23 @@ bool CSubsystem::isAlive() const } // Resynchronization after subsystem restart needed -bool CSubsystem::needResync(bool bClear) +bool CSubsystem::needResync(bool /*bClear*/) { - (void)bClear; - return false; } -// From IXmlSink -bool CSubsystem::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CSubsystem::structureFromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Subsystem class does not rely on generic fromXml algorithm of Element class. // So, setting here the description if found as XML attribute. - setDescription(getXmlDescriptionAttribute(xmlElement)); + string description; + xmlElement.getAttribute(gDescriptionPropertyName, description); + setDescription(description); // Context - CXmlParameterSerializingContext& parameterBuildContext = static_cast<CXmlParameterSerializingContext&>(serializingContext); + CXmlParameterSerializingContext ¶meterBuildContext = + static_cast<CXmlParameterSerializingContext &>(serializingContext); // Install temporary component library for further component creation parameterBuildContext.setComponentLibrary(_pComponentLibrary); @@ -118,11 +110,16 @@ bool CSubsystem::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& CXmlElement childElement; // Manage mapping attribute - if (xmlElement.hasAttribute("Mapping")) { + string rawMapping; + xmlElement.getAttribute("Mapping", rawMapping); + if (!rawMapping.empty()) { + std::string error; _pMappingData = new CMappingData; - if (!_pMappingData->fromXml(xmlElement, serializingContext)) { + if (!_pMappingData->init(rawMapping, error)) { + serializingContext.setError("Invalid Mapping data from XML element '" + + xmlElement.getPath() + "': " + error); return false; } } @@ -154,23 +151,10 @@ bool CSubsystem::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& return false; } - // Endianness - _bBigEndian = xmlElement.getAttributeBoolean("Endianness", "Big"); - return true; } -// XML configuration settings parsing -bool CSubsystem::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const -{ - // Fix Endianness - configurationAccessContext.setBigEndianSubsystem(_bBigEndian); - - return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, configurationAccessContext); -} - - -bool CSubsystem::mapSubsystemElements(string& strError) +bool CSubsystem::mapSubsystemElements(string &strError) { // Default mapping context CMappingContext context(_contextMappingKeyArray.size()); @@ -180,12 +164,12 @@ bool CSubsystem::mapSubsystemElements(string& strError) _contextStack.push(context); // Map all instantiated subelements in subsystem - size_t uiNbChildren = getNbChildren(); - size_t uiChild; + size_t nbChildren = getNbChildren(); - for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { + for (size_t child = 0; child < nbChildren; child++) { - CInstanceConfigurableElement* pInstanceConfigurableChildElement = static_cast<CInstanceConfigurableElement*>(getChild(uiChild)); + CInstanceConfigurableElement *pInstanceConfigurableChildElement = + static_cast<CInstanceConfigurableElement *>(getChild(child)); if (!pInstanceConfigurableChildElement->map(*this, strError)) { @@ -195,70 +179,61 @@ bool CSubsystem::mapSubsystemElements(string& strError) return true; } -// Parameter access -bool CSubsystem::accessValue(CPathNavigator& pathNavigator, string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const -{ - // Deal with Endianness - parameterAccessContext.setBigEndianSubsystem(_bBigEndian); - - return base::accessValue(pathNavigator, strValue, bSet, parameterAccessContext); -} - // Formats the mapping of the ConfigurableElements string CSubsystem::formatMappingDataList( - const list<const CConfigurableElement*>& configurableElementPath) const + const list<const CConfigurableElement *> &configurableElementPath) const { // The list is parsed in reverse order because it has been filled from the leaf to the trunk // of the tree. When formatting the mapping, we want to start from the subsystem level - ostringstream ossStream; - list<const CConfigurableElement*>::const_reverse_iterator it; + std::list<string> mappings; + list<const CConfigurableElement *>::const_reverse_iterator it; for (it = configurableElementPath.rbegin(); it != configurableElementPath.rend(); ++it) { - const CInstanceConfigurableElement* pInstanceConfigurableElement = - static_cast<const CInstanceConfigurableElement*>(*it); - - ossStream << pInstanceConfigurableElement->getFormattedMapping() << ", "; + auto maybeMapping = (*it)->getFormattedMapping(); + if (not maybeMapping.empty()) { + mappings.push_back(maybeMapping); + } } - return ossStream.str(); + + return utility::asString(mappings, ", "); } // Find the CSubystemObject containing a specific CInstanceConfigurableElement -const CSubsystemObject* CSubsystem::findSubsystemObjectFromConfigurableElement( - const CInstanceConfigurableElement* pInstanceConfigurableElement) const { - - const CSubsystemObject* pSubsystemObject = NULL; +const CSubsystemObject *CSubsystem::findSubsystemObjectFromConfigurableElement( + const CInstanceConfigurableElement *pInstanceConfigurableElement) const +{ - list<CSubsystemObject*>::const_iterator it; + list<CSubsystemObject *>::const_iterator it; for (it = _subsystemObjectList.begin(); it != _subsystemObjectList.end(); ++it) { // Check if one of the SubsystemObjects is associated with a ConfigurableElement // corresponding to the expected one - pSubsystemObject = *it; + const CSubsystemObject *pSubsystemObject = *it; + if (pSubsystemObject->getConfigurableElement() == pInstanceConfigurableElement) { - break; + return pSubsystemObject; } } - return pSubsystemObject; + return nullptr; } void CSubsystem::findSubsystemLevelMappingKeyValue( - const CInstanceConfigurableElement* pInstanceConfigurableElement, - string& strMappingKey, - string& strMappingValue) const + const CInstanceConfigurableElement *pInstanceConfigurableElement, string &strMappingKey, + string &strMappingValue) const { // Find creator to get key name - std::vector<CSubsystemObjectCreator*>::const_iterator it; - for (it = _subsystemObjectCreatorArray.begin(); - it != _subsystemObjectCreatorArray.end(); ++it) { + std::vector<CSubsystemObjectCreator *>::const_iterator it; + for (it = _subsystemObjectCreatorArray.begin(); it != _subsystemObjectCreatorArray.end(); + ++it) { - const CSubsystemObjectCreator* pSubsystemObjectCreator = *it; + const CSubsystemObjectCreator *pSubsystemObjectCreator = *it; strMappingKey = pSubsystemObjectCreator->getMappingKey(); // Check if the ObjectCreator MappingKey corresponds to the element mapping data - const string* pStrValue; + const string *pStrValue; if (pInstanceConfigurableElement->getMappingData(strMappingKey, pStrValue)) { strMappingValue = *pStrValue; @@ -270,11 +245,11 @@ void CSubsystem::findSubsystemLevelMappingKeyValue( // Formats the mapping data as a comma separated list of key value pairs string CSubsystem::getFormattedSubsystemMappingData( - const CInstanceConfigurableElement* pInstanceConfigurableElement) const + const CInstanceConfigurableElement *pInstanceConfigurableElement) const { // Find the SubsystemObject related to pInstanceConfigurableElement - const CSubsystemObject* pSubsystemObject = findSubsystemObjectFromConfigurableElement( - pInstanceConfigurableElement); + const CSubsystemObject *pSubsystemObject = + findSubsystemObjectFromConfigurableElement(pInstanceConfigurableElement); // Exit if node does not correspond to a SubsystemObject if (pSubsystemObject == NULL) { @@ -291,7 +266,7 @@ string CSubsystem::getFormattedSubsystemMappingData( return strMappingKey + ":" + pSubsystemObject->getFormattedMappingValue(); } -string CSubsystem::getMapping(list<const CConfigurableElement*>& configurableElementPath) const +string CSubsystem::getMapping(list<const CConfigurableElement *> &configurableElementPath) const { if (configurableElementPath.empty()) { @@ -299,71 +274,55 @@ string CSubsystem::getMapping(list<const CConfigurableElement*>& configurableEle } // Get the first element, which is the element containing the amended mapping - const CInstanceConfigurableElement* pInstanceConfigurableElement = - static_cast<const CInstanceConfigurableElement*>(configurableElementPath.front()); - configurableElementPath.pop_front(); - // Now the list only contains elements whose mapping are related to the context + const CInstanceConfigurableElement *pInstanceConfigurableElement = + static_cast<const CInstanceConfigurableElement *>(configurableElementPath.front()); // Format context mapping data string strValue = formatMappingDataList(configurableElementPath); // Print the mapping of the first node, which corresponds to a SubsystemObject - strValue += getFormattedSubsystemMappingData(pInstanceConfigurableElement); + auto subsystemObjectAmendedMapping = + getFormattedSubsystemMappingData(pInstanceConfigurableElement); + if (not subsystemObjectAmendedMapping.empty()) { + strValue += ", " + subsystemObjectAmendedMapping; + } return strValue; } -void CSubsystem::logValue(string& strValue, CErrorContext& errorContext) const -{ - CParameterAccessContext& parameterAccessContext = static_cast<CParameterAccessContext&>(errorContext); - - // Deal with Endianness - parameterAccessContext.setBigEndianSubsystem(_bBigEndian); - - return base::logValue(strValue, errorContext); -} - // Used for simulation and virtual subsystems -void CSubsystem::setDefaultValues(CParameterAccessContext& parameterAccessContext) const +void CSubsystem::setDefaultValues(CParameterAccessContext ¶meterAccessContext) const { - // Deal with Endianness - parameterAccessContext.setBigEndianSubsystem(_bBigEndian); - base::setDefaultValues(parameterAccessContext); } // Belonging subsystem -const CSubsystem* CSubsystem::getBelongingSubsystem() const +const CSubsystem *CSubsystem::getBelongingSubsystem() const { return this; } // Subsystem context mapping keys publication -void CSubsystem::addContextMappingKey(const string& strMappingKey) +void CSubsystem::addContextMappingKey(const string &strMappingKey) { _contextMappingKeyArray.push_back(strMappingKey); } // Subsystem object creator publication (strong reference) -void CSubsystem::addSubsystemObjectFactory(CSubsystemObjectCreator* pSubsystemObjectCreator) +void CSubsystem::addSubsystemObjectFactory(CSubsystemObjectCreator *pSubsystemObjectCreator) { _subsystemObjectCreatorArray.push_back(pSubsystemObjectCreator); } // Generic error handling from derived subsystem classes -string CSubsystem::getMappingError( - const string& strKey, - const string& strMessage, - const CConfigurableElementWithMapping* pConfigurableElementWithMapping) const +string CSubsystem::getMappingError(const string &strKey, const string &strMessage, + const CConfigurableElement *pConfigurableElement) const { - return getName() + " " + getKind() + " " + - "mapping:\n" + strKey + " " + - "error: \"" + strMessage + "\" " + - "for element " + pConfigurableElementWithMapping->getPath(); + return getName() + " " + getKind() + " " + "mapping:\n" + strKey + " " + "error: \"" + + strMessage + "\" " + "for element " + pConfigurableElement->getPath(); } - -bool CSubsystem::getMappingData(const std::string& strKey, const std::string*& pStrValue) const +bool CSubsystem::getMappingData(const std::string &strKey, const std::string *&pStrValue) const { if (_pMappingData) { @@ -372,25 +331,30 @@ bool CSubsystem::getMappingData(const std::string& strKey, const std::string*& p return false; } +// Returns the formatted mapping +std::string CSubsystem::getFormattedMapping() const +{ + if (!_pMappingData) { + return ""; + } + return _pMappingData->asString(); +} + // Mapping generic context handling -bool CSubsystem::handleMappingContext( - const CConfigurableElementWithMapping* pConfigurableElementWithMapping, - CMappingContext& context, - string& strError) const +bool CSubsystem::handleMappingContext(const CConfigurableElement *pConfigurableElement, + CMappingContext &context, string &strError) const { // Feed context with found mapping data - uint32_t uiItem; - - for (uiItem = 0; uiItem < _contextMappingKeyArray.size(); uiItem++) { + for (size_t item = 0; item < _contextMappingKeyArray.size(); item++) { - const string& strKey = _contextMappingKeyArray[uiItem]; - const string* pStrValue; + const string &strKey = _contextMappingKeyArray[item]; + const string *pStrValue; - if (pConfigurableElementWithMapping->getMappingData(strKey, pStrValue)) { + if (pConfigurableElement->getMappingData(strKey, pStrValue)) { // Assign item to context - if (!context.setItem(uiItem, &strKey, pStrValue)) { + if (!context.setItem(item, &strKey, pStrValue)) { - strError = getMappingError(strKey, "Already set", pConfigurableElementWithMapping); + strError = getMappingError(strKey, "Already set", pConfigurableElement); return false; } @@ -401,30 +365,26 @@ bool CSubsystem::handleMappingContext( // Subsystem object creation handling bool CSubsystem::handleSubsystemObjectCreation( - CInstanceConfigurableElement* pInstanceConfigurableElement, - CMappingContext& context, bool& bHasCreatedSubsystemObject, string& strError) + CInstanceConfigurableElement *pInstanceConfigurableElement, CMappingContext &context, + bool &bHasCreatedSubsystemObject, string &strError) { - uint32_t uiItem; bHasCreatedSubsystemObject = false; - for (uiItem = 0; uiItem < _subsystemObjectCreatorArray.size(); uiItem++) { - - const CSubsystemObjectCreator* pSubsystemObjectCreator = - _subsystemObjectCreatorArray[uiItem]; + for (const auto *pSubsystemObjectCreator : _subsystemObjectCreatorArray) { // Mapping key string strKey = pSubsystemObjectCreator->getMappingKey(); // Object id - const string* pStrValue; + const string *pStrValue; if (pInstanceConfigurableElement->getMappingData(strKey, pStrValue)) { // First check context consistency // (required ancestors must have been set prior to object creation) - uint32_t uiAncestorKey; uint32_t uiAncestorMask = pSubsystemObjectCreator->getAncestorMask(); - for (uiAncestorKey = 0; uiAncestorKey < _contextMappingKeyArray.size(); uiAncestorKey++) { + for (size_t uiAncestorKey = 0; uiAncestorKey < _contextMappingKeyArray.size(); + uiAncestorKey++) { if (!((1 << uiAncestorKey) & uiAncestorMask)) { // Ancestor not required @@ -433,8 +393,9 @@ bool CSubsystem::handleSubsystemObjectCreation( // Check ancestor was provided if (!context.iSet(uiAncestorKey)) { - strError = getMappingError(strKey, _contextMappingKeyArray[uiAncestorKey] + - " not set", pInstanceConfigurableElement); + strError = + getMappingError(strKey, _contextMappingKeyArray[uiAncestorKey] + " not set", + pInstanceConfigurableElement); return false; } @@ -444,9 +405,9 @@ bool CSubsystem::handleSubsystemObjectCreation( if (pInstanceConfigurableElement->getFootPrint() > pSubsystemObjectCreator->getMaxConfigurableElementSize()) { - string strSizeError = "Size should not exceed " + - CUtility::toString( - pSubsystemObjectCreator->getMaxConfigurableElementSize()); + string strSizeError = + "Size should not exceed " + + std::to_string(pSubsystemObjectCreator->getMaxConfigurableElementSize()); strError = getMappingError(strKey, strSizeError, pInstanceConfigurableElement); @@ -455,7 +416,7 @@ bool CSubsystem::handleSubsystemObjectCreation( // Do create object and keep its track _subsystemObjectList.push_back(pSubsystemObjectCreator->objectCreate( - *pStrValue, pInstanceConfigurableElement, context)); + *pStrValue, pInstanceConfigurableElement, context, _logger)); // Indicate subsytem creation to caller bHasCreatedSubsystemObject = true; @@ -471,15 +432,14 @@ bool CSubsystem::handleSubsystemObjectCreation( // From IMapper // Handle a configurable element mapping -bool CSubsystem::mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, - bool& bKeepDiving, string& strError) +bool CSubsystem::mapBegin(CInstanceConfigurableElement *pInstanceConfigurableElement, + bool &bKeepDiving, string &strError) { // Get current context CMappingContext context = _contextStack.top(); // Add mapping in context - if (!handleMappingContext(pInstanceConfigurableElement, context, - strError)) { + if (!handleMappingContext(pInstanceConfigurableElement, context, strError)) { return false; } @@ -493,40 +453,39 @@ bool CSubsystem::mapBegin(CInstanceConfigurableElement* pInstanceConfigurableEle // Deal with ambiguous usage of parameter blocks bool bShouldCreateSubsystemObject = true; - switch(pInstanceConfigurableElement->getType()) { + switch (pInstanceConfigurableElement->getType()) { - case CInstanceConfigurableElement::EComponent: - case CInstanceConfigurableElement::EParameterBlock: - // Subsystem object creation is optional in parameter blocks - bShouldCreateSubsystemObject = false; - // No break - case CInstanceConfigurableElement::EBitParameterBlock: - case CInstanceConfigurableElement::EParameter: - case CInstanceConfigurableElement::EStringParameter: + case CInstanceConfigurableElement::EComponent: + case CInstanceConfigurableElement::EParameterBlock: + // Subsystem object creation is optional in parameter blocks + bShouldCreateSubsystemObject = false; + // No break + case CInstanceConfigurableElement::EBitParameterBlock: + case CInstanceConfigurableElement::EParameter: + case CInstanceConfigurableElement::EStringParameter: - bool bHasCreatedSubsystemObject; + bool bHasCreatedSubsystemObject; - if (!handleSubsystemObjectCreation(pInstanceConfigurableElement, context, - bHasCreatedSubsystemObject, strError)) { + if (!handleSubsystemObjectCreation(pInstanceConfigurableElement, context, + bHasCreatedSubsystemObject, strError)) { - return false; - } - // Check for creation error - if (bShouldCreateSubsystemObject && !bHasCreatedSubsystemObject) { + return false; + } + // Check for creation error + if (bShouldCreateSubsystemObject && !bHasCreatedSubsystemObject) { - strError = getMappingError("Not found", - "Subsystem object mapping key is missing", - pInstanceConfigurableElement); - return false; - } - // Not created and no error, keep diving - bKeepDiving = !bHasCreatedSubsystemObject; + strError = getMappingError("Not found", "Subsystem object mapping key is missing", + pInstanceConfigurableElement); + return false; + } + // Not created and no error, keep diving + bKeepDiving = !bHasCreatedSubsystemObject; - return true; + return true; - default: - assert(0); - return false; + default: + assert(0); + return false; } } diff --git a/parameter/Subsystem.h b/parameter/Subsystem.h index e537352..af7e1fb 100644 --- a/parameter/Subsystem.h +++ b/parameter/Subsystem.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,10 +29,13 @@ */ #pragma once +#include "parameter_export.h" + #include "ConfigurableElement.h" -#include "ConfigurableElementWithMapping.h" #include "Mapper.h" #include "MappingContext.h" +#include <log/Logger.h> + #include <list> #include <stack> #include <string> @@ -45,19 +48,23 @@ class CSubsystemObjectCreator; class CInstanceConfigurableElement; class CMappingData; -class CSubsystem : public CConfigurableElementWithMapping, private IMapper +class PARAMETER_EXPORT CSubsystem : public CConfigurableElement, private IMapper { // Subsystem objects iterator - typedef std::list<CSubsystemObject*>::const_iterator SubsystemObjectListIterator; + typedef std::list<CSubsystemObject *>::const_iterator SubsystemObjectListIterator; + public: - CSubsystem(const std::string& strName); + /** + * Class Constructor + * + * @param[in] strName subsystem name + * @param[in] logger the main logger of the application + */ + CSubsystem(const std::string &strName, core::log::Logger &logger); virtual ~CSubsystem(); - // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); - - // Susbsystem Endianness - bool isBigEndian() const; + virtual bool structureFromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext); // Susbsystem sanity virtual bool isAlive() const; @@ -65,18 +72,17 @@ public: // Resynchronization after subsystem restart needed virtual bool needResync(bool bClear); - // XML configuration settings parsing - virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const; - // from CElement virtual std::string getKind() const; - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const; + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const; + std::string getFormattedMapping() const override; /** * Fetch mapping data of an element. * - * The mapping is represented as a std::string of all the mapping data (key:value) defined in the + * The mapping is represented as a std::string of all the mapping data (key:value) defined in + * the * context of the element. * This method gathers the mapping data found in each Element of the configurableElementPath * list to format the resulting std::string. @@ -87,36 +93,35 @@ public: * * @return Formatted std::string of the mapping data */ - virtual std::string getMapping(std::list<const CConfigurableElement*>& configurableElementPath) const; + virtual std::string getMapping( + std::list<const CConfigurableElement *> &configurableElementPath) const; protected: - // Parameter access - virtual bool accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const; - virtual void logValue(std::string& strValue, CErrorContext& errorContext) const; // Used for simulation and virtual subsystems - virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const; + virtual void setDefaultValues(CParameterAccessContext ¶meterAccessContext) const; /// Functionality intendedn for derived Subsystems // Subsystem context mapping keys publication - void addContextMappingKey(const std::string& strMappingKey); + void addContextMappingKey(const std::string &strMappingKey); // Subsystem object creator publication (strong reference) - void addSubsystemObjectFactory(CSubsystemObjectCreator* pSubsystemObjectCreator); + void addSubsystemObjectFactory(CSubsystemObjectCreator *pSubsystemObjectCreator); + private: - CSubsystem(const CSubsystem&); - CSubsystem& operator=(const CSubsystem&); + CSubsystem(const CSubsystem &); + CSubsystem &operator=(const CSubsystem &); // Belonging subsystem - virtual const CSubsystem* getBelongingSubsystem() const; + virtual const CSubsystem *getBelongingSubsystem() const; // Mapping execution - bool mapSubsystemElements(std::string& strError); + bool mapSubsystemElements(std::string &strError); /** * Handle a configurable element mapping. * * Add context mappings to the context and instantiate a subsystem object if needed. * - * @param[in:out] pInstanceConfigurableElement The configurable element + * @param[in,out] pInstanceConfigurableElement The configurable element * @param[out] bKeepDiving Keep diving for mapping keys Is set to true if a subsystem object (tree leave) has been instantiated. Undetermined on error @@ -125,7 +130,8 @@ private: * * @return true on success, false on failure */ - virtual bool mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, std::string& strError); + virtual bool mapBegin(CInstanceConfigurableElement *pInstanceConfigurableElement, + bool &bKeepDiving, std::string &strError); virtual void mapEnd(); // Mapping access @@ -136,14 +142,12 @@ private: * * @param[in] strKey The key on which the error refers * @param[in] strMessage The error message - * @param[in] pConfigurableElementWithMapping The element on which the error refers + * @param[in] pConfigurableElement The element on which the error refers * * returns The formated error std::string */ - std::string getMappingError( - const std::string& strKey, - const std::string& strMessage, - const CConfigurableElementWithMapping* pConfigurableElementWithMapping) const; + std::string getMappingError(const std::string &strKey, const std::string &strMessage, + const CConfigurableElement *pConfigurableElement) const; /** * Format the mapping data of the ConfigurableElements that have been gathered through recursive @@ -156,7 +160,7 @@ private: * @return String containing the formatted mapping */ std::string formatMappingDataList( - const std::list<const CConfigurableElement*>& configurableElementPath) const; + const std::list<const CConfigurableElement *> &configurableElementPath) const; /** * Find the SubystemObject which contains a specific CInstanceConfigurableElement. @@ -167,8 +171,8 @@ private: * * @return A pointer to the SubsystemObject related to pInstanceConfigurableElement */ - const CSubsystemObject* findSubsystemObjectFromConfigurableElement( - const CInstanceConfigurableElement* pInstanceConfigurableElement) const; + const CSubsystemObject *findSubsystemObjectFromConfigurableElement( + const CInstanceConfigurableElement *pInstanceConfigurableElement) const; /** * Find the mapping data defined for the CInstanceConfigurableElement given in parameter, that @@ -182,9 +186,8 @@ private: * @param[out] strMappingValue Mapping value contained in pInstanceConfigurableElement */ void findSubsystemLevelMappingKeyValue( - const CInstanceConfigurableElement* pInstanceConfigurableElement, - std::string& strMappingKey, - std::string& strMappingValue) const; + const CInstanceConfigurableElement *pInstanceConfigurableElement, + std::string &strMappingKey, std::string &strMappingValue) const; /** * Formats the mapping of a SubsystemObject @@ -194,28 +197,26 @@ private: * @return String containing the formatted mapping */ std::string getFormattedSubsystemMappingData( - const CInstanceConfigurableElement* pInstanceConfigurableElement) const; + const CInstanceConfigurableElement *pInstanceConfigurableElement) const; /** * Generic context handling * * Feed context with mapping data of the current element * - * @param[in] pConfigurableElementWithMapping The element containing mapping data + * @param[in] pConfigurableElement The element containing mapping data * @param[out] context The context mapping to update with the current element mapping values * @param[out] strError The formated error std::string * * @return true on success */ - bool handleMappingContext( - const CConfigurableElementWithMapping* pConfigurableElementWithMapping, - CMappingContext& context, - std::string& strError) const; + bool handleMappingContext(const CConfigurableElement *pConfigurableElement, + CMappingContext &context, std::string &strError) const; /** * Looks if a subsystem object needs to be instantiated for the given configurable * element, then instantiate it if needed. * - * @param[in:out] pInstanceConfigurableElement The configurable element to check + * @param[in,out] pInstanceConfigurableElement The configurable element to check * for instanciation * @param[in] context The mapping values container * @param[out] bHasCreatedSubsystemObject If a subsystem object has been instantiated. @@ -225,29 +226,29 @@ private: * * @return true on success, false on failure */ - bool handleSubsystemObjectCreation(CInstanceConfigurableElement* pInstanceConfigurableElement, - CMappingContext& context, bool& bHasCreatedSubsystemObject, - std::string& strError); + bool handleSubsystemObjectCreation(CInstanceConfigurableElement *pInstanceConfigurableElement, + CMappingContext &context, bool &bHasCreatedSubsystemObject, + std::string &strError); // Subsystem context mapping keys std::vector<std::string> _contextMappingKeyArray; // Subsystem object creator map - std::vector<CSubsystemObjectCreator*> _subsystemObjectCreatorArray; + std::vector<CSubsystemObjectCreator *> _subsystemObjectCreatorArray; // Subsystem sync objects (house keeping) - std::list<CSubsystemObject*> _subsystemObjectList; + std::list<CSubsystemObject *> _subsystemObjectList; // Mapping Context stack std::stack<CMappingContext> _contextStack; // Subelements - CComponentLibrary* _pComponentLibrary; - CInstanceDefinition* _pInstanceDefinition; - - // Endianness - bool _bBigEndian; + CComponentLibrary *_pComponentLibrary; + CInstanceDefinition *_pInstanceDefinition; //! Contains the mapping info at Subsystem level - CMappingData* _pMappingData; + CMappingData *_pMappingData{nullptr}; + + /** Logger which has to be provided to subsystem objects */ + core::log::Logger &_logger; }; diff --git a/parameter/SubsystemElementBuilder.cpp b/parameter/SubsystemElementBuilder.cpp index c166113..96a0be2 100644 --- a/parameter/SubsystemElementBuilder.cpp +++ b/parameter/SubsystemElementBuilder.cpp @@ -30,12 +30,12 @@ #include "SubsystemElementBuilder.h" #include "SubsystemLibrary.h" -CSubsystemElementBuilder::CSubsystemElementBuilder(const CSubsystemLibrary* pSubsystemLibrary) : - CElementBuilder(), _pSubsystemLibrary(pSubsystemLibrary) +CSubsystemElementBuilder::CSubsystemElementBuilder(const CSubsystemLibrary *pSubsystemLibrary) + : CElementBuilder(), _pSubsystemLibrary(pSubsystemLibrary) { } -CElement* CSubsystemElementBuilder::createElement(const CXmlElement& xmlElement) const +CElement *CSubsystemElementBuilder::createElement(const CXmlElement &xmlElement) const { return _pSubsystemLibrary->createElement(xmlElement); } diff --git a/parameter/SubsystemElementBuilder.h b/parameter/SubsystemElementBuilder.h index d0465bf..4dfe78f 100644 --- a/parameter/SubsystemElementBuilder.h +++ b/parameter/SubsystemElementBuilder.h @@ -36,11 +36,10 @@ class CSubsystemLibrary; class CSubsystemElementBuilder : public CElementBuilder { public: - CSubsystemElementBuilder(const CSubsystemLibrary* pSubsystemLibrary); + CSubsystemElementBuilder(const CSubsystemLibrary *pSubsystemLibrary); - virtual CElement* createElement(const CXmlElement& xmlElement) const; + virtual CElement *createElement(const CXmlElement &xmlElement) const; private: - const CSubsystemLibrary* _pSubsystemLibrary; + const CSubsystemLibrary *_pSubsystemLibrary; }; - diff --git a/parameter/SubsystemLibrary.h b/parameter/SubsystemLibrary.h index 78a497e..f3082e2 100644 --- a/parameter/SubsystemLibrary.h +++ b/parameter/SubsystemLibrary.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,17 +31,28 @@ #include "DefaultElementLibrary.h" #include "VirtualSubsystem.h" -#include "NamedElementBuilderTemplate.h" +#include "LoggingElementBuilderTemplate.h" #include <string> -class CSubsystemLibrary : - public CDefaultElementLibrary<TNamedElementBuilderTemplate<CVirtualSubsystem> > +/** Plugin entry point symbol + * + * Needs to be implemented by plugin libraries. This function's purpose is to + * register element builders; + * + * "V1" refers to the version of this entry-point API. + */ +#define PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1 ParameterFrameworkPluginEntryPointMagicV1 + +class CSubsystemLibrary + : public CDefaultElementLibrary<TLoggingElementBuilderTemplate<CVirtualSubsystem>> { private: // Builder type (based on element's name attribute) - virtual std::string getBuilderType(const CXmlElement& xmlElement) const + virtual std::string getBuilderType(const CXmlElement &xmlElement) const { // Xml element's name attribute - return xmlElement.getAttributeString("Type"); + std::string type; + xmlElement.getAttribute("Type", type); + return type; } }; diff --git a/parameter/SubsystemObject.cpp b/parameter/SubsystemObject.cpp index e6b7b44..1b7b8f1 100644 --- a/parameter/SubsystemObject.cpp +++ b/parameter/SubsystemObject.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -34,6 +34,7 @@ #include "ParameterAccessContext.h" #include "MappingContext.h" #include "ParameterType.h" +#include "convert.hpp" #include <assert.h> #include <stdlib.h> #include <string.h> @@ -42,11 +43,10 @@ using std::string; -CSubsystemObject::CSubsystemObject(CInstanceConfigurableElement* pInstanceConfigurableElement) - : _pInstanceConfigurableElement(pInstanceConfigurableElement), - _uiDataSize(pInstanceConfigurableElement->getFootPrint()), - _pucBlackboardLocation(NULL), - _uiAccessedIndex(0) +CSubsystemObject::CSubsystemObject(CInstanceConfigurableElement *pInstanceConfigurableElement, + core::log::Logger &logger) + : _logger(logger), _pInstanceConfigurableElement(pInstanceConfigurableElement), + _dataSize(pInstanceConfigurableElement->getFootPrint()) { // Syncer _pInstanceConfigurableElement->setSyncer(this); @@ -64,35 +64,19 @@ string CSubsystemObject::getFormattedMappingValue() const } // Blackboard data location -uint8_t* CSubsystemObject::getBlackboardLocation() const +uint8_t *CSubsystemObject::getBlackboardLocation() const { - return _pucBlackboardLocation; + return _blackboard->getLocation(getOffset()); } // Size -uint32_t CSubsystemObject::getSize() const +size_t CSubsystemObject::getSize() const { - return _uiDataSize; -} - -// Conversion utility -uint32_t CSubsystemObject::asInteger(const string& strValue) -{ - return strtoul(strValue.c_str(), NULL, 0); -} - -string CSubsystemObject::asString(uint32_t uiValue) -{ - std::ostringstream ostr; - - ostr << uiValue; - - return ostr.str(); + return _dataSize; } int CSubsystemObject::toPlainInteger( - const CInstanceConfigurableElement *instanceConfigurableElement, - int sizeOptimizedData) + const CInstanceConfigurableElement *instanceConfigurableElement, int sizeOptimizedData) { if (instanceConfigurableElement) { @@ -108,31 +92,31 @@ int CSubsystemObject::toPlainInteger( } // Default back synchronization -void CSubsystemObject::setDefaultValues(CParameterBlackboard& parameterBlackboard) const +void CSubsystemObject::setDefaultValues(CParameterBlackboard ¶meterBlackboard) const { string strError; // Create access context - CParameterAccessContext parameterAccessContext(strError, ¶meterBlackboard, false); + CParameterAccessContext parameterAccessContext(strError, ¶meterBlackboard); // Just implement back synchronization with default values _pInstanceConfigurableElement->setDefaultValues(parameterAccessContext); } // Synchronization -bool CSubsystemObject::sync(CParameterBlackboard& parameterBlackboard, bool bBack, string& strError) +bool CSubsystemObject::sync(CParameterBlackboard ¶meterBlackboard, bool bBack, string &strError) { // Get blackboard location - _pucBlackboardLocation = parameterBlackboard.getLocation(_pInstanceConfigurableElement->getOffset()); + _blackboard = ¶meterBlackboard; // Access index init - _uiAccessedIndex = 0; + _accessedIndex = 0; #ifdef SIMULATION return true; #endif // Retrieve subsystem - const CSubsystem* pSubsystem = _pInstanceConfigurableElement->getBelongingSubsystem(); + const CSubsystem *pSubsystem = _pInstanceConfigurableElement->getBelongingSubsystem(); // Get it's health insdicator bool bIsSubsystemAlive = pSubsystem->isAlive(); @@ -146,15 +130,10 @@ bool CSubsystemObject::sync(CParameterBlackboard& parameterBlackboard, bool bBac // Synchronize to/from HW if (!bIsSubsystemAlive || !accessHW(bBack, strError)) { - strError = string("Unable to ") + (bBack ? "back" : "forward") + " synchronize configurable element " + - _pInstanceConfigurableElement->getPath() + ": " + strError; - - log_warning("%s", strError.c_str()); - // Fall back to parameter default initialization if (bBack) { - setDefaultValues(parameterBlackboard); + setDefaultValues(parameterBlackboard); } return false; } @@ -163,17 +142,15 @@ bool CSubsystemObject::sync(CParameterBlackboard& parameterBlackboard, bool bBac } // Sync to/from HW -bool CSubsystemObject::sendToHW(string& strError) +bool CSubsystemObject::sendToHW(string &strError) { strError = "Send to HW interface not implemented at subsystem level"; return false; } -bool CSubsystemObject::receiveFromHW(string& strError) +bool CSubsystemObject::receiveFromHW(string & /*strError*/) { - (void)strError; - // Back synchronization is not supported at subsystem level. // Rely on blackboard content @@ -181,7 +158,7 @@ bool CSubsystemObject::receiveFromHW(string& strError) } // Fall back HW access -bool CSubsystemObject::accessHW(bool bReceive, string& strError) +bool CSubsystemObject::accessHW(bool bReceive, string &strError) { // Default access fall back if (bReceive) { @@ -194,68 +171,32 @@ bool CSubsystemObject::accessHW(bool bReceive, string& strError) } // Blackboard access from subsystems -void CSubsystemObject::blackboardRead(void* pvData, uint32_t uiSize) -{ - assert(_uiAccessedIndex + uiSize <= _uiDataSize); - - memcpy(pvData, _pucBlackboardLocation + _uiAccessedIndex, uiSize); - - _uiAccessedIndex += uiSize; -} - -void CSubsystemObject::blackboardWrite(const void* pvData, uint32_t uiSize) -{ - assert(_uiAccessedIndex + uiSize <= _uiDataSize); - - memcpy(_pucBlackboardLocation + _uiAccessedIndex, pvData, uiSize); - - _uiAccessedIndex += uiSize; -} - -// Logging -void CSubsystemObject::log_info(std::string strMessage, ...) const +void CSubsystemObject::blackboardRead(void *pvData, size_t size) { - char *pacBuffer; - va_list listPointer; - - va_start(listPointer, strMessage); - - vasprintf(&pacBuffer, strMessage.c_str(), listPointer); - - va_end(listPointer); - - if (pacBuffer != NULL) { - _pInstanceConfigurableElement->log_info("%s", pacBuffer); - } + _blackboard->readBuffer(pvData, size, getOffset() + _accessedIndex); - free(pacBuffer); + _accessedIndex += size; } -void CSubsystemObject::log_warning(std::string strMessage, ...) const +void CSubsystemObject::blackboardWrite(const void *pvData, size_t size) { - char *pacBuffer; - va_list listPointer; + _blackboard->writeBuffer(pvData, size, getOffset() + _accessedIndex); - va_start(listPointer, strMessage); - - vasprintf(&pacBuffer, strMessage.c_str(), listPointer); - - va_end(listPointer); - - if (pacBuffer != NULL) { - _pInstanceConfigurableElement->log_warning("%s", pacBuffer); - } - - free(pacBuffer); + _accessedIndex += size; } // Configurable element retrieval -const CInstanceConfigurableElement* CSubsystemObject::getConfigurableElement() const +const CInstanceConfigurableElement *CSubsystemObject::getConfigurableElement() const { return _pInstanceConfigurableElement; } // Belonging Subsystem retrieval -const CSubsystem* CSubsystemObject::getSubsystem() const +const CSubsystem *CSubsystemObject::getSubsystem() const { return _pInstanceConfigurableElement->getBelongingSubsystem(); } + +size_t CSubsystemObject::getOffset() const +{ + return _pInstanceConfigurableElement->getOffset(); +} diff --git a/parameter/SubsystemObject.h b/parameter/SubsystemObject.h index 2ba2123..2400573 100644 --- a/parameter/SubsystemObject.h +++ b/parameter/SubsystemObject.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,19 +29,23 @@ */ #pragma once +#include "parameter_export.h" + #include "Syncer.h" -#include <stdint.h> +#include <log/Logger.h> +#include <stdint.h> #include <string> class CInstanceConfigurableElement; class CMappingContext; class CSubsystem; -class CSubsystemObject : private ISyncer +class PARAMETER_EXPORT CSubsystemObject : private ISyncer { public: - CSubsystemObject(CInstanceConfigurableElement* pInstanceConfigurableElement); + CSubsystemObject(CInstanceConfigurableElement *pInstanceConfigurableElement, + core::log::Logger &logger); virtual ~CSubsystemObject(); /** @@ -52,16 +56,15 @@ public: virtual std::string getFormattedMappingValue() const; // Configurable element retrieval - const CInstanceConfigurableElement* getConfigurableElement() const; + const CInstanceConfigurableElement *getConfigurableElement() const; protected: - // Blackboard data location - uint8_t* getBlackboardLocation() const; + /** FIXME: plugins should not have direct access to blackboard memory. + * Ie: This method should be removed or return a abstracted iterator. + */ + uint8_t *getBlackboardLocation() const; // Size - uint32_t getSize() const; - // Conversion utility - static uint32_t asInteger(const std::string& strValue); - static std::string asString(uint32_t uiValue); + size_t getSize() const; /** * Conversion of int8, int16, int32 to int (taking care of sign extension) @@ -75,43 +78,52 @@ protected: int sizeOptimizedData); // Sync to/from HW - virtual bool sendToHW(std::string& strError); - virtual bool receiveFromHW(std::string& strError); + virtual bool sendToHW(std::string &strError); + virtual bool receiveFromHW(std::string &strError); // Fall back HW access - virtual bool accessHW(bool bReceive, std::string& strError); + virtual bool accessHW(bool bReceive, std::string &strError); // Blackboard access from subsystems - void blackboardRead(void* pvData, uint32_t uiSize); - void blackboardWrite(const void* pvData, uint32_t uiSize); - // Logging - // Copy the string format because: - // - passing char * would break compatibility - // - passing a const std::string & in forbiden by the c++ standard - // as va_start second argument must not be a reference. - void log_info(std::string strMessage, ...) const; - void log_warning(std::string strMessage, ...) const; + void blackboardRead(void *pvData, size_t size); + void blackboardWrite(const void *pvData, size_t size); // Belonging Subsystem retrieval - const CSubsystem* getSubsystem() const; + const CSubsystem *getSubsystem() const; + + /** Logging methods + *@{ + */ + core::log::details::Info info() const { return _logger.info(); } + core::log::details::Warning warning() const { return _logger.warning(); } + /* @} */ private: // from ISyncer - virtual bool sync(CParameterBlackboard& parameterBlackboard, bool bBack, std::string& strError); + /** This method is not supposed to be overridden by plugins + * as if not called, plugins will not work (sets _blackboard). + */ + bool sync(CParameterBlackboard ¶meterBlackboard, bool bBack, + std::string &strError) override final; // Default back synchronization - void setDefaultValues(CParameterBlackboard& parameterBlackboard) const; + void setDefaultValues(CParameterBlackboard ¶meterBlackboard) const; + + /** @return the offset in the main blackboard of the sync values. */ + size_t getOffset() const; // Prevent unsupported operators - CSubsystemObject(const CSubsystemObject&); + CSubsystemObject(const CSubsystemObject &); // Define affection operator - const CSubsystemObject& operator=(const CSubsystemObject&); + const CSubsystemObject &operator=(const CSubsystemObject &); + + /** Application Logger */ + core::log::Logger &_logger; // Instance element to sync from/to - CInstanceConfigurableElement* _pInstanceConfigurableElement; + CInstanceConfigurableElement *_pInstanceConfigurableElement; // Data size - uint32_t _uiDataSize; + size_t _dataSize; // Blackboard data location - uint8_t* _pucBlackboardLocation; + CParameterBlackboard *_blackboard{nullptr}; // Accessed index for Subsystem read/write from/to blackboard - uint32_t _uiAccessedIndex; + size_t _accessedIndex{0}; }; - diff --git a/parameter/SubsystemObjectCreator.cpp b/parameter/SubsystemObjectCreator.cpp index 66c1cac..69e007a 100644 --- a/parameter/SubsystemObjectCreator.cpp +++ b/parameter/SubsystemObjectCreator.cpp @@ -31,13 +31,16 @@ using std::string; -CSubsystemObjectCreator::CSubsystemObjectCreator(const string& strMappingKey, uint32_t uiAncestorIdMask, uint32_t uiMaxConfigurableElementSize) - : _strMappingKey(strMappingKey), _uiAncestorIdMask(uiAncestorIdMask), _uiMaxConfigurableElementSize(uiMaxConfigurableElementSize) +CSubsystemObjectCreator::CSubsystemObjectCreator(const string &strMappingKey, + uint32_t uiAncestorIdMask, + size_t maxConfigurableElementSize) + : _strMappingKey(strMappingKey), _uiAncestorIdMask(uiAncestorIdMask), + _maxConfigurableElementSize(maxConfigurableElementSize) { } // Accessors -const string& CSubsystemObjectCreator::getMappingKey() const +const string &CSubsystemObjectCreator::getMappingKey() const { return _strMappingKey; } @@ -47,7 +50,7 @@ uint32_t CSubsystemObjectCreator::getAncestorMask() const return _uiAncestorIdMask; } -uint32_t CSubsystemObjectCreator::getMaxConfigurableElementSize() const +size_t CSubsystemObjectCreator::getMaxConfigurableElementSize() const { - return _uiMaxConfigurableElementSize; + return _maxConfigurableElementSize; } diff --git a/parameter/SubsystemObjectCreator.h b/parameter/SubsystemObjectCreator.h index ed6e79d..8a4b098 100644 --- a/parameter/SubsystemObjectCreator.h +++ b/parameter/SubsystemObjectCreator.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,24 +29,30 @@ */ #pragma once +#include "parameter_export.h" + #include "SubsystemObject.h" #include "MappingContext.h" #include <string> -class CSubsystemObjectCreator +class PARAMETER_EXPORT CSubsystemObjectCreator { public: - CSubsystemObjectCreator(const std::string& strMappingKey, uint32_t uiAncestorIdMask, uint32_t uiMaxConfigurableElementSize); + CSubsystemObjectCreator(const std::string &strMappingKey, uint32_t uiAncestorIdMask, + size_t maxConfigurableElementSize); // Accessors - const std::string& getMappingKey() const; + const std::string &getMappingKey() const; uint32_t getAncestorMask() const; - uint32_t getMaxConfigurableElementSize() const; + size_t getMaxConfigurableElementSize() const; // Object creation - virtual CSubsystemObject* objectCreate(const std::string& strMappingValue, CInstanceConfigurableElement* pInstanceConfigurableElement, const CMappingContext& context) const = 0; + virtual CSubsystemObject *objectCreate( + const std::string &strMappingValue, + CInstanceConfigurableElement *pInstanceConfigurableElement, const CMappingContext &context, + core::log::Logger &logger) const = 0; - virtual ~CSubsystemObjectCreator() {} + virtual ~CSubsystemObjectCreator() = default; private: // Mapping key @@ -54,6 +60,5 @@ private: // Mask of must-be-specified ancestors uint32_t _uiAncestorIdMask; // Masximum expected size for configurable elment (-1 means none) - uint32_t _uiMaxConfigurableElementSize; + size_t _maxConfigurableElementSize; }; - diff --git a/parameter/SubsystemObjectFactory.h b/parameter/SubsystemObjectFactory.h index 3ac7835..9881227 100644 --- a/parameter/SubsystemObjectFactory.h +++ b/parameter/SubsystemObjectFactory.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,16 +31,25 @@ #include "SubsystemObjectCreator.h" #include <string> +#include <limits> template <class SubsystemObjectType> class TSubsystemObjectFactory : public CSubsystemObjectCreator { public: - TSubsystemObjectFactory(const std::string& strMappingKey, uint32_t uiAncestorIdMask, uint32_t uiMaxConfigurableElementSize = -1) : CSubsystemObjectCreator(strMappingKey, uiAncestorIdMask, uiMaxConfigurableElementSize) {} + TSubsystemObjectFactory(const std::string &strMappingKey, uint32_t uiAncestorIdMask, + size_t maxConfigurableElementSize = std::numeric_limits<size_t>::max()) + : CSubsystemObjectCreator(strMappingKey, uiAncestorIdMask, maxConfigurableElementSize) + { + } // Object creation - virtual CSubsystemObject* objectCreate(const std::string& strMappingValue, CInstanceConfigurableElement* pInstanceConfigurableElement, const CMappingContext& context) const + virtual CSubsystemObject *objectCreate( + const std::string &strMappingValue, + CInstanceConfigurableElement *pInstanceConfigurableElement, const CMappingContext &context, + core::log::Logger &logger) const { - return new SubsystemObjectType(strMappingValue, pInstanceConfigurableElement, context); + return new SubsystemObjectType(strMappingValue, pInstanceConfigurableElement, context, + logger); } }; diff --git a/parameter/SubsystemPlugins.h b/parameter/SubsystemPlugins.h index aa9e32c..c5eb1c6 100644 --- a/parameter/SubsystemPlugins.h +++ b/parameter/SubsystemPlugins.h @@ -36,13 +36,11 @@ class CSubsystemPlugins : public CKindElement { public: - CSubsystemPlugins(const std::string& strName, const std::string& strKind) : CKindElement(strName, strKind) + CSubsystemPlugins(const std::string &strName, const std::string &strKind) + : CKindElement(strName, strKind) { } private: - virtual bool childrenAreDynamic() const - { - return true; - } + virtual bool childrenAreDynamic() const { return true; } }; diff --git a/parameter/Syncer.h b/parameter/Syncer.h index f119028..279dba3 100644 --- a/parameter/Syncer.h +++ b/parameter/Syncer.h @@ -36,8 +36,9 @@ class CParameterBlackboard; class ISyncer { public: - virtual bool sync(CParameterBlackboard& parameterBlackboard, bool bBack, std::string& strError) = 0; + virtual bool sync(CParameterBlackboard ¶meterBlackboard, bool bBack, + std::string &strError) = 0; protected: - virtual ~ISyncer() {} + virtual ~ISyncer() = default; }; diff --git a/parameter/SyncerSet.cpp b/parameter/SyncerSet.cpp index 9daf2a6..c27245c 100644 --- a/parameter/SyncerSet.cpp +++ b/parameter/SyncerSet.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -30,18 +30,14 @@ #include "SyncerSet.h" #include "Syncer.h" -CSyncerSet::CSyncerSet() -{ -} - -const CSyncerSet& CSyncerSet::operator+=(ISyncer* pRightSyncer) +const CSyncerSet &CSyncerSet::operator+=(ISyncer *pRightSyncer) { _syncerSet.insert(pRightSyncer); return *this; } -const CSyncerSet& CSyncerSet::operator+=(const CSyncerSet& rightSyncerSet) +const CSyncerSet &CSyncerSet::operator+=(const CSyncerSet &rightSyncerSet) { if (&rightSyncerSet != this) { @@ -56,7 +52,8 @@ void CSyncerSet::clear() _syncerSet.clear(); } -bool CSyncerSet::sync(CParameterBlackboard& parameterBlackboard, bool bBack, std::list<std::string>* plstrError) const +bool CSyncerSet::sync(CParameterBlackboard ¶meterBlackboard, bool bBack, + core::Results *errors) const { bool bSuccess = true; @@ -67,13 +64,13 @@ bool CSyncerSet::sync(CParameterBlackboard& parameterBlackboard, bool bBack, std for (it = _syncerSet.begin(); it != _syncerSet.end(); ++it) { - ISyncer* pSyncer = *it; + ISyncer *pSyncer = *it; if (!pSyncer->sync(parameterBlackboard, bBack, strError)) { - if (plstrError) { + if (errors != NULL) { - plstrError->push_back(strError); + errors->push_back(strError); } bSuccess = false; } diff --git a/parameter/SyncerSet.h b/parameter/SyncerSet.h index 7e37f45..a1bff8d 100644 --- a/parameter/SyncerSet.h +++ b/parameter/SyncerSet.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,29 +29,33 @@ */ #pragma once +#include "Results.h" #include <set> -#include <string> -#include <list> class ISyncer; class CParameterBlackboard; class CSyncerSet { - typedef std::set<ISyncer*>::const_iterator SyncerSetConstIterator; -public: - CSyncerSet(); + typedef std::set<ISyncer *>::const_iterator SyncerSetConstIterator; +public: // Filling - const CSyncerSet& operator+=(ISyncer* pRightSyncer); - const CSyncerSet& operator+=(const CSyncerSet& rightSyncerSet); + const CSyncerSet &operator+=(ISyncer *pRightSyncer); + const CSyncerSet &operator+=(const CSyncerSet &rightSyncerSet); // Clearing void clear(); - // Sync - bool sync(CParameterBlackboard& parameterBlackboard, bool bBack, std::list<std::string>* plstrError) const; + /** Sync the blackboard + * + * @param parameterBlackboard blackboard associated to syncer + * @param[in] bBack indicates if we want to back synchronise or to forward synchronise + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool sync(CParameterBlackboard ¶meterBlackboard, bool bBack, core::Results *errors) const; private: - std::set<ISyncer*> _syncerSet; + std::set<ISyncer *> _syncerSet; }; diff --git a/parameter/SystemClass.cpp b/parameter/SystemClass.cpp index ae4f747..21c7a86 100644 --- a/parameter/SystemClass.cpp +++ b/parameter/SystemClass.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,43 +27,36 @@ * (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 <dlfcn.h> -#include <dirent.h> #include <algorithm> -#include <ctype.h> #include "SystemClass.h" #include "SubsystemLibrary.h" -#include "AutoLog.h" #include "VirtualSubsystem.h" -#include "NamedElementBuilderTemplate.h" -#include <assert.h> +#include "LoggingElementBuilderTemplate.h" +#include <cassert> #include "PluginLocation.h" +#include "DynamicLibrary.hpp" #include "Utility.h" +#include "Memory.hpp" #define base CConfigurableElement +#ifndef PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1 +#error Missing PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1 macro definition +#endif +#define QUOTE(X) #X +#define MACRO_TO_STR(X) QUOTE(X) +const char CSystemClass::entryPointSymbol[] = + MACRO_TO_STR(PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1); +using PluginEntryPointV1 = void (*)(CSubsystemLibrary *, core::log::Logger &); + using std::list; using std::string; -/** - * A plugin file name is of the form: - * lib<type>-subsystem.so or lib<type>-subsystem._host.so - * - * The plugin symbol is of the form: - * get<TYPE>SubsystemBuilder -*/ -// Plugin file naming -const char* gpcPluginSuffix = "-subsystem"; -const char* gpcPluginPrefix = "lib"; - -// Plugin symbol naming -const char* gpcPluginSymbolPrefix = "get"; -const char* gpcPluginSymbolSuffix = "SubsystemBuilder"; +// FIXME: integrate SystemClass to core namespace +using namespace core; -// Used by subsystem plugins -typedef void (*GetSubsystemBuilder)(CSubsystemLibrary*); - -CSystemClass::CSystemClass() : _pSubsystemLibrary(new CSubsystemLibrary) +CSystemClass::CSystemClass(log::Logger &logger) + : _pSubsystemLibrary(new CSubsystemLibrary()), _logger(logger) { } @@ -74,14 +67,6 @@ CSystemClass::~CSystemClass() // Destroy child subsystems *before* unloading the libraries (otherwise crashes will occur // as unmapped code will be referenced) clean(); - - // Close all previously opened subsystem libraries - list<void*>::const_iterator it; - - for (it = _subsystemLibraryHandleList.begin(); it != _subsystemLibraryHandleList.end(); ++it) { - - dlclose(*it); - } } bool CSystemClass::childrenAreDynamic() const @@ -94,53 +79,59 @@ string CSystemClass::getKind() const return "SystemClass"; } -bool CSystemClass::loadSubsystems(string& strError, - const CSubsystemPlugins* pSubsystemPlugins, - bool bVirtualSubsystemFallback) +bool CSystemClass::getMappingData(const std::string & /*strKey*/, + const std::string *& /*pStrValue*/) const { - CAutoLog autoLog_info(this, "Loading subsystem plugins"); + // Although it could make sense to have mapping in the system class, + // just like at subsystem level, it is currently not supported. + return false; +} +string CSystemClass::getFormattedMapping() const +{ + return ""; +} + +bool CSystemClass::loadSubsystems(string &strError, const CSubsystemPlugins *pSubsystemPlugins, + bool bVirtualSubsystemFallback) +{ // Start clean _pSubsystemLibrary->clean(); + typedef TLoggingElementBuilderTemplate<CVirtualSubsystem> VirtualSubsystemBuilder; // Add virtual subsystem builder - _pSubsystemLibrary->addElementBuilder("Virtual", - new TNamedElementBuilderTemplate<CVirtualSubsystem>()); + _pSubsystemLibrary->addElementBuilder("Virtual", new VirtualSubsystemBuilder(_logger)); // Set virtual subsytem as builder fallback if required - _pSubsystemLibrary->enableDefaultMechanism(bVirtualSubsystemFallback); + if (bVirtualSubsystemFallback) { + _pSubsystemLibrary->setDefaultBuilder( + utility::make_unique<VirtualSubsystemBuilder>(_logger)); + } // Add subsystem defined in shared libraries - list<string> lstrError; - bool bLoadPluginsSuccess = loadSubsystemsFromSharedLibraries(lstrError, pSubsystemPlugins); - - if (bLoadPluginsSuccess) { - log_info("All subsystem plugins successfully loaded"); - } else { - // Log plugin as warning if no fallback available - log_table(!bVirtualSubsystemFallback, lstrError); - } + core::Results errors; + bool bLoadPluginsSuccess = loadSubsystemsFromSharedLibraries(errors, pSubsystemPlugins); - if (!bVirtualSubsystemFallback) { - // Any problem reported is an error as there is no fallback. - // Fill strError for caller. - CUtility::asString(lstrError, strError); - } + // Fill strError for caller, he has to decide if there is a problem depending on + // bVirtualSubsystemFallback value + strError = utility::asString(errors); return bLoadPluginsSuccess || bVirtualSubsystemFallback; } -bool CSystemClass::loadSubsystemsFromSharedLibraries(list<string>& lstrError, - const CSubsystemPlugins* pSubsystemPlugins) +bool CSystemClass::loadSubsystemsFromSharedLibraries(core::Results &errors, + const CSubsystemPlugins *pSubsystemPlugins) { // Plugin list list<string> lstrPluginFiles; - uint32_t uiPluginLocation; + size_t pluginLocation; - for (uiPluginLocation = 0; uiPluginLocation < pSubsystemPlugins->getNbChildren(); uiPluginLocation++) { + for (pluginLocation = 0; pluginLocation < pSubsystemPlugins->getNbChildren(); + pluginLocation++) { // Get Folder for current Plugin Location - const CPluginLocation* pPluginLocation = static_cast<const CPluginLocation*>(pSubsystemPlugins->getChild(uiPluginLocation)); + const CPluginLocation *pPluginLocation = + static_cast<const CPluginLocation *>(pSubsystemPlugins->getChild(pluginLocation)); string strFolder(pPluginLocation->getFolder()); if (!strFolder.empty()) { @@ -149,7 +140,7 @@ bool CSystemClass::loadSubsystemsFromSharedLibraries(list<string>& lstrError, // Iterator on Plugin List: list<string>::const_iterator it; - const list<string>& pluginList = pPluginLocation->getPluginList(); + const list<string> &pluginList = pPluginLocation->getPluginList(); for (it = pluginList.begin(); it != pluginList.end(); ++it) { @@ -167,7 +158,7 @@ bool CSystemClass::loadSubsystemsFromSharedLibraries(list<string>& lstrError, // process failed to load at least one of them // Attempt to load the complete list - if (!loadPlugins(lstrPluginFiles, lstrError)) { + if (!loadPlugins(lstrPluginFiles, errors)) { // Unable to load at least one plugin break; @@ -176,41 +167,16 @@ bool CSystemClass::loadSubsystemsFromSharedLibraries(list<string>& lstrError, if (!lstrPluginFiles.empty()) { // Unable to load at least one plugin - string strPluginUnloaded; - CUtility::asString(lstrPluginFiles, strPluginUnloaded, ", "); - - lstrError.push_back("Unable to load the following plugins: " + strPluginUnloaded + "."); + errors.push_back("Unable to load the following plugins: " + + utility::asString(lstrPluginFiles, ", ") + "."); return false; } return true; } -// Plugin symbol computation -string CSystemClass::getPluginSymbol(const string& strPluginPath) -{ - // Extract plugin type out of file name - string strPluginSuffix = gpcPluginSuffix; - string strPluginPrefix = gpcPluginPrefix; - - // Remove folder and library prefix - size_t iPluginTypePos = strPluginPath.rfind('/') + 1 + strPluginPrefix.length(); - - // Get index of -subsystem.so or -subsystem_host.so suffix - size_t iSubsystemPos = strPluginPath.find(strPluginSuffix, iPluginTypePos); - - // Get type (between iPluginTypePos and iSubsystemPos) - string strPluginType = strPluginPath.substr(iPluginTypePos, iSubsystemPos - iPluginTypePos); - - // Make it upper case - std::transform(strPluginType.begin(), strPluginType.end(), strPluginType.begin(), ::toupper); - - // Get plugin symbol - return gpcPluginSymbolPrefix + strPluginType + gpcPluginSymbolSuffix; -} - // Plugin loading -bool CSystemClass::loadPlugins(list<string>& lstrPluginFiles, list<string>& lstrError) +bool CSystemClass::loadPlugins(list<string> &lstrPluginFiles, core::Results &errors) { assert(lstrPluginFiles.size()); @@ -222,39 +188,24 @@ bool CSystemClass::loadPlugins(list<string>& lstrPluginFiles, list<string>& lstr string strPluginFileName = *it; - log_info("Attempting to load subsystem plugin path \"%s\"", strPluginFileName.c_str()); - // Load attempt - void* lib_handle = dlopen(strPluginFileName.c_str(), RTLD_LAZY); + try { + auto library = utility::make_unique<DynamicLibrary>(strPluginFileName); - if (!lib_handle) { + // Load symbol from library + auto subSystemBuilder = library->getSymbol<PluginEntryPointV1>(entryPointSymbol); - const char *err = dlerror(); - // Failed - if (err == NULL) { - lstrError.push_back("dlerror failed"); - } else { - lstrError.push_back("Plugin load failed: " + string(err)); - } - // Next plugin - ++it; - - continue; - } - - // Store libraries handles - _subsystemLibraryHandleList.push_back(lib_handle); + // Store libraries handles + _subsystemLibraryHandleList.push_back(std::move(library)); - // Get plugin symbol - string strPluginSymbol = getPluginSymbol(strPluginFileName); + // Fill library + subSystemBuilder(_pSubsystemLibrary, _logger); - // Load symbol from library - GetSubsystemBuilder pfnGetSubsystemBuilder = (GetSubsystemBuilder)dlsym(lib_handle, strPluginSymbol.c_str()); + } catch (std::exception &e) { + errors.push_back(e.what()); - if (!pfnGetSubsystemBuilder) { - - lstrError.push_back("Subsystem plugin " + strPluginFileName + - " does not contain " + strPluginSymbol + " symbol."); + // Next plugin + ++it; continue; } @@ -262,9 +213,6 @@ bool CSystemClass::loadPlugins(list<string>& lstrPluginFiles, list<string>& lstr // Account for this success bAtLeastOneSubsystemPluginSuccessfullyLoaded = true; - // Fill library - pfnGetSubsystemBuilder(_pSubsystemLibrary); - // Remove successfully loaded plugin from list and select next lstrPluginFiles.erase(it++); } @@ -272,24 +220,24 @@ bool CSystemClass::loadPlugins(list<string>& lstrPluginFiles, list<string>& lstr return bAtLeastOneSubsystemPluginSuccessfullyLoaded; } -const CSubsystemLibrary* CSystemClass::getSubsystemLibrary() const +const CSubsystemLibrary *CSystemClass::getSubsystemLibrary() const { return _pSubsystemLibrary; } -void CSystemClass::checkForSubsystemsToResync(CSyncerSet& syncerSet) +void CSystemClass::checkForSubsystemsToResync(CSyncerSet &syncerSet, core::Results &infos) { size_t uiNbChildren = getNbChildren(); size_t uiChild; for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - CSubsystem* pSubsystem = static_cast<CSubsystem*>(getChild(uiChild)); + CSubsystem *pSubsystem = static_cast<CSubsystem *>(getChild(uiChild)); // Collect and consume the need for a resync if (pSubsystem->needResync(true)) { - log_info("Resynchronizing subsystem: %s", pSubsystem->getName().c_str()); + infos.push_back("Resynchronizing subsystem: " + pSubsystem->getName()); // get all subsystem syncers pSubsystem->fillSyncerSet(syncerSet); } @@ -303,7 +251,7 @@ void CSystemClass::cleanSubsystemsNeedToResync() for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - CSubsystem* pSubsystem = static_cast<CSubsystem*>(getChild(uiChild)); + CSubsystem *pSubsystem = static_cast<CSubsystem *>(getChild(uiChild)); // Consume the need for a resync pSubsystem->needResync(true); diff --git a/parameter/SystemClass.h b/parameter/SystemClass.h index dd215a6..43a581b 100644 --- a/parameter/SystemClass.h +++ b/parameter/SystemClass.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,15 +31,23 @@ #include "ConfigurableElement.h" #include "SubsystemPlugins.h" +#include "Results.h" +#include <log/Logger.h> #include <list> #include <string> +#include <memory> class CSubsystemLibrary; +class DynamicLibrary; -class CSystemClass : public CConfigurableElement +class CSystemClass final : public CConfigurableElement { public: - CSystemClass(); + /** + * @param[in] logger the logger provided by the client + * it need to be given to the subsystem library + */ + CSystemClass(core::log::Logger &logger); virtual ~CSystemClass(); /** Load subsystem plugin and fill the corresponding libraries. @@ -52,10 +60,10 @@ public: * @return true if the plugins succesfully started or that a fallback is available, false otherwise. */ - bool loadSubsystems(std::string& strError, const CSubsystemPlugins* pSubsystemPlugins, + bool loadSubsystems(std::string &strError, const CSubsystemPlugins *pSubsystemPlugins, bool bVirtualSubsystemFallback = false); // Subsystem factory - const CSubsystemLibrary* getSubsystemLibrary() const; + const CSubsystemLibrary *getSubsystemLibrary() const; /** * Look for subsystems that need to be resynchronized. @@ -63,8 +71,9 @@ public: * and fill a syncer set with all syncers that need to be resynchronized * * @param[out] syncerSet The syncer set to fill + * @param[out] infos Relevant informations client may want to log */ - void checkForSubsystemsToResync(CSyncerSet& syncerSet); + void checkForSubsystemsToResync(CSyncerSet &syncerSet, core::Results &infos); /** * Reset subsystems need to resync flag. @@ -74,39 +83,46 @@ public: // base virtual std::string getKind() const; + bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const override; + std::string getFormattedMapping() const override; + private: - CSystemClass(const CSystemClass&); - CSystemClass& operator=(const CSystemClass&); + CSystemClass(const CSystemClass &); + CSystemClass &operator=(const CSystemClass &); // base virtual bool childrenAreDynamic() const; /** Load shared libraries subsystem plugins. * - * @param[out] lstrError is the list of error that occured during loadings. + * @param[out] errors is the list of error that occured during loadings. * @param[in] pSubsystemPlugins The plugins to load. * * @return true if all plugins have been succesfully loaded, false otherwises. */ - bool loadSubsystemsFromSharedLibraries(std::list<std::string>& lstrError, - const CSubsystemPlugins* pSubsystemPlugins); - - // Plugin symbol computation - static std::string getPluginSymbol(const std::string& strPluginPath); + bool loadSubsystemsFromSharedLibraries(core::Results &errors, + const CSubsystemPlugins *pSubsystemPlugins); /** Load subsystem plugin shared libraries. * - * @param[in:out] lstrPluginFiles is the path list of the plugins shared libraries to load. + * @param[in,out] lstrPluginFiles is the path list of the plugins shared libraries to load. * Successfully loaded plugins are removed from the list. - * @param[out] lstrError is the list of error that occured during loadings. + * @param[out] errors is the list of error that occured during loadings. * * @return true if at least one plugin has been succesfully loaded, false otherwise. * When false is returned, some plugins MIHGT have been loaded * but the lstrPluginFiles is accurate. */ - bool loadPlugins(std::list<std::string>& lstrPluginFiles, std::list<std::string>& lstrError); + bool loadPlugins(std::list<std::string> &lstrPluginFiles, core::Results &errors); // Subsystem factory - CSubsystemLibrary* _pSubsystemLibrary; - std::list<void*> _subsystemLibraryHandleList; /**< Contains the list of all open plugin libs. */ -}; + CSubsystemLibrary *_pSubsystemLibrary; + std::list<std::unique_ptr<DynamicLibrary>> + _subsystemLibraryHandleList; /**< Contains the list of all open plugin libs. */ + + /** Application Logger we need to provide to plugins */ + core::log::Logger &_logger; + /** The entry point symbol that must be implemented by plugins + */ + static const char entryPointSymbol[]; +}; diff --git a/parameter/TypeElement.cpp b/parameter/TypeElement.cpp index 01b7137..e6b9276 100644 --- a/parameter/TypeElement.cpp +++ b/parameter/TypeElement.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,11 +31,13 @@ #include "MappingData.h" #include "Tokenizer.h" #include "InstanceConfigurableElement.h" +#include "Utility.h" +#include <list> #include <assert.h> #define base CElement -CTypeElement::CTypeElement(const std::string& strName) : base(strName), _uiArrayLength(0), _pMappingData(NULL) +CTypeElement::CTypeElement(const std::string &strName) : base(strName) { } @@ -46,12 +48,12 @@ CTypeElement::~CTypeElement() bool CTypeElement::isScalar() const { - return !_uiArrayLength; + return !_arrayLength; } -uint32_t CTypeElement::getArrayLength() const +size_t CTypeElement::getArrayLength() const { - return _uiArrayLength; + return _arrayLength; } int CTypeElement::toPlainInteger(int iSizeOptimizedData) const @@ -59,7 +61,7 @@ int CTypeElement::toPlainInteger(int iSizeOptimizedData) const return iSizeOptimizedData; } -bool CTypeElement::getMappingData(const std::string& strKey, const std::string*& pStrValue) const +bool CTypeElement::getMappingData(const std::string &strKey, const std::string *&pStrValue) const { if (_pMappingData) { @@ -74,7 +76,7 @@ bool CTypeElement::hasMappingData() const } // Element properties -void CTypeElement::showProperties(std::string& strResult) const +void CTypeElement::showProperties(std::string &strResult) const { // The description attribute may be found in the type and not from instance. showDescriptionProperty(strResult); @@ -83,7 +85,7 @@ void CTypeElement::showProperties(std::string& strResult) const // which have a common base Element) } -void CTypeElement::populate(CElement* pElement) const +void CTypeElement::populate(CElement *pElement) const { // Populate children size_t uiChild; @@ -91,38 +93,40 @@ void CTypeElement::populate(CElement* pElement) const for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { - const CTypeElement* pChildTypeElement = static_cast<const CTypeElement*>(getChild(uiChild)); + const CTypeElement *pChildTypeElement = + static_cast<const CTypeElement *>(getChild(uiChild)); - CInstanceConfigurableElement* pInstanceConfigurableChildElement = pChildTypeElement->instantiate(); + CInstanceConfigurableElement *pInstanceConfigurableChildElement = + pChildTypeElement->instantiate(); // Affiliate pElement->addChild(pInstanceConfigurableChildElement); } } -bool CTypeElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CTypeElement::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Array Length attribute - if (xmlElement.hasAttribute("ArrayLength")) { - - _uiArrayLength = xmlElement.getAttributeInteger("ArrayLength"); - } else { - _uiArrayLength = 0; // Scalar - } + xmlElement.getAttribute("ArrayLength", _arrayLength); // Manage mapping attribute - if (xmlElement.hasAttribute("Mapping")) { + std::string rawMapping; + if (xmlElement.getAttribute("Mapping", rawMapping) && !rawMapping.empty()) { - if (!getMappingData()->fromXml(xmlElement, serializingContext)) { + std::string error; + if (!getMappingData()->init(rawMapping, error)) { + serializingContext.setError("Invalid Mapping data from XML element '" + + xmlElement.getPath() + "': " + error); return false; } } return base::fromXml(xmlElement, serializingContext); } -CInstanceConfigurableElement* CTypeElement::instantiate() const +CInstanceConfigurableElement *CTypeElement::instantiate() const { - CInstanceConfigurableElement* pInstanceConfigurableElement = doInstantiate(); + CInstanceConfigurableElement *pInstanceConfigurableElement = doInstantiate(); // Populate populate(pInstanceConfigurableElement); @@ -130,7 +134,7 @@ CInstanceConfigurableElement* CTypeElement::instantiate() const return pInstanceConfigurableElement; } -CMappingData* CTypeElement::getMappingData() +CMappingData *CTypeElement::getMappingData() { if (!_pMappingData) { @@ -139,6 +143,30 @@ CMappingData* CTypeElement::getMappingData() return _pMappingData; } +std::string CTypeElement::getFormattedMapping(const CTypeElement *predecessor) const +{ + std::list<std::string> mappings; + std::string mapping; + + // Try predecessor type first, then myself (in order to have higher-level + // mappings displayed first) + if (predecessor) { + mapping = predecessor->getFormattedMapping(); + if (not mapping.empty()) { + mappings.push_back(mapping); + } + } + + // Explicitly call the root implementation instead of calling it virtually + // (otherwise, it will infinitely recurse). + mapping = CTypeElement::getFormattedMapping(); + if (not mapping.empty()) { + mappings.push_back(mapping); + } + + return utility::asString(mappings, ", "); +} + std::string CTypeElement::getFormattedMapping() const { if (_pMappingData) { @@ -149,11 +177,11 @@ std::string CTypeElement::getFormattedMapping() const } // From IXmlSource -void CTypeElement::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +void CTypeElement::toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const { if (!isScalar()) { - xmlElement.setAttributeInteger("ArrayLength", getArrayLength()); + xmlElement.setAttribute("ArrayLength", getArrayLength()); } base::toXml(xmlElement, serializingContext); diff --git a/parameter/TypeElement.h b/parameter/TypeElement.h index 8f474c0..9d8f46f 100644 --- a/parameter/TypeElement.h +++ b/parameter/TypeElement.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,23 +29,25 @@ */ #pragma once +#include "parameter_export.h" + #include "Element.h" #include <string> class CMappingData; class CInstanceConfigurableElement; -class CTypeElement : public CElement +class PARAMETER_EXPORT CTypeElement : public CElement { public: - CTypeElement(const std::string& strName = ""); + CTypeElement(const std::string &strName = ""); virtual ~CTypeElement(); // Instantiation - CInstanceConfigurableElement* instantiate() const; + CInstanceConfigurableElement *instantiate() const; // Mapping info - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const; + virtual bool getMappingData(const std::string &strKey, const std::string *&pStrValue) const; virtual bool hasMappingData() const; /** @@ -56,19 +58,19 @@ public: virtual std::string getFormattedMapping() const; // Element properties - virtual void showProperties(std::string& strResult) const; + virtual void showProperties(std::string &strResult) const; // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); // From IXmlSource - virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const; + virtual void toXml(CXmlElement &xmlElement, CXmlSerializingContext &serializingContext) const; // Scalar or Array? bool isScalar() const; // Array Length - uint32_t getArrayLength() const; + size_t getArrayLength() const; /** * Converts size optimized integer input data (int8, int16, int32) to plain int @@ -81,19 +83,31 @@ public: protected: // Object creation - virtual void populate(CElement* pElement) const; + virtual void populate(CElement *pElement) const; + /** @Returns the mapping associated to the current type and its predecessor + * + * The meaning of predecessor depends on the TypeElement type: e.g. for a + * component instance, the predecessor is the ComponentType; for a + * ComponentType, the predecessor is its base type. + * + * The predecessor's mapping comes first, then the current type's mapping. + * + * @param[in] predecessor A pointer to the predecessor or NULL. + */ + std::string getFormattedMapping(const CTypeElement *predecessor) const; + private: - CTypeElement(const CTypeElement&); - CTypeElement& operator=(const CTypeElement&); + CTypeElement(const CTypeElement &); + CTypeElement &operator=(const CTypeElement &); // Actual instance creation - virtual CInstanceConfigurableElement* doInstantiate() const = 0; + virtual CInstanceConfigurableElement *doInstantiate() const = 0; // Mapping data creation and access - CMappingData* getMappingData(); + CMappingData *getMappingData(); // For Arrays. 0 means scalar - uint32_t _uiArrayLength; + size_t _arrayLength{0}; // Mapping info - CMappingData* _pMappingData; + CMappingData *_pMappingData{nullptr}; }; diff --git a/parameter/VirtualSubsystem.cpp b/parameter/VirtualSubsystem.cpp index 36027bf..4bb7a17 100644 --- a/parameter/VirtualSubsystem.cpp +++ b/parameter/VirtualSubsystem.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,14 +29,18 @@ */ #include "VirtualSubsystem.h" #include "VirtualSyncer.h" +#include "SyncerSet.h" #define base CSubsystem using std::string; -CVirtualSubsystem::CVirtualSubsystem(const string& strName) - : base(strName), _pVirtualSyncer(new CVirtualSyncer(this)) +CVirtualSubsystem::CVirtualSubsystem(const string &strName, core::log::Logger &logger) + : base(strName, logger), _pVirtualSyncer(new CVirtualSyncer(this)) { + logger.warning() << "Subsystem " << strName + << " loaded as virtual. " + "Its parameters will not be synced with any external system."; } CVirtualSubsystem::~CVirtualSubsystem() @@ -45,17 +49,20 @@ CVirtualSubsystem::~CVirtualSubsystem() } // Syncer -ISyncer* CVirtualSubsystem::getSyncer() const +ISyncer *CVirtualSubsystem::getSyncer() const { return _pVirtualSyncer; } -// From IMapper -bool CVirtualSubsystem::mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, string& strError) +void CVirtualSubsystem::fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const { - (void)pInstanceConfigurableElement; - (void)strError; + syncerSet += _pVirtualSyncer; +} +// From IMapper +bool CVirtualSubsystem::mapBegin(CInstanceConfigurableElement * /*elem*/, bool &bKeepDiving, + string & /*strError*/) +{ // Do nothing: prevent any subsystem object from being mapped // Stop diving diff --git a/parameter/VirtualSubsystem.h b/parameter/VirtualSubsystem.h index 3a9c89b..8590361 100644 --- a/parameter/VirtualSubsystem.h +++ b/parameter/VirtualSubsystem.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -35,21 +35,34 @@ class CVirtualSyncer; -class CVirtualSubsystem : public CSubsystem +class CVirtualSubsystem final : public CSubsystem { public: - CVirtualSubsystem(const std::string& strName); + /** + * @param[in] strName subsystem name + * @param[in] logger the main logger of the application + */ + CVirtualSubsystem(const std::string &strName, core::log::Logger &logger); virtual ~CVirtualSubsystem(); protected: // Syncer - virtual ISyncer* getSyncer() const; + virtual ISyncer *getSyncer() const; + + /** + * Fill Syncer Set From descendant nodes + * + * This functionality allows to collect the syncers when crawling down the + * parameter tree. + */ + void fillSyncerSetFromDescendant(CSyncerSet &syncerSet) const override; private: // From IMapper - virtual bool mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, std::string& strError); + virtual bool mapBegin(CInstanceConfigurableElement *pInstanceConfigurableElement, + bool &bKeepDiving, std::string &strError); virtual void mapEnd(); // Subsystem level dummy syncer - CVirtualSyncer* _pVirtualSyncer; + CVirtualSyncer *_pVirtualSyncer; }; diff --git a/parameter/VirtualSyncer.cpp b/parameter/VirtualSyncer.cpp index 5ab889f..5bb8ef4 100644 --- a/parameter/VirtualSyncer.cpp +++ b/parameter/VirtualSyncer.cpp @@ -33,17 +33,18 @@ using std::string; -CVirtualSyncer::CVirtualSyncer(const CConfigurableElement* pConfigurableElement) : _pConfigurableElement(pConfigurableElement) +CVirtualSyncer::CVirtualSyncer(const CConfigurableElement *pConfigurableElement) + : _pConfigurableElement(pConfigurableElement) { } // Synchronization -bool CVirtualSyncer::sync(CParameterBlackboard& parameterBlackboard, bool bBack, string& strError) +bool CVirtualSyncer::sync(CParameterBlackboard ¶meterBlackboard, bool bBack, string &strError) { // Synchronize to/from HW if (bBack) { // Create access context - CParameterAccessContext parameterAccessContext(strError, ¶meterBlackboard, false); + CParameterAccessContext parameterAccessContext(strError, ¶meterBlackboard); // Just implement back synchronization with default values _pConfigurableElement->setDefaultValues(parameterAccessContext); diff --git a/parameter/VirtualSyncer.h b/parameter/VirtualSyncer.h index 30254cb..3942678 100644 --- a/parameter/VirtualSyncer.h +++ b/parameter/VirtualSyncer.h @@ -36,10 +36,11 @@ class CConfigurableElement; class CVirtualSyncer : public ISyncer { public: - CVirtualSyncer(const CConfigurableElement* pConfigurableElement); + CVirtualSyncer(const CConfigurableElement *pConfigurableElement); // from ISyncer - virtual bool sync(CParameterBlackboard& parameterBlackboard, bool bBack, std::string& strError); + virtual bool sync(CParameterBlackboard ¶meterBlackboard, bool bBack, std::string &strError); + private: - const CConfigurableElement* _pConfigurableElement; + const CConfigurableElement *_pConfigurableElement; }; diff --git a/parameter/XmlDomainExportContext.h b/parameter/XmlDomainExportContext.h index 22ad995..02a517e 100644 --- a/parameter/XmlDomainExportContext.h +++ b/parameter/XmlDomainExportContext.h @@ -35,36 +35,22 @@ class CXmlDomainExportContext : public CXmlDomainSerializingContext { public: - CXmlDomainExportContext(std::string& strError, - bool bWithSettings = true, - bool bValueSpaceIsRaw = true, - bool bOutputRawFormatIsHex = true): - base(strError, bWithSettings), - _bValueSpaceIsRaw(bValueSpaceIsRaw), - _bOutputRawFormatIsHex(bOutputRawFormatIsHex) - {} - - // Value interpretation as Real or Raw - void setValueSpaceRaw(bool bIsRaw) + CXmlDomainExportContext(std::string &strError, bool bWithSettings = true, + bool bValueSpaceIsRaw = true, bool bOutputRawFormatIsHex = true) + : base(strError, bWithSettings), _bValueSpaceIsRaw(bValueSpaceIsRaw), + _bOutputRawFormatIsHex(bOutputRawFormatIsHex) { - _bValueSpaceIsRaw = bIsRaw; } - bool valueSpaceIsRaw() const - { - return _bValueSpaceIsRaw; - } + // Value interpretation as Real or Raw + void setValueSpaceRaw(bool bIsRaw) { _bValueSpaceIsRaw = bIsRaw; } + + bool valueSpaceIsRaw() const { return _bValueSpaceIsRaw; } // Output Raw Format for user get value interpretation - void setOutputRawFormat(bool bIsHex) - { - _bOutputRawFormatIsHex = bIsHex; - } + void setOutputRawFormat(bool bIsHex) { _bOutputRawFormatIsHex = bIsHex; } - bool outputRawFormatIsHex() const - { - return _bOutputRawFormatIsHex; - } + bool outputRawFormatIsHex() const { return _bOutputRawFormatIsHex; } private: typedef CXmlDomainSerializingContext base; @@ -74,5 +60,4 @@ private: // Output Raw Format bool _bOutputRawFormatIsHex; - }; diff --git a/parameter/XmlDomainImportContext.h b/parameter/XmlDomainImportContext.h index 11090b0..17404f1 100644 --- a/parameter/XmlDomainImportContext.h +++ b/parameter/XmlDomainImportContext.h @@ -38,23 +38,22 @@ class CXmlDomainImportContext : public CXmlDomainSerializingContext { public: - CXmlDomainImportContext(std::string& strError, bool bWithSettings, CSystemClass& systemClass): - base(strError, bWithSettings), _systemClass(systemClass), _bAutoValidationRequired(true) {} - - // System Class - CSystemClass& getSystemClass() const + CXmlDomainImportContext(std::string &strError, bool bWithSettings, CSystemClass &systemClass) + : base(strError, bWithSettings), _systemClass(systemClass) { - return _systemClass; } + // System Class + CSystemClass &getSystemClass() const { return _systemClass; } + // Criteria defintion void setSelectionCriteriaDefinition( - const CSelectionCriteriaDefinition* pSelectionCriteriaDefinition) + const CSelectionCriteriaDefinition *pSelectionCriteriaDefinition) { _pSelectionCriteriaDefinition = pSelectionCriteriaDefinition; } - const CSelectionCriteriaDefinition* getSelectionCriteriaDefinition() const + const CSelectionCriteriaDefinition *getSelectionCriteriaDefinition() const { return _pSelectionCriteriaDefinition; } @@ -65,21 +64,17 @@ public: _bAutoValidationRequired = bAutoValidationRequired; } - bool autoValidationRequired() const - { - return _bAutoValidationRequired; - } + bool autoValidationRequired() const { return _bAutoValidationRequired; } private: typedef CXmlDomainSerializingContext base; // System Class - CSystemClass& _systemClass; + CSystemClass &_systemClass; // Criteria defintion - const CSelectionCriteriaDefinition* _pSelectionCriteriaDefinition; + const CSelectionCriteriaDefinition *_pSelectionCriteriaDefinition{nullptr}; // Auto validation of configurations - bool _bAutoValidationRequired; + bool _bAutoValidationRequired{true}; }; - diff --git a/parameter/XmlDomainSerializingContext.h b/parameter/XmlDomainSerializingContext.h index 955d939..49c2733 100644 --- a/parameter/XmlDomainSerializingContext.h +++ b/parameter/XmlDomainSerializingContext.h @@ -36,15 +36,14 @@ class CXmlDomainSerializingContext : public CXmlElementSerializingContext { public: - CXmlDomainSerializingContext(std::string& strError, bool bWithSettings): - base(strError), _bWithSettings(bWithSettings) {} - - // Settings to be serialized or not - bool withSettings() const + CXmlDomainSerializingContext(std::string &strError, bool bWithSettings) + : base(strError), _bWithSettings(bWithSettings) { - return _bWithSettings; } + // Settings to be serialized or not + bool withSettings() const { return _bWithSettings; } + private: typedef CXmlElementSerializingContext base; diff --git a/parameter/XmlElementSerializingContext.cpp b/parameter/XmlElementSerializingContext.cpp index 6046d8e..491f160 100644 --- a/parameter/XmlElementSerializingContext.cpp +++ b/parameter/XmlElementSerializingContext.cpp @@ -28,39 +28,31 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "XmlElementSerializingContext.h" -#include <stdlib.h> #define base CXmlSerializingContext using std::string; -CXmlElementSerializingContext::CXmlElementSerializingContext(string& strError) : base(strError), _pElementLibrary(NULL) +CXmlElementSerializingContext::CXmlElementSerializingContext(string &strError) : base(strError) { } // Init -void CXmlElementSerializingContext::set(const CElementLibrary* pElementLibrary, const string& strXmlFolder, const string& strXmlSchemaFolder) +void CXmlElementSerializingContext::set(const CElementLibrary *pElementLibrary, + const string &xmlUri) { _pElementLibrary = pElementLibrary; - _strXmlFolder = strXmlFolder; - _strXmlSchemaFolder = strXmlSchemaFolder; + _xmlUri = xmlUri; } // ElementLibrary -const CElementLibrary* CXmlElementSerializingContext::getElementLibrary() const +const CElementLibrary *CXmlElementSerializingContext::getElementLibrary() const { return _pElementLibrary; } // XML Folder Path -const string& CXmlElementSerializingContext::getXmlFolder() const +const string &CXmlElementSerializingContext::getXmlUri() const { - return _strXmlFolder; + return _xmlUri; } - -// XML Schema Path -const string& CXmlElementSerializingContext::getXmlSchemaPathFolder() const -{ - return _strXmlSchemaFolder; -} - diff --git a/parameter/XmlElementSerializingContext.h b/parameter/XmlElementSerializingContext.h index dadb1da..3169d40 100644 --- a/parameter/XmlElementSerializingContext.h +++ b/parameter/XmlElementSerializingContext.h @@ -38,21 +38,18 @@ class CElementLibrary; class CXmlElementSerializingContext : public CXmlSerializingContext { public: - CXmlElementSerializingContext(std::string& strError); + CXmlElementSerializingContext(std::string &strError); // Init - void set(const CElementLibrary* pElementLibrary, const std::string& strXmlFolder, const std::string& strXmlSchemaFolder); + void set(const CElementLibrary *pElementLibrary, const std::string &xmlUri); // ElementLibrary - const CElementLibrary* getElementLibrary() const; + const CElementLibrary *getElementLibrary() const; - // XML File Path - const std::string& getXmlFolder() const; + // Xml URI + const std::string &getXmlUri() const; - // Schema Path - const std::string& getXmlSchemaPathFolder() const; private: - const CElementLibrary* _pElementLibrary; - std::string _strXmlFolder; - std::string _strXmlSchemaFolder; + const CElementLibrary *_pElementLibrary{nullptr}; + std::string _xmlUri; }; diff --git a/parameter/XmlFileIncluderElement.cpp b/parameter/XmlFileIncluderElement.cpp index d20a624..b736a24 100644 --- a/parameter/XmlFileIncluderElement.cpp +++ b/parameter/XmlFileIncluderElement.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -32,54 +32,43 @@ #include "XmlMemoryDocSink.h" #include "XmlElementSerializingContext.h" #include "ElementLibrary.h" -#include "AutoLog.h" #include <assert.h> #include <fstream> #define base CKindElement -CXmlFileIncluderElement::CXmlFileIncluderElement(const std::string& strName, - const std::string& strKind, - bool bValidateWithSchemas) - : base(strName, strKind), _bValidateSchemasOnStart(bValidateWithSchemas) +CXmlFileIncluderElement::CXmlFileIncluderElement(const std::string &strName, + const std::string &strKind, + bool bValidateWithSchemas, + const std::string &schemaBaseUri) + : base(strName, strKind), _bValidateSchemasOnStart(bValidateWithSchemas), + _schemaBaseUri(schemaBaseUri) { } // From IXmlSink -bool CXmlFileIncluderElement::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +bool CXmlFileIncluderElement::fromXml(const CXmlElement &xmlElement, + CXmlSerializingContext &serializingContext) { // Context - CXmlElementSerializingContext& elementSerializingContext = static_cast<CXmlElementSerializingContext&>(serializingContext); + CXmlElementSerializingContext &elementSerializingContext = + static_cast<CXmlElementSerializingContext &>(serializingContext); // Parse included document - std::string strPath = xmlElement.getAttributeString("Path"); - - // Relative path? - if (strPath[0] != '/') { - - strPath = elementSerializingContext.getXmlFolder() + "/" + strPath; - } + std::string strPath; + xmlElement.getAttribute("Path", strPath); + strPath = CXmlDocSource::mkUri(elementSerializingContext.getXmlUri(), strPath); // Instantiate parser std::string strIncludedElementType = getIncludedElementType(); { - // Open a log section titled with loading file path - CAutoLog autolog(this, "Loading " + strPath); + _xmlDoc *doc = CXmlDocSource::mkXmlDoc(strPath, true, true, elementSerializingContext); - // Use a doc source that load data from a file - std::string strPathToXsdFile = elementSerializingContext.getXmlSchemaPathFolder() + "/" + - strIncludedElementType + ".xsd"; + CXmlDocSource docSource(doc, _bValidateSchemasOnStart, strIncludedElementType); - std::string xmlErrorMsg; - _xmlDoc *doc = CXmlDocSource::mkXmlDoc(strPath, true, true, xmlErrorMsg); - if (doc == NULL) { - elementSerializingContext.setError(xmlErrorMsg); - return false; + if (not _schemaBaseUri.empty()) { + docSource.setSchemaBaseUri(_schemaBaseUri); } - CXmlDocSource docSource(doc, _bValidateSchemasOnStart, - strPathToXsdFile, - strIncludedElementType); - if (!docSource.isParsable()) { elementSerializingContext.setError("Could not parse document \"" + strPath + "\""); @@ -93,7 +82,8 @@ bool CXmlFileIncluderElement::fromXml(const CXmlElement& xmlElement, CXmlSeriali docSource.getRootElement(childElement); // Create child element - CElement* pChild = elementSerializingContext.getElementLibrary()->createElement(childElement); + CElement *pChild = + elementSerializingContext.getElementLibrary()->createElement(childElement); if (pChild) { @@ -101,7 +91,8 @@ bool CXmlFileIncluderElement::fromXml(const CXmlElement& xmlElement, CXmlSeriali getParent()->addChild(pChild); } else { - elementSerializingContext.setError("Unable to create XML element " + childElement.getPath()); + elementSerializingContext.setError("Unable to create XML element " + + childElement.getPath()); return false; } diff --git a/parameter/XmlFileIncluderElement.h b/parameter/XmlFileIncluderElement.h index 9163356..144e078 100644 --- a/parameter/XmlFileIncluderElement.h +++ b/parameter/XmlFileIncluderElement.h @@ -37,13 +37,14 @@ class CXmlFileIncluderElement : public CKindElement { public: - CXmlFileIncluderElement(const std::string& strName, - const std::string& strKind, - bool bValidateWithSchemas); + CXmlFileIncluderElement(const std::string &strName, const std::string &strKind, + bool bValidateWithSchemas, const std::string &schemaBaseUri); // From IXmlSink - virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext); + virtual bool fromXml(const CXmlElement &xmlElement, CXmlSerializingContext &serializingContext); + private: // Element type std::string getIncludedElementType() const; bool _bValidateSchemasOnStart; + const std::string _schemaBaseUri; }; diff --git a/parameter/XmlParameterSerializingContext.cpp b/parameter/XmlParameterSerializingContext.cpp index 12de305..c13c5ae 100644 --- a/parameter/XmlParameterSerializingContext.cpp +++ b/parameter/XmlParameterSerializingContext.cpp @@ -33,19 +33,20 @@ using std::string; -CXmlParameterSerializingContext::CXmlParameterSerializingContext(string& strError) : base(strError) +CXmlParameterSerializingContext::CXmlParameterSerializingContext(CParameterAccessContext &context, + string &strError) + : base(strError), mAccessContext(context) { } // ComponentLibrary -void CXmlParameterSerializingContext::setComponentLibrary(const CComponentLibrary* pComponentLibrary) +void CXmlParameterSerializingContext::setComponentLibrary( + const CComponentLibrary *pComponentLibrary) { _pComponentLibrary = pComponentLibrary; } -const CComponentLibrary* CXmlParameterSerializingContext::getComponentLibrary() const +const CComponentLibrary *CXmlParameterSerializingContext::getComponentLibrary() const { return _pComponentLibrary; } - - diff --git a/parameter/XmlParameterSerializingContext.h b/parameter/XmlParameterSerializingContext.h index 61306ce..05d5a9b 100644 --- a/parameter/XmlParameterSerializingContext.h +++ b/parameter/XmlParameterSerializingContext.h @@ -30,6 +30,7 @@ #pragma once #include "XmlElementSerializingContext.h" +#include "ParameterAccessContext.h" #include <string> @@ -38,11 +39,16 @@ class CComponentLibrary; class CXmlParameterSerializingContext : public CXmlElementSerializingContext { public: - CXmlParameterSerializingContext(std::string& strError); + CXmlParameterSerializingContext(CParameterAccessContext &context, std::string &strError); // ComponentLibrary - void setComponentLibrary(const CComponentLibrary* pComponentLibrary); - const CComponentLibrary* getComponentLibrary() const; + void setComponentLibrary(const CComponentLibrary *pComponentLibrary); + const CComponentLibrary *getComponentLibrary() const; + + CParameterAccessContext &getAccessContext() const { return mAccessContext; } + private: - const CComponentLibrary* _pComponentLibrary; + const CComponentLibrary *_pComponentLibrary{nullptr}; + + CParameterAccessContext &mAccessContext; }; diff --git a/parameter/BinaryStream.h b/parameter/include/CommandHandlerInterface.h index 6df777c..50b7343 100644 --- a/parameter/BinaryStream.h +++ b/parameter/include/CommandHandlerInterface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,50 +29,39 @@ */ #pragma once -#include <stdint.h> #include <string> -#include <fstream> +#include <vector> -class CBinaryStream +/** Class used to send commands to a parameter framework. + * @see the help command for more information on which command can be sent. + * @see ParameterMgrFullConnector::createCommandHandler to create an instance. + * + * This interface is primary designed to send commands without using a + * tcp socket for test purposes. + * + * Note: the fact that this class must be deleted by the client is because the + * PF interface is not c++11. + * TODO: When the interface will transition to C++11, return directly the + * CommandHandlerWrapper as this base class only use is to hide the + * move semantic that is not supported in C++03. + */ +class CommandHandlerInterface { public: - CBinaryStream(const std::string& strFileName, bool bOut, size_t uiDataSize, uint8_t uiStructureChecksum); - ~CBinaryStream(); - - // Open close - bool open(std::string& strError); - void close(); + /** Send a command synchronously and receive it's result. + * + * @see CParameterMgr::gastRemoteCommandParserItems for the list of possible + * command and their description. + * + * @param[in] command the command to execute. + * @param[in] arguments the command arguments. + * @param[out] output the result of the command. + * + * return true in the command executed succesfuly, + * false otherwise. + */ + virtual bool process(const std::string &command, const std::vector<std::string> &arguments, + std::string &output) = 0; - // Seek - void reset(); - - // Read/Write - void write(const uint8_t* puiData, size_t uiSize); - void read(uint8_t* puiData, size_t uiSize); - - // Direction - bool isOut() const; -private: - CBinaryStream(const CBinaryStream&); - CBinaryStream& operator=(const CBinaryStream&); - // Checksum - uint8_t computeChecksum() const; - - // File name - std::string _strFileName; - // Serialization direction - bool _bOut; - // Data size - size_t _uiDataSize; - // System structure checksum - uint8_t _uiStructureChecksum; - // Read/Write data - uint8_t* _puiData; - // File - std::fstream _fileStream; - // Ops in faile - size_t _uiPos; - // File state - bool _bOpen; + virtual ~CommandHandlerInterface(){}; }; - diff --git a/parameter/include/ElementHandle.h b/parameter/include/ElementHandle.h new file mode 100644 index 0000000..7d0888a --- /dev/null +++ b/parameter/include/ElementHandle.h @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +#include "parameter_export.h" + +#include <stdint.h> +#include <string> +#include <vector> + +/** Forward declaration of private classes. + * Client should not use those class. + * They are not part of the public api and may be remove/renamed in any release. + * @{ + */ +class CParameterMgr; +class CConfigurableElement; +class CBaseParameter; +/** @} */ + +/** TODO */ +class PARAMETER_EXPORT ElementHandle +{ +public: + /** @return element's name. */ + std::string getName() const; + + /** @return element's size in bytes. + * + * If the element size in bit is not a multiple of CHAR_BIT (8) + * it is rounded to the upper multiple. + * Effectively returning the element memory footprint. + */ + size_t getSize() const; + + /** @return true if the element is a parameter, false otherwise. */ + bool isParameter() const; + + /** @return a human readable description of the element. */ + std::string getDescription() const; + + /** @return is the element and all its descendant not in a domain. + * + * Only rogue elements are allowed to be set. + * */ + bool isRogue() const; + + /** @return true if the element is an array, false otherwise.*/ + bool isArray() const; + + /** @return the parameter array length. + * 0 if the element is not an array (scalar). + */ + size_t getArrayLength() const; + + /** @return element's path in the parameter hierarchy tree. */ + std::string getPath() const; + + /** @return element's kind. + * + * Ie: a string identifying the type of Element. + */ + std::string getKind() const; + + std::vector<ElementHandle> getChildren(); + + /** Get mapping data of the element context + * + * Retrieve mapping data associated to a given key if any. + * If the key is not present in this element, query ancestors. + * + * @param[in] strKey the input mapping key + * @param[out] strValue the resulting mapping value in case of success + * @return true for if mapping key exists, false otherwise + */ + bool getMappingData(const std::string &strKey, std::string &strValue) const; + + /** Gets element structure description as XML string + * + * @return the output XML string + */ + bool getStructureAsXML(std::string &xmlStructure, std::string &error) const; + + /** Gets element settings as XML string + * + * @param[out] xmlValue the values to get + * @param[out] error On failure (false returned) will contain a human + * readable description of the error. + * On success (true returned) the content is not + * specified. + * + * @note returned value format depends on the current ParameterMgr format + * control properties, including value space and output raw format. + * @see ParameterMgrPlatformConnector::setOutputRawFormat + * @see ParameterMgrPlatformConnector::setValueSpace + * + * @return true on success, false on failure + */ + bool getAsXML(std::string &xmlValue, std::string &error) const; + + /** Sets element settings as XML string + * + * @param[in] xmlValue the values to set + * @param[out] error On failure (false returned) will contain a human + * readable description of the error. + * On success (true returned) the content is not + * specified. + * + * @note + * - targeted element needs to be rogue for this operation to be allowed + * - structure of the passed XML element must match the targeted + * configurable element's one otherwise this operation will fail + * - expected value format depends on current value space. + * @see ParameterMgrPlatformConnector::valueSpaceIsRaw + * + * @return true on success, false otherwise + */ + bool setAsXML(const std::string &xmlValue, std::string &error); + + /** Gets element settings in binary format + * + * @param[out] bytesValue the output vector + * @param[out] error unused + * + * @returns true + */ + bool getAsBytes(std::vector<uint8_t> &bytesValue, std::string &error) const; + + /** Sets element settings in binary format + * + * @param[out] bytesValue the output vector + * @param[out] error On failure (false returned) will contain a human + * readable description of the error. + * On success (true returned) the content is not + * specified. + * + * @note + * - targeted element needs to be rogue for this operation to be allowed + * - size of the passed array must match that of the element + */ + bool setAsBytes(const std::vector<uint8_t> &bytesValue, std::string &error); + + /** Access (get or set) parameters as different types. + * + * Will fail if the element is not a paramete. + * Array access will fail if the parameter is not an array. + * + * @param value if get, the value to get (in parameter) + * if set, the value to set (out parameter) + * + * Setting an array requires the std::vector size to match the arrayLength. + * Ie: value.size() == arrayLength() + * + * @param[out] error On failure (false returned) will contain a human + * readable description of the error. + * On success (true returned) the content is not + * specified. + * @return true if the access was successful, + * false otherwise (see error for the detail) + * @{ + */ + + /** Boolean access @{ */ + bool getAsBoolean(bool &value, std::string &error) const; + bool setAsBoolean(bool value, std::string &error); + bool setAsBooleanArray(const std::vector<bool> &value, std::string &error); + bool getAsBooleanArray(std::vector<bool> &value, std::string &error) const; + /** @} */ + + /** Integer Access @{ */ + bool setAsInteger(uint32_t value, std::string &error); + bool getAsInteger(uint32_t &value, std::string &error) const; + bool setAsIntegerArray(const std::vector<uint32_t> &value, std::string &error); + bool getAsIntegerArray(std::vector<uint32_t> &value, std::string &error) const; + /** @} */ + + /** Signed Integer Access @{ */ + bool setAsSignedInteger(int32_t value, std::string &error); + bool getAsSignedInteger(int32_t &value, std::string &error) const; + bool setAsSignedIntegerArray(const std::vector<int32_t> &value, std::string &error); + bool getAsSignedIntegerArray(std::vector<int32_t> &value, std::string &error) const; + /** @} */ + + /** Double Access @{ */ + bool setAsDouble(double value, std::string &error); + bool getAsDouble(double &value, std::string &error) const; + bool setAsDoubleArray(const std::vector<double> &value, std::string &error); + bool getAsDoubleArray(std::vector<double> &value, std::string &error) const; + /** @} */ + + /** String Access @{ */ + bool setAsString(const std::string &value, std::string &error); + bool getAsString(std::string &value, std::string &error) const; + bool setAsStringArray(const std::vector<std::string> &value, std::string &error); + bool getAsStringArray(std::vector<std::string> &value, std::string &error) const; + /** @} */ + + /** @} */ + +protected: + ElementHandle(CConfigurableElement &element, CParameterMgr ¶meterMgr); + friend CParameterMgr; // So that it can build the handler + +private: + template <class T> + bool setAs(const T value, std::string &error) const; + template <class T> + bool getAs(T &value, std::string &error) const; + + CBaseParameter &getParameter(); + const CBaseParameter &getParameter() const; + + /** Check that the parameter value can be modify. + * + * @param arrayLength[in] If accessing as an array: the new value array length + * Otherwise: 0 + * @param error[out] If access is forbidden: a human readable message explaining why + * Otherwise: not modified. + * + * @return true if the parameter value can be retrieved, false otherwise. + */ + bool checkSetValidity(size_t arrayLength, std::string &error) const; + + /** Check that the parameter value can be retrieved. + * + * @param asArray[in] true if accessing as an array, false otherwise. + * @param error[out] If access is forbidden, a human readable message explaining why + * Otherwise, not modified. + * + * @return true if the parameter value can be retrieved, false otherwise. + */ + bool checkGetValidity(bool asArray, std::string &error) const; + + /** Reference to the handled Configurable element. */ + CConfigurableElement &mElement; + + CParameterMgr &mParameterMgr; +}; diff --git a/parameter/include/ParameterHandle.h b/parameter/include/ParameterHandle.h index 7dd9fcb..75f28e2 100644 --- a/parameter/include/ParameterHandle.h +++ b/parameter/include/ParameterHandle.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,75 +29,25 @@ */ #pragma once -#include <stdint.h> -#include <string> -#include <vector> +#include "parameter_export.h" -class CBaseParameter; -class CParameterMgr; +#include "ElementHandle.h" -class CParameterHandle +/** Pre v3.1 Handle to a parameter. Kept for retro-compatibility. + * @deprecated This class has been deprecated in favor of ElementHandle, + * Use ElementHandle instead of CParameterHandle. + * It is a api retro-compatible superset of the pre v3.1 + * CParameterHandle class. + * @note Achieve retro-compatibility with a derived class instead of an alias + * (`typedef ElementHandle CParameterHandle`) as the later would break + * client compilation in case of client forward declaration. + */ +class PARAMETER_EXPORT CParameterHandle : public ElementHandle { -public: - CParameterHandle(const CBaseParameter* pParameter, CParameterMgr* pParameterMgr); - - // Parameter features - bool isRogue() const; - bool isArray() const; - // Array Length - uint32_t getArrayLength() const; // Returns 0 for scalar - // Parameter path - std::string getPath() const; - // Parameter kind - std::string getKind() const; - - // Boolean access - bool setAsBoolean(bool bValue, std::string& strError); - - /** - * Fetch the parameter value as a boolean. - * - * @param bValue Reference to a boolean variable where the value will be stored - * @param strError Error message if a problem occured - * - * @return true on success, false otherwise - */ - bool getAsBoolean(bool& bValue, std::string& strError) const; - bool setAsBooleanArray(const std::vector<bool>& abValues, std::string& strError); - bool getAsBooleanArray(std::vector<bool>& abValues, std::string& strError) const; - - // Integer Access - bool setAsInteger(uint32_t uiValue, std::string& strError); - bool getAsInteger(uint32_t& uiValue, std::string& strError) const; - bool setAsIntegerArray(const std::vector<uint32_t>& auiValues, std::string& strError); - bool getAsIntegerArray(std::vector<uint32_t>& auiValues, std::string& strError) const; - - // Signed Integer Access - bool setAsSignedInteger(int32_t iValue, std::string& strError); - bool getAsSignedInteger(int32_t& iValue, std::string& strError) const; - bool setAsSignedIntegerArray(const std::vector<int32_t>& aiValues, std::string& strError); - bool getAsSignedIntegerArray(std::vector<int32_t>& aiValues, std::string& strError) const; - - // Double Access - bool setAsDouble(double dValue, std::string& strError); - bool getAsDouble(double& dValue, std::string& strError) const; - bool setAsDoubleArray(const std::vector<double>& adValues, std::string& strError); - bool getAsDoubleArray(std::vector<double>& adValues, std::string& strError) const; - - // String Access - bool setAsString(const std::string& strValue, std::string& strError); - bool getAsString(std::string& strValue, std::string& strError) const; - bool setAsStringArray(const std::vector<std::string>& astrValues, std::string& strError); - bool getAsStringArray(std::vector<std::string>& astrValues, std::string& strError) const; - private: - // Access validity - bool checkAccessValidity(bool bSet, size_t uiArrayLength, std::string& strError) const; - - // Accessed parameter instance - const CBaseParameter* _pBaseParameter; - // Parameter Mgr - CParameterMgr* _pParameterMgr; - // Subsystem endianness - bool _bBigEndianSubsystem; + CParameterHandle(CConfigurableElement &element, CParameterMgr ¶meterMgr) + : ElementHandle(element, parameterMgr) + { + } + friend CParameterMgr; // So that it can build the handler }; diff --git a/parameter/include/ParameterMgrFullConnector.h b/parameter/include/ParameterMgrFullConnector.h index 4ee3b4f..c8c8d6e 100644 --- a/parameter/include/ParameterMgrFullConnector.h +++ b/parameter/include/ParameterMgrFullConnector.h @@ -29,10 +29,14 @@ */ #pragma once +#include "parameter_export.h" + #include "SelectionCriterionTypeInterface.h" #include "SelectionCriterionInterface.h" #include "ParameterHandle.h" #include "ParameterMgrLoggerForward.h" +#include "ParameterMgrPlatformConnector.h" +#include "CommandHandlerInterface.h" #include <string> #include <list> @@ -41,108 +45,48 @@ class CParameterMgr; -class CParameterMgrFullConnector +/** @note Since only C++11 components use this interface + * (contrary to the more restricted CParameterMgrPlatformConnector), + * could this api not be transition to c++11 ? + */ +class PARAMETER_EXPORT CParameterMgrFullConnector : public CParameterMgrPlatformConnector { - friend class CParameterMgrLogger<CParameterMgrFullConnector>; - public: - CParameterMgrFullConnector(const std::string& strConfigurationFilePath); - ~CParameterMgrFullConnector(); - - class ILogger - { - public: - virtual void log(bool bIsWarning, const std::string& strLog) = 0; - protected: - virtual ~ILogger() {} - }; - // Logging - /** Should be called before start */ - void setLogger(ILogger* pLogger); - + /** String list type which can hold list of error/info and can be presented to client */ + typedef std::list<std::string> Results; - bool start(std::string& strError); + CParameterMgrFullConnector(const std::string &strConfigurationFilePath); - // Dynamic parameter handling - CParameterHandle* createParameterHandle(const std::string& strPath, std::string& strError); - - ISelectionCriterionTypeInterface* createSelectionCriterionType(bool bIsInclusive); - ISelectionCriterionInterface* createSelectionCriterion(const std::string& strName, - const ISelectionCriterionTypeInterface* pSelectionCriterionType); - ISelectionCriterionInterface* getSelectionCriterion(const std::string& strName); - - /** Is the remote interface forcefully disabled ? - */ - bool getForceNoRemoteInterface() const; - - /** - * Forcefully disable the remote interface or cancel this policy. + /** Create and return a command handler for this ParameterMgr instance * - * Has no effect if called after calling start(). + * The caller owns the returned pointer and is responsible for deleting it + * before destroying the Connector object. * - * @param[in] bForceNoRemoteInterface disable the remote interface if true. + * @returns a Command Handler */ - void setForceNoRemoteInterface(bool bForceNoRemoteInterface); + CommandHandlerInterface *createCommandHandler(); - void applyConfigurations(); - - /** Should start fail in case of missing subsystems. - * - * @param[in] bFail: If set to true, parameterMgr start will fail on missing subsystems. - * If set to false, missing subsystems will fallback on virtual subsystem. - */ - void setFailureOnMissingSubsystem(bool bFail); - - /** Would start fail in case of missing subsystems. - * - * @return true if the subsystem will fail on missing subsystem, false otherwise. - */ - bool getFailureOnMissingSubsystem() const; - - /** Should start fail in failed settings load. - * - * @param[in] bFail: If set to true, parameterMgr start will fail on failed settings load. - * If set to false, failed settings load will be ignored. - */ - void setFailureOnFailedSettingsLoad(bool bFail); - /** Would start fail in case of failed settings load. - * - * @return failure on failed settings load policy state. - */ - bool getFailureOnFailedSettingsLoad(); - - /** Get the path to the directory containing the XML Schemas - * - * @returns the directory containing the XML Schemas + /** @deprecated Same as its overload without error handling. + * @note this deprecated method in not available in the python wrapper. */ - const std::string& getSchemaFolderLocation() const; + void setFailureOnMissingSubsystem(bool bFail); + using CParameterMgrPlatformConnector::setFailureOnMissingSubsystem; - /** Override the directory containing the XML Schemas - * - * @param[in] strSchemaFolderLocation directory containing the XML Schemas + /** @deprecated Same as its overload without error handling. + * @note this deprecated method in not available in the python wrapper. */ - void setSchemaFolderLocation(const std::string& strSchemaFolderLocation); + void setFailureOnFailedSettingsLoad(bool bFail); + using CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad; - /** Should .xml files be validated on start ? - * - * @param[in] bValidate: - * If set to true, parameterMgr will report an error - * when being unable to validate .xml files - * If set to false, no .xml/xsd validation will happen - * (default behaviour) - * - * @return false if unable to set, true otherwise. + /** @deprecated Same as its overload without error handling. + * @note this deprecated method in not available in the python wrapper. */ void setValidateSchemasOnStart(bool bValidate); + using CParameterMgrPlatformConnector::setValidateSchemasOnStart; - /** Would .xml files be validated on start? - * - * @return areSchemasValidated - */ - bool getValidateSchemasOnStart() const; //////////// Tuning ///////////// // Tuning mode - bool setTuningMode(bool bOn, std::string& strError); + bool setTuningMode(bool bOn, std::string &strError); bool isTuningModeOn() const; // Current value space for user set/get value interpretation @@ -153,13 +97,16 @@ public: void setOutputRawFormat(bool bIsHex); bool isOutputRawFormatHex() const; // Automatic hardware synchronization control (during tuning session) - bool setAutoSync(bool bAutoSyncOn, std::string& strError); + bool setAutoSync(bool bAutoSyncOn, std::string &strError); bool isAutoSyncOn() const; - bool sync(std::string& strError); + bool sync(std::string &strError); // User set/get parameters - bool accessParameterValue(const std::string& strPath, std::string& strValue, bool bSet, std::string& strError); - bool accessConfigurationValue(const std::string &strDomain, const std::string &strConfiguration, const std::string& strPath, std::string& strValue, bool bSet, std::string& strError); + bool accessParameterValue(const std::string &strPath, std::string &strValue, bool bSet, + std::string &strError); + bool accessConfigurationValue(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strPath, std::string &strValue, bool bSet, + std::string &strError); /** * Returns the element mapping corresponding to the path given in parameter. @@ -169,34 +116,57 @@ public: * * @return true if a mapping was found for this element */ - bool getParameterMapping(const std::string& strPath, std::string& strValue) const; + bool getParameterMapping(const std::string &strPath, std::string &strValue) const; ////////// Configuration/Domains handling ////////////// // Creation/Deletion - bool createDomain(const std::string& strName, std::string& strError); - bool deleteDomain(const std::string& strName, std::string& strError); - bool renameDomain(const std::string& strName, const std::string& strNewName, std::string& strError); - bool deleteAllDomains(std::string& strError); - bool setSequenceAwareness(const std::string& strName, bool bSequenceAware, std::string& strResult); - bool getSequenceAwareness(const std::string& strName, bool& bSequenceAware, std::string& strResult); - bool createConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool deleteConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); - bool renameConfiguration(const std::string& strDomain, const std::string& strConfiguration, const std::string& strNewConfiguration, std::string& strError); + bool createDomain(const std::string &strName, std::string &strError); + bool deleteDomain(const std::string &strName, std::string &strError); + bool renameDomain(const std::string &strName, const std::string &strNewName, + std::string &strError); + bool deleteAllDomains(std::string &strError); + bool setSequenceAwareness(const std::string &strName, bool bSequenceAware, + std::string &strResult); + bool getSequenceAwareness(const std::string &strName, bool &bSequenceAware, + std::string &strResult); + bool createConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool deleteConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); + bool renameConfiguration(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strNewConfiguration, std::string &strError); + + /** Restore a configuration + * + * @param[in] strDomain the domain name + * @param[in] strConfiguration the configuration name + * @param[out] errors, errors encountered during restoration + * @return true if success false otherwise + */ + bool restoreConfiguration(const std::string &strDomain, const std::string &strConfiguration, + Results &errors); - // Save/Restore - bool restoreConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::list<std::string>& strError); - bool saveConfiguration(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); + bool saveConfiguration(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); // Configurable element - domain association - bool addConfigurableElementToDomain(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool removeConfigurableElementFromDomain(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool split(const std::string& strDomain, const std::string& strConfigurableElementPath, std::string& strError); - bool setElementSequence(const std::string& strDomain, const std::string& strConfiguration, const std::vector<std::string>& astrNewElementSequence, std::string& strError); - - bool setApplicationRule(const std::string& strDomain, const std::string& strConfiguration, - const std::string& strApplicationRule, std::string& strError); - bool getApplicationRule(const std::string& strDomain, const std::string& strConfiguration, - std::string& strResult); - bool clearApplicationRule(const std::string& strDomain, const std::string& strConfiguration, std::string& strError); + bool addConfigurableElementToDomain(const std::string &strDomain, + const std::string &strConfigurableElementPath, + std::string &strError); + bool removeConfigurableElementFromDomain(const std::string &strDomain, + const std::string &strConfigurableElementPath, + std::string &strError); + bool split(const std::string &strDomain, const std::string &strConfigurableElementPath, + std::string &strError); + bool setElementSequence(const std::string &strDomain, const std::string &strConfiguration, + const std::vector<std::string> &astrNewElementSequence, + std::string &strError); + + bool setApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + const std::string &strApplicationRule, std::string &strError); + bool getApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strResult); + bool clearApplicationRule(const std::string &strDomain, const std::string &strConfiguration, + std::string &strError); /** * Method that imports Configurable Domains from an Xml source. @@ -210,8 +180,8 @@ public: * * @return false if any error occures */ - bool importDomainsXml(const std::string& strXmlSource, bool bWithSettings, bool bFromFile, - std::string& strError); + bool importDomainsXml(const std::string &strXmlSource, bool bWithSettings, bool bFromFile, + std::string &strError); /** * Method that imports a single Configurable Domain from an Xml source. * @@ -226,8 +196,8 @@ public: * * @return false if any error occurs */ - bool importSingleDomainXml(const std::string& xmlSource, bool overwrite, bool withSettings, - bool toFile, std::string& errorMsg); + bool importSingleDomainXml(const std::string &xmlSource, bool overwrite, bool withSettings, + bool fromFile, std::string &errorMsg); /** * Method that imports a single Configurable Domain from an string * describing an Xml source. @@ -241,9 +211,8 @@ public: * * @return false if any error occurs */ - bool importSingleDomainXml(const std::string& strXmlSource, bool bOverwrite, - std::string& strError); - + bool importSingleDomainXml(const std::string &strXmlSource, bool bOverwrite, + std::string &strError); /** * Method that exports Configurable Domains to an Xml destination. @@ -257,8 +226,8 @@ public: * * @return false if any error occures, true otherwise. */ - bool exportDomainsXml(std::string& strXmlDest, bool bWithSettings, bool bToFile, - std::string& strError) const; + bool exportDomainsXml(std::string &strXmlDest, bool bWithSettings, bool bToFile, + std::string &strError) const; /** * Method that exports a given Configurable Domain to an Xml destination. @@ -273,19 +242,11 @@ public: * * @return false if any error occurs, true otherwise. */ - bool exportSingleDomainXml(std::string& strXmlDest, const std::string& strDomainName, bool bWithSettings, - bool bToFile, std::string& strError) const; + bool exportSingleDomainXml(std::string &strXmlDest, const std::string &strDomainName, + bool bWithSettings, bool bToFile, std::string &strError) const; private: // disallow copying because this class manages raw pointers' lifecycle - CParameterMgrFullConnector(const CParameterMgrFullConnector&); - CParameterMgrFullConnector& operator=(const CParameterMgrFullConnector&); - - void doLog(bool bIsWarning, const std::string& strLog); - - CParameterMgr* _pParameterMgr; - - ILogger* _pLogger; - // Log wrapper - CParameterMgrLogger<CParameterMgrFullConnector>* _pParameterMgrLogger; + CParameterMgrFullConnector(const CParameterMgrFullConnector &); + CParameterMgrFullConnector &operator=(const CParameterMgrFullConnector &); }; diff --git a/parameter/include/ParameterMgrLoggerForward.h b/parameter/include/ParameterMgrLoggerForward.h index 28b26db..ad99931 100644 --- a/parameter/include/ParameterMgrLoggerForward.h +++ b/parameter/include/ParameterMgrLoggerForward.h @@ -30,4 +30,5 @@ #pragma once // Shared forward declaration, to ensure declaration alignment -template<class T> class CParameterMgrLogger; +template <class T> +class CParameterMgrLogger; diff --git a/parameter/include/ParameterMgrPlatformConnector.h b/parameter/include/ParameterMgrPlatformConnector.h index cd99215..3df9794 100644 --- a/parameter/include/ParameterMgrPlatformConnector.h +++ b/parameter/include/ParameterMgrPlatformConnector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,43 +29,58 @@ */ #pragma once +#include "parameter_export.h" + #include "SelectionCriterionTypeInterface.h" #include "SelectionCriterionInterface.h" #include "ParameterHandle.h" +#include "ElementHandle.h" #include "ParameterMgrLoggerForward.h" class CParameterMgr; -class CParameterMgrPlatformConnector +class PARAMETER_EXPORT CParameterMgrPlatformConnector { friend class CParameterMgrLogger<CParameterMgrPlatformConnector>; + public: - // Logger interface + /** Interface to implement to provide a custom logger to the PF. + * + * Override info and warning methods to specify how each log level + * should be printed. + * + * @note Errors are always returned synchronously. Never logged. + */ class ILogger { public: - virtual void log(bool bIsWarning, const std::string& strLog) = 0; + virtual void info(const std::string &strLog) = 0; + virtual void warning(const std::string &strLog) = 0; + protected: virtual ~ILogger() {} }; // Construction - CParameterMgrPlatformConnector(const std::string& strConfigurationFilePath); - ~CParameterMgrPlatformConnector(); // Not virtual since not supposed to be derived! + CParameterMgrPlatformConnector(const std::string &strConfigurationFilePath); + virtual ~CParameterMgrPlatformConnector(); - // Selection Criteria interface. Beware returned objects are lent, clients shall not delete them! + // Selection Criteria interface. Beware returned objects are lent, clients shall not delete + // them! // Should be called before start - ISelectionCriterionTypeInterface* createSelectionCriterionType(bool bIsInclusive = false); - ISelectionCriterionInterface* createSelectionCriterion(const std::string& strName, const ISelectionCriterionTypeInterface* pSelectionCriterionType); + ISelectionCriterionTypeInterface *createSelectionCriterionType(bool bIsInclusive = false); + ISelectionCriterionInterface *createSelectionCriterion( + const std::string &strName, + const ISelectionCriterionTypeInterface *pSelectionCriterionType); // Selection criterion retrieval - ISelectionCriterionInterface* getSelectionCriterion(const std::string& strName) const; + ISelectionCriterionInterface *getSelectionCriterion(const std::string &strName) const; // Logging // Should be called before start - void setLogger(ILogger* pLogger); + void setLogger(ILogger *pLogger); // Start - bool start(std::string& strError); + bool start(std::string &strError); // Started state bool isStarted() const; @@ -76,7 +91,21 @@ public: // Dynamic parameter handling // Returned objects are owned by clients // Must be cassed after successfull start - CParameterHandle* createParameterHandle(const std::string& strPath, std::string& strError) const; + CParameterHandle *createParameterHandle(const std::string &strPath, + std::string &strError) const; + + /** Creates a handle to a configurable element. + * + * The returned object is owned by the client who is responsible to delete it. + * + * @param[in] path A string representing a path to a configurable element. + * @param[out] error On error: an human readable error message + * On success: undefined + * + * @return An element handle on success + * NULL on error + */ + ElementHandle *createElementHandle(const std::string &path, std::string &error) const; /** Is the remote interface forcefully disabled ? */ @@ -102,49 +131,51 @@ public: * * @return false if unable to set, true otherwise. */ - bool setFailureOnMissingSubsystem(bool bFail, std::string& strError); + bool setFailureOnMissingSubsystem(bool bFail, std::string &strError); /** Would start fail in case of missing subsystems. * * @return if the subsystem load will fail on missing subsystem. */ - bool getFailureOnMissingSubsystem(); + bool getFailureOnMissingSubsystem() const; /** Should start fail in failed settings load. * * Will fail if called on started instance. * - * @param[in] bFail: If set to true, parameterMgr start will fail on failed settings load. - * If set to false, failed settings load will be ignored. - * @param[out] strResult a string containing the result of the command. + * @param[in] bFail If set to true, parameterMgr start will fail on failed settings load. + * If set to false, failed settings load will be ignored. + * @param[out] strError On error: an human readable error message + * On success: undefined * * @return false if unable to set, true otherwise. */ - bool setFailureOnFailedSettingsLoad(bool bFail, std::string& strError); + bool setFailureOnFailedSettingsLoad(bool bFail, std::string &strError); /** Would start fail in case of failed settings load. * * @return failure on failed settings load policy state. */ - bool getFailureOnFailedSettingsLoad(); + bool getFailureOnFailedSettingsLoad() const; - /** Get the path to the directory containing the XML Schemas + /** Get the XML Schemas URI * - * @returns the directory containing the XML Schemas + * @returns the XML Schemas URI */ - const std::string& getSchemaFolderLocation() const; + const std::string &getSchemaUri() const; - /** Override the directory containing the XML Schemas + /** Override the XML Schemas URI * - * @param[in] strSchemaFolderLocation directory containing the XML Schemas + * @param[in] schemaUri the XML Schemas URI */ - void setSchemaFolderLocation(const std::string& strSchemaFolderLocation); + void setSchemaUri(const std::string &schemaUri); /** Should .xml files be validated on start ? * * @param[in] bValidate: * If set to true, parameterMgr will abort when being unable to validate .xml files * If set to false, no .xml/xsd validation will happen (default behaviour) - * @param[out] strResult a string containing the result of the command. + * @param[out] strError On error: an human readable error message + * On success: undefined * * @return false if unable to set, true otherwise. */ @@ -154,20 +185,22 @@ public: * * @return areSchemasValidated */ - bool getValidateSchemasOnStart(); + bool getValidateSchemasOnStart() const; private: - CParameterMgrPlatformConnector(const CParameterMgrPlatformConnector&); - CParameterMgrPlatformConnector& operator=(const CParameterMgrPlatformConnector&); + CParameterMgrPlatformConnector(const CParameterMgrPlatformConnector &); + CParameterMgrPlatformConnector &operator=(const CParameterMgrPlatformConnector &); // Private logging - void doLog(bool bIsWarning, const std::string& strLog); + void info(const std::string &log); + void warning(const std::string &log); +protected: + // Private logging + CParameterMgrLogger<CParameterMgrPlatformConnector> *_pParameterMgrLogger; // Implementation - CParameterMgr* _pParameterMgr; + CParameterMgr *_pParameterMgr; // State bool _bStarted; // Logging - ILogger* _pLogger; - // Private logging - CParameterMgrLogger<CParameterMgrPlatformConnector>* _pParameterMgrLogger; + ILogger *_pLogger; }; diff --git a/parameter/include/SelectionCriterionInterface.h b/parameter/include/SelectionCriterionInterface.h index d71eff3..6eb2d8a 100644 --- a/parameter/include/SelectionCriterionInterface.h +++ b/parameter/include/SelectionCriterionInterface.h @@ -39,7 +39,7 @@ public: virtual void setCriterionState(int iState) = 0; virtual int getCriterionState() const = 0; virtual std::string getCriterionName() const = 0; - virtual const ISelectionCriterionTypeInterface* getCriterionType() const = 0; + virtual const ISelectionCriterionTypeInterface *getCriterionType() const = 0; protected: virtual ~ISelectionCriterionInterface() {} diff --git a/parameter/include/SelectionCriterionTypeInterface.h b/parameter/include/SelectionCriterionTypeInterface.h index 0b62ee4..bebcfc7 100644 --- a/parameter/include/SelectionCriterionTypeInterface.h +++ b/parameter/include/SelectionCriterionTypeInterface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -34,13 +34,20 @@ class ISelectionCriterionTypeInterface { public: - virtual bool addValuePair(int iValue, const std::string& strValue) = 0; - virtual bool getNumericalValue(const std::string& strValue, int& iValue) const = 0; - virtual bool getLiteralValue(int iValue, std::string& strValue) const = 0; + /** + * Add a new pair [integer, litteral] which represents a criterion + * + * @param[in] iValue integer value + * @param[in] strValue litteral value + * @param[out] strError string containing error information we can provide to client + * @return true if succeed false otherwise + */ + virtual bool addValuePair(int iValue, const std::string &strValue, std::string &strError) = 0; + virtual bool getNumericalValue(const std::string &strValue, int &iValue) const = 0; + virtual bool getLiteralValue(int iValue, std::string &strValue) const = 0; virtual bool isTypeInclusive() const = 0; virtual std::string getFormattedState(int iValue) const = 0; protected: virtual ~ISelectionCriterionTypeInterface() {} }; - diff --git a/parameter/log/include/log/Context.h b/parameter/log/include/log/Context.h new file mode 100644 index 0000000..a3d5fd4 --- /dev/null +++ b/parameter/log/include/log/Context.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +#include "log/Logger.h" +#include <string> + +namespace core +{ +namespace log +{ + +/** Log formatter which provide context indentation */ +class Context +{ +public: + /** + * Class Constructor + * + * @param[in] logger application logger + * @param[in] context name of the context to open + */ + Context(Logger &logger, const std::string &context) : mLogger(logger) + { + mLogger.info() << context << " {"; + mLogger.mProlog += " "; + } + + /** Class Destructor */ + ~Context() + { + mLogger.mProlog.resize(mLogger.mProlog.size() - 4); + mLogger.info() << "}"; + } + +private: + Context(const Context &); + Context &operator=(const Context &); + + /** Application logger */ + Logger &mLogger; +}; + +} /** log namespace */ +} /** core namespace */ diff --git a/parameter/ErrorContext.h b/parameter/log/include/log/ILogger.h index ae2afe1..9b72813 100644 --- a/parameter/ErrorContext.h +++ b/parameter/log/include/log/ILogger.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -31,18 +31,21 @@ #include <string> -class CErrorContext +namespace core +{ +namespace log { -public: - CErrorContext(std::string& strError); - // Error - void setError(const std::string& strError); - void appendToError(const std::string& strAppend); - const std::string& getError() const; +/** Logger interface provided by client */ +class ILogger +{ +public: + virtual void info(const std::string &strLog) = 0; + virtual void warning(const std::string &strLog) = 0; -private: - // Error reference - std::string& _strError; +protected: + virtual ~ILogger() {} }; +} /** log namespace */ +} /** core namespace */ diff --git a/parameter/log/include/log/LogWrapper.h b/parameter/log/include/log/LogWrapper.h new file mode 100644 index 0000000..14624e4 --- /dev/null +++ b/parameter/log/include/log/LogWrapper.h @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2015, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#pragma once + +#include "log/ILogger.h" +#include "Utility.h" +#include <string> +#include <sstream> +#include <iterator> +#include <list> + +namespace core +{ +namespace log +{ +namespace details +{ + +/** + * Template log wrapper + * Simulate a stream which can be used instead of basic ILogger API. + * + * @tparam isWarning indicates which log canal to use + */ +template <bool isWarning> +class LogWrapper +{ +public: + /** @param logger the ILogger to wrap */ + LogWrapper(ILogger &logger, const std::string &prolog = "") : mLogger(logger), mProlog(prolog) + { + } + + /** + * Class copy constructor + * + * @param[in] logWrapper the instance to copy + */ + LogWrapper(const LogWrapper &logWrapper) + : mLogger(logWrapper.mLogger), mProlog(logWrapper.mProlog) + { + } + + /** Class destructor */ + ~LogWrapper() + { + if (!mLog.str().empty()) { + if (isWarning) { + mLogger.warning(mProlog + mLog.str()); + } else { + mLogger.info(mProlog + mLog.str()); + } + } + } + + /** + * Simulate stream behaviour + * + * @tparam T the type of the information to log + * @param[in] log the information to log + */ + template <class T> + LogWrapper &operator<<(const T &log) + { + mLog << log; + return *this; + } + + /** + * Simulate stream behaviour for string list + * + * @param[in] logs list of information to log + */ + LogWrapper &operator<<(const std::list<std::string> &logs) + { + std::string separator = "\n" + mProlog; + std::string formatedLogs = utility::asString(logs, separator); + + // Check if there is something in the log to know if we have to add a prefix + if (!mLog.str().empty() && mLog.str()[mLog.str().length() - 1] == separator[0]) { + *this << mProlog; + } + + *this << formatedLogs; + return *this; + } + +private: + LogWrapper &operator=(const LogWrapper &); + + /** Log stream holder */ + std::ostringstream mLog; + + /** Wrapped logger */ + ILogger &mLogger; + + /** Log Prefix */ + const std::string &mProlog; +}; + +/** Default information logger type */ +typedef details::LogWrapper<false> Info; + +/** Default warning logger type */ +typedef details::LogWrapper<true> Warning; + +} /** details namespace */ +} /** log namespace */ +} /** core namespace */ diff --git a/parameter/ConfigurableElementWithMapping.h b/parameter/log/include/log/Logger.h index b5f6a1f..b224d35 100644 --- a/parameter/ConfigurableElementWithMapping.h +++ b/parameter/log/include/log/Logger.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Intel Corporation + * Copyright (c) 2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -29,27 +29,52 @@ */ #pragma once -#include "ConfigurableElement.h" -#include <string> +#include "log/ILogger.h" +#include "log/LogWrapper.h" -/** - * Base class for all Configurable Elements that can have a Mapping attribute. - * - * This class acts as an interface: it doesn't implement anything but only - * declares getMappingData as pure virtual fonction. +#include "NonCopyable.hpp" + +namespace core +{ +namespace log +{ + +/** Application logger object (Thread unsafe) + * Provide contextualisable logging API. + * Streams can be used through Info and Warning objects returned by dedicated + * methods. + * This is the class you want to use to log in the project. */ -class CConfigurableElementWithMapping : public CConfigurableElement { +class Logger : private utility::NonCopyable +{ public: - CConfigurableElementWithMapping(const std::string& strName) : CConfigurableElement(strName) {} - virtual ~CConfigurableElementWithMapping() {} + /** Context class is friend let the prolog by externally modified */ + friend class Context; + + /** @param[in] logger raw logger provided by client */ + Logger(ILogger &logger) : mLogger(logger) {} /** - * Get the value associated to a mapping key in the object's mapping + * Retrieve wrapped information logger * - * @param[in] strKey the mapping key - * @param[out] pStrValue the associated value + * @return Info logger + */ + details::Info info() { return details::Info(mLogger, mProlog); } + + /** + * Retrieve wrapped warning logger * - * @return true if @p strKey is found in the object's mapping, false if not + * @return Warning logger */ - virtual bool getMappingData(const std::string& strKey, const std::string*& pStrValue) const = 0; + details::Warning warning() { return details::Warning(mLogger, mProlog); } + +private: + /** Raw logger provided by client */ + ILogger &mLogger; + + /** Log prolog, owns the context indentation */ + std::string mProlog; }; + +} /** log namespace */ +} /** core namespace */ diff --git a/parameter/ErrorContext.cpp b/parameter/version.h.in index e9c0b43..264fbba 100644 --- a/parameter/ErrorContext.cpp +++ b/parameter/version.h.in @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2014, Intel Corporation + * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,25 +27,4 @@ * (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 "ErrorContext.h" - -CErrorContext::CErrorContext(std::string& strError) : _strError(strError) -{ -} - -// Error -void CErrorContext::setError(const std::string& strError) -{ - _strError = strError; -} - -void CErrorContext::appendToError(const std::string& strAppend) -{ - _strError += strAppend; -} - -const std::string& CErrorContext::getError() const -{ - return _strError; -} - +#define PARAMETER_FRAMEWORK_VERSION "@NICE_PF_VERSION@" |
