Index: src/common/TShellExtMenuConfig.cpp =================================================================== diff -u -r3c248d4f6d0fdb1e487cc868b2f0b219eec37ef4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/common/TShellExtMenuConfig.cpp (.../TShellExtMenuConfig.cpp) (revision 3c248d4f6d0fdb1e487cc868b2f0b219eec37ef4) +++ src/common/TShellExtMenuConfig.cpp (.../TShellExtMenuConfig.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,533 +1,533 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TShellExtMenuConfig.cpp -/// @date 2011/05/06 -/// @brief Contains implementation of shell menu configuration classes. -// ============================================================================ -#include "stdafx.h" -#include "TShellExtMenuConfig.h" -#include "../libchcore/TConfig.h" -#include "../libchcore/TConfigArray.h" -#include -#include -#include - -// helper method for concatenating strings -namespace -{ - PCTSTR Concat(std::wstring& wstrBuffer, PCTSTR pszFirst, PCTSTR pszSecond) - { - if(pszFirst && pszFirst[ 0 ] != _T('\0')) - { - wstrBuffer = pszFirst; - wstrBuffer += _T("."); - wstrBuffer += pszSecond; - } - else - wstrBuffer = pszSecond; - - return wstrBuffer.c_str(); - } -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// class TOperationTypeInfo - -TOperationTypeInfo::TOperationTypeInfo() : - m_eOperationTypeSource(eOpType_Autodetect), - m_eDefaultOperationType(chcore::eOperation_None) -{ -} - -TOperationTypeInfo::TOperationTypeInfo(TOperationTypeInfo::EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType) : - m_eOperationTypeSource(eType), - m_eDefaultOperationType(eDefaultOperationType) -{ -} - -void TOperationTypeInfo::SetOperationTypeInfo(TOperationTypeInfo::EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType) -{ - m_eOperationTypeSource = eType; - m_eDefaultOperationType = eDefaultOperationType; -} - -TOperationTypeInfo::EOperationTypeSource TOperationTypeInfo::GetOperationTypeSource() const -{ - return m_eOperationTypeSource; -} - -chcore::EOperationType TOperationTypeInfo::GetDefaultOperationType() const -{ - return m_eDefaultOperationType; -} - -void TOperationTypeInfo::Clear() -{ - m_eOperationTypeSource = eOpType_Autodetect; - m_eDefaultOperationType = chcore::eOperation_None; -} - -void TOperationTypeInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const -{ - std::wstring wstrBuffer; - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationTypeSource")), m_eOperationTypeSource); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultOperationType")), m_eDefaultOperationType); -} - -bool TOperationTypeInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) -{ - std::wstring wstrBuffer; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationTypeSource")), *(int*)&m_eOperationTypeSource)) - return false; - return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultOperationType")), *(int*)&m_eDefaultOperationType); -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// class TSourcePathsInfo - -TSourcePathsInfo::TSourcePathsInfo() : - m_eSrcPathsSource(eSrcType_InitializeAuto) -{ -} - -TSourcePathsInfo::TSourcePathsInfo(TSourcePathsInfo::ESrcPathsSource eSrcPathSource) : - m_eSrcPathsSource(eSrcPathSource) -{ -} - -void TSourcePathsInfo::SetSourcePathsInfo(TSourcePathsInfo::ESrcPathsSource eSrcPathSource) -{ - m_eSrcPathsSource = eSrcPathSource; -} - -TSourcePathsInfo::ESrcPathsSource TSourcePathsInfo::GetSrcPathsSource() const -{ - return m_eSrcPathsSource; -} - -void TSourcePathsInfo::Clear() -{ - m_eSrcPathsSource = eSrcType_InitializeAuto; -} - -void TSourcePathsInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const -{ - std::wstring wstrBuffer; - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SrcPathsSource")), m_eSrcPathsSource); -} - -bool TSourcePathsInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) -{ - std::wstring wstrBuffer; - return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SrcPathsSource")), *(int*)&m_eSrcPathsSource); -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// class TDestinationPathInfo -// - -TDestinationPathInfo::TDestinationPathInfo() : - m_eDstPathSource(eDstType_InitializeAuto), - m_pathDestination() -{ -} - -TDestinationPathInfo::TDestinationPathInfo(TDestinationPathInfo::EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination) : - m_eDstPathSource(eDstPathSource), - m_pathDestination(pathDestination) -{ -} - -void TDestinationPathInfo::SetDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination) -{ - m_eDstPathSource = eDstPathSource; - m_pathDestination = pathDestination; -} - -TDestinationPathInfo::EDstPathsSource TDestinationPathInfo::GetDstPathSource() const -{ - return m_eDstPathSource; -} - -chcore::TSmartPath TDestinationPathInfo::GetDefaultDestinationPath() const -{ - return m_pathDestination; -} - -void TDestinationPathInfo::Clear() -{ - m_eDstPathSource = eDstType_InitializeAuto; - m_pathDestination.Clear(); -} - -void TDestinationPathInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const -{ - std::wstring wstrBuffer; - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DstPathSource")), m_eDstPathSource); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultDestinationPath")), m_pathDestination); -} - -bool TDestinationPathInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) -{ - std::wstring wstrBuffer; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DstPathSource")), *(int*)&m_eDstPathSource)) - return false; - return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultDestinationPath")), m_pathDestination); -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// class TShellMenuItem - -TShellMenuItem::TShellMenuItem() : - m_tOperationType(), - m_tSourcePaths(), - m_tDestinationPath(), - m_eItemType(eSeparatorItem), - m_bSpecialOperation(false), - m_eDefaultItemHint(chcore::eOperation_None) -{ -} - -TShellMenuItem::TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, bool bSpecialOperation, chcore::EOperationType eDefaultItemHint) : - m_strName(wstrName), - m_strItemTip(wstrItemTip), - m_tOperationType(rOperationType), - m_tSourcePaths(rSourcePaths), - m_tDestinationPath(rDestinationPath), - m_eItemType(eStandardItem), - m_bSpecialOperation(bSpecialOperation), - m_eDefaultItemHint(eDefaultItemHint) -{ -} - -TShellMenuItem::TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip) : - m_strName(wstrName), - m_strItemTip(wstrItemTip), - m_tOperationType(), - m_tSourcePaths(), - m_tDestinationPath(), - m_eItemType(eGroupItem), - m_bSpecialOperation(false), - m_eDefaultItemHint(chcore::eOperation_None) -{ -} - -TShellMenuItem::~TShellMenuItem() -{ -} - -void TShellMenuItem::Clear() -{ - m_eItemType = eSeparatorItem; - - m_strName.Clear(); - m_strItemTip.Clear(); - - m_tOperationType.Clear(); - m_tSourcePaths.Clear(); - m_tDestinationPath.Clear(); - - m_bSpecialOperation = false; - m_eDefaultItemHint = chcore::eOperation_None; - - m_vChildItems.clear(); -} - -const chcore::TString& TShellMenuItem::GetName() const -{ - return m_strName; -} - -const chcore::TString& TShellMenuItem::GetLocalName(bool bUseFallback) const -{ - if(bUseFallback && m_strLocalName.IsEmpty()) - return m_strName; - - return m_strLocalName; -} - -void TShellMenuItem::SetLocalName(const chcore::TString& strLocalName) -{ - m_strLocalName = strLocalName; -} - -void TShellMenuItem::InitSeparatorItem() -{ - Clear(); - - m_eItemType = eSeparatorItem; -} - -void TShellMenuItem::InitStandardItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, bool bSpecialOperation, chcore::EOperationType eDefaultItemHint) -{ - Clear(); - - m_eItemType = eStandardItem; - - m_strName = wstrName; - m_strItemTip = wstrItemTip; - m_tOperationType = rOperationType; - m_tSourcePaths = rSourcePaths; - m_tDestinationPath = rDestinationPath; - - m_bSpecialOperation = bSpecialOperation; - m_eDefaultItemHint = eDefaultItemHint; -} - -void TShellMenuItem::InitGroupItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip) -{ - Clear(); - - m_eItemType = eGroupItem; - m_strName = wstrName; - m_strItemTip = wstrItemTip; -} - -bool TShellMenuItem::SpecifiesDestinationPath() const -{ - return !IsGroupItem() && (m_tDestinationPath.GetDstPathSource() == TDestinationPathInfo::eDstType_Specified); -} - -bool TShellMenuItem::RequiresClipboardPaths() const -{ - return !IsGroupItem() && (m_tDestinationPath.GetDstPathSource() == TDestinationPathInfo::eDstType_Clipboard || m_tSourcePaths.GetSrcPathsSource() == TSourcePathsInfo::eSrcType_Clipboard); -} - -size_t TShellMenuItem::GetChildrenCount() const -{ - return m_vChildItems.size(); -} - -TShellMenuItemPtr TShellMenuItem::GetChildAt(size_t stIndex) const -{ - return m_vChildItems[stIndex]; -} - -void TShellMenuItem::AddChild(const TShellMenuItemPtr& rItem) -{ - m_vChildItems.push_back(rItem); -} - -void TShellMenuItem::SetChildAt(size_t stIndex, const TShellMenuItemPtr& rItem) -{ - m_vChildItems[stIndex] = rItem; -} - -void TShellMenuItem::InsertChildAt(size_t stIndex, const TShellMenuItemPtr& rItem) -{ - m_vChildItems.insert(m_vChildItems.begin() + stIndex, rItem); -} - -void TShellMenuItem::RemoveChildAt(size_t stIndex) -{ - m_vChildItems.erase(m_vChildItems.begin() + stIndex); -} - -void TShellMenuItem::RemoveAllChildren() -{ - m_vChildItems.clear(); -} - -void TShellMenuItem::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const -{ - std::wstring wstrBuffer; - - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemType")), m_eItemType); - switch(m_eItemType) - { - case eSeparatorItem: - break; - case eGroupItem: - { - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip); - - for(const TShellMenuItemPtr& rItem : m_vChildItems) - { - chcore::TConfig cfgItem; - rItem->StoreInConfig(cfgItem, _T("")); - rConfig.AddSubConfig(Concat(wstrBuffer, pszNodeName, _T("Subitems.Subitem")), cfgItem); - } - - break; - } - case eStandardItem: - { - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SpecialOperation")), m_bSpecialOperation); - SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultItemHint")), m_eDefaultItemHint); - - m_tOperationType.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationType"))); - m_tSourcePaths.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("SourcePaths"))); - m_tDestinationPath.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("DestinationPath"))); - - break; - } - default: - BOOST_ASSERT(false); // unhandled case - } -} - -bool TShellMenuItem::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) -{ - Clear(); - - std::wstring wstrBuffer; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemType")), *(int*)&m_eItemType)) - return false; - switch(m_eItemType) - { - case eSeparatorItem: - break; - case eGroupItem: - { - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName)) - return false; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip)) - return false; - - chcore::TConfigArray vCfgs; - if(rConfig.ExtractMultiSubConfigs(Concat(wstrBuffer, pszNodeName, _T("Subitems.Subitem")), vCfgs)) - { - for(size_t stIndex = 0; stIndex < vCfgs.GetCount(); ++stIndex) - { - chcore::TConfig& rCfg = vCfgs.GetAt(stIndex); - - TShellMenuItemPtr spItem(std::make_shared()); - spItem->ReadFromConfig(rCfg, nullptr); - m_vChildItems.push_back(spItem); - } - } - - break; - } - case eStandardItem: - { - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName)) - return false; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip)) - return false; - - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SpecialOperation")), m_bSpecialOperation)) - return false; - if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultItemHint")), *(int*)&m_eDefaultItemHint)) - return false; - - if(!m_tOperationType.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationType")))) - return false; - - if(!m_tSourcePaths.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("SourcePaths")))) - return false; - - if(!m_tDestinationPath.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("DestinationPath")))) - return false; - - break; - } - default: - BOOST_ASSERT(false); // unhandled case - return false; - } - - return true; -} - -TShellExtMenuConfig::TShellExtMenuConfig() : - m_bInterceptDragAndDrop(false), - m_bInterceptKeyboardActions(false), - m_bInterceptCtxMenuActions(false), - m_bShowShortcutIcons(false), - m_spDragAndDropRoot(std::make_shared(_T(""), _T(""))), - m_spNormalRoot(std::make_shared(_T(""), _T(""))), - m_spFmtSize(std::make_shared()) -{ -} - -TShellExtMenuConfig::~TShellExtMenuConfig() -{ -} - -void TShellExtMenuConfig::Clear() -{ - m_spDragAndDropRoot->Clear(); - - m_bInterceptDragAndDrop = false; - m_bInterceptKeyboardActions = false; - m_bInterceptCtxMenuActions = false; - m_bShowShortcutIcons = false; -} - -// commands support -TShellMenuItemPtr TShellExtMenuConfig::GetDragAndDropRoot() -{ - return m_spDragAndDropRoot; -} - -TShellMenuItemPtr TShellExtMenuConfig::GetNormalRoot() -{ - return m_spNormalRoot; -} - -chcore::TSizeFormatterPtr TShellExtMenuConfig::GetFormatter() const -{ - return m_spFmtSize; -} - -void TShellExtMenuConfig::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const -{ - std::wstring strBuffer; - SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptDragAndDrop")), m_bInterceptDragAndDrop); - SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptKeyboardActions")), m_bInterceptKeyboardActions); - SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptCtxMenuActions")), m_bInterceptCtxMenuActions); - SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowShortcutIcons")), m_bShowShortcutIcons); - SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowFreeSpace")), m_bShowFreeSpace); - - m_spFmtSize->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, L"Sizes")); - - m_spDragAndDropRoot->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, _T("DragAndDropRootItem"))); - m_spNormalRoot->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, _T("NormalRootItem"))); -} - -bool TShellExtMenuConfig::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) -{ - Clear(); - - std::wstring strBuffer; - if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptDragAndDrop")), m_bInterceptDragAndDrop)) - return false; - if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptKeyboardActions")), m_bInterceptKeyboardActions)) - return false; - if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptCtxMenuActions")), m_bInterceptCtxMenuActions)) - return false; - if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowShortcutIcons")), m_bShowShortcutIcons)) - return false; - if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowFreeSpace")), m_bShowFreeSpace)) - return false; - - if(!m_spFmtSize->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, L"Sizes"))) - return false; - - if(!m_spDragAndDropRoot->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, _T("DragAndDropRootItem")))) - return false; - if(!m_spNormalRoot->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, _T("NormalRootItem")))) - return false; - - return true; -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TShellExtMenuConfig.cpp +/// @date 2011/05/06 +/// @brief Contains implementation of shell menu configuration classes. +// ============================================================================ +#include "stdafx.h" +#include "TShellExtMenuConfig.h" +#include "../libchcore/TConfig.h" +#include "../libchcore/TConfigArray.h" +#include +#include +#include + +// helper method for concatenating strings +namespace +{ + PCTSTR Concat(std::wstring& wstrBuffer, PCTSTR pszFirst, PCTSTR pszSecond) + { + if(pszFirst && pszFirst[ 0 ] != _T('\0')) + { + wstrBuffer = pszFirst; + wstrBuffer += _T("."); + wstrBuffer += pszSecond; + } + else + wstrBuffer = pszSecond; + + return wstrBuffer.c_str(); + } +} + +/////////////////////////////////////////////////////////////////////////////////////////// +// class TOperationTypeInfo + +TOperationTypeInfo::TOperationTypeInfo() : + m_eOperationTypeSource(eOpType_Autodetect), + m_eDefaultOperationType(chcore::eOperation_None) +{ +} + +TOperationTypeInfo::TOperationTypeInfo(TOperationTypeInfo::EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType) : + m_eOperationTypeSource(eType), + m_eDefaultOperationType(eDefaultOperationType) +{ +} + +void TOperationTypeInfo::SetOperationTypeInfo(TOperationTypeInfo::EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType) +{ + m_eOperationTypeSource = eType; + m_eDefaultOperationType = eDefaultOperationType; +} + +TOperationTypeInfo::EOperationTypeSource TOperationTypeInfo::GetOperationTypeSource() const +{ + return m_eOperationTypeSource; +} + +chcore::EOperationType TOperationTypeInfo::GetDefaultOperationType() const +{ + return m_eDefaultOperationType; +} + +void TOperationTypeInfo::Clear() +{ + m_eOperationTypeSource = eOpType_Autodetect; + m_eDefaultOperationType = chcore::eOperation_None; +} + +void TOperationTypeInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const +{ + std::wstring wstrBuffer; + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationTypeSource")), m_eOperationTypeSource); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultOperationType")), m_eDefaultOperationType); +} + +bool TOperationTypeInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) +{ + std::wstring wstrBuffer; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationTypeSource")), *(int*)&m_eOperationTypeSource)) + return false; + return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultOperationType")), *(int*)&m_eDefaultOperationType); +} + +/////////////////////////////////////////////////////////////////////////////////////////// +// class TSourcePathsInfo + +TSourcePathsInfo::TSourcePathsInfo() : + m_eSrcPathsSource(eSrcType_InitializeAuto) +{ +} + +TSourcePathsInfo::TSourcePathsInfo(TSourcePathsInfo::ESrcPathsSource eSrcPathSource) : + m_eSrcPathsSource(eSrcPathSource) +{ +} + +void TSourcePathsInfo::SetSourcePathsInfo(TSourcePathsInfo::ESrcPathsSource eSrcPathSource) +{ + m_eSrcPathsSource = eSrcPathSource; +} + +TSourcePathsInfo::ESrcPathsSource TSourcePathsInfo::GetSrcPathsSource() const +{ + return m_eSrcPathsSource; +} + +void TSourcePathsInfo::Clear() +{ + m_eSrcPathsSource = eSrcType_InitializeAuto; +} + +void TSourcePathsInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const +{ + std::wstring wstrBuffer; + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SrcPathsSource")), m_eSrcPathsSource); +} + +bool TSourcePathsInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) +{ + std::wstring wstrBuffer; + return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SrcPathsSource")), *(int*)&m_eSrcPathsSource); +} + +/////////////////////////////////////////////////////////////////////////////////////////// +// class TDestinationPathInfo +// + +TDestinationPathInfo::TDestinationPathInfo() : + m_eDstPathSource(eDstType_InitializeAuto), + m_pathDestination() +{ +} + +TDestinationPathInfo::TDestinationPathInfo(TDestinationPathInfo::EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination) : + m_eDstPathSource(eDstPathSource), + m_pathDestination(pathDestination) +{ +} + +void TDestinationPathInfo::SetDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination) +{ + m_eDstPathSource = eDstPathSource; + m_pathDestination = pathDestination; +} + +TDestinationPathInfo::EDstPathsSource TDestinationPathInfo::GetDstPathSource() const +{ + return m_eDstPathSource; +} + +chcore::TSmartPath TDestinationPathInfo::GetDefaultDestinationPath() const +{ + return m_pathDestination; +} + +void TDestinationPathInfo::Clear() +{ + m_eDstPathSource = eDstType_InitializeAuto; + m_pathDestination.Clear(); +} + +void TDestinationPathInfo::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const +{ + std::wstring wstrBuffer; + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DstPathSource")), m_eDstPathSource); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultDestinationPath")), m_pathDestination); +} + +bool TDestinationPathInfo::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) +{ + std::wstring wstrBuffer; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DstPathSource")), *(int*)&m_eDstPathSource)) + return false; + return GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultDestinationPath")), m_pathDestination); +} + +/////////////////////////////////////////////////////////////////////////////////////////// +// class TShellMenuItem + +TShellMenuItem::TShellMenuItem() : + m_tOperationType(), + m_tSourcePaths(), + m_tDestinationPath(), + m_eItemType(eSeparatorItem), + m_bSpecialOperation(false), + m_eDefaultItemHint(chcore::eOperation_None) +{ +} + +TShellMenuItem::TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, bool bSpecialOperation, chcore::EOperationType eDefaultItemHint) : + m_strName(wstrName), + m_strItemTip(wstrItemTip), + m_tOperationType(rOperationType), + m_tSourcePaths(rSourcePaths), + m_tDestinationPath(rDestinationPath), + m_eItemType(eStandardItem), + m_bSpecialOperation(bSpecialOperation), + m_eDefaultItemHint(eDefaultItemHint) +{ +} + +TShellMenuItem::TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip) : + m_strName(wstrName), + m_strItemTip(wstrItemTip), + m_tOperationType(), + m_tSourcePaths(), + m_tDestinationPath(), + m_eItemType(eGroupItem), + m_bSpecialOperation(false), + m_eDefaultItemHint(chcore::eOperation_None) +{ +} + +TShellMenuItem::~TShellMenuItem() +{ +} + +void TShellMenuItem::Clear() +{ + m_eItemType = eSeparatorItem; + + m_strName.Clear(); + m_strItemTip.Clear(); + + m_tOperationType.Clear(); + m_tSourcePaths.Clear(); + m_tDestinationPath.Clear(); + + m_bSpecialOperation = false; + m_eDefaultItemHint = chcore::eOperation_None; + + m_vChildItems.clear(); +} + +const chcore::TString& TShellMenuItem::GetName() const +{ + return m_strName; +} + +const chcore::TString& TShellMenuItem::GetLocalName(bool bUseFallback) const +{ + if(bUseFallback && m_strLocalName.IsEmpty()) + return m_strName; + + return m_strLocalName; +} + +void TShellMenuItem::SetLocalName(const chcore::TString& strLocalName) +{ + m_strLocalName = strLocalName; +} + +void TShellMenuItem::InitSeparatorItem() +{ + Clear(); + + m_eItemType = eSeparatorItem; +} + +void TShellMenuItem::InitStandardItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, bool bSpecialOperation, chcore::EOperationType eDefaultItemHint) +{ + Clear(); + + m_eItemType = eStandardItem; + + m_strName = wstrName; + m_strItemTip = wstrItemTip; + m_tOperationType = rOperationType; + m_tSourcePaths = rSourcePaths; + m_tDestinationPath = rDestinationPath; + + m_bSpecialOperation = bSpecialOperation; + m_eDefaultItemHint = eDefaultItemHint; +} + +void TShellMenuItem::InitGroupItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip) +{ + Clear(); + + m_eItemType = eGroupItem; + m_strName = wstrName; + m_strItemTip = wstrItemTip; +} + +bool TShellMenuItem::SpecifiesDestinationPath() const +{ + return !IsGroupItem() && (m_tDestinationPath.GetDstPathSource() == TDestinationPathInfo::eDstType_Specified); +} + +bool TShellMenuItem::RequiresClipboardPaths() const +{ + return !IsGroupItem() && (m_tDestinationPath.GetDstPathSource() == TDestinationPathInfo::eDstType_Clipboard || m_tSourcePaths.GetSrcPathsSource() == TSourcePathsInfo::eSrcType_Clipboard); +} + +size_t TShellMenuItem::GetChildrenCount() const +{ + return m_vChildItems.size(); +} + +TShellMenuItemPtr TShellMenuItem::GetChildAt(size_t stIndex) const +{ + return m_vChildItems[stIndex]; +} + +void TShellMenuItem::AddChild(const TShellMenuItemPtr& rItem) +{ + m_vChildItems.push_back(rItem); +} + +void TShellMenuItem::SetChildAt(size_t stIndex, const TShellMenuItemPtr& rItem) +{ + m_vChildItems[stIndex] = rItem; +} + +void TShellMenuItem::InsertChildAt(size_t stIndex, const TShellMenuItemPtr& rItem) +{ + m_vChildItems.insert(m_vChildItems.begin() + stIndex, rItem); +} + +void TShellMenuItem::RemoveChildAt(size_t stIndex) +{ + m_vChildItems.erase(m_vChildItems.begin() + stIndex); +} + +void TShellMenuItem::RemoveAllChildren() +{ + m_vChildItems.clear(); +} + +void TShellMenuItem::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const +{ + std::wstring wstrBuffer; + + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemType")), m_eItemType); + switch(m_eItemType) + { + case eSeparatorItem: + break; + case eGroupItem: + { + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip); + + for(const TShellMenuItemPtr& rItem : m_vChildItems) + { + chcore::TConfig cfgItem; + rItem->StoreInConfig(cfgItem, _T("")); + rConfig.AddSubConfig(Concat(wstrBuffer, pszNodeName, _T("Subitems.Subitem")), cfgItem); + } + + break; + } + case eStandardItem: + { + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SpecialOperation")), m_bSpecialOperation); + SetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultItemHint")), m_eDefaultItemHint); + + m_tOperationType.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationType"))); + m_tSourcePaths.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("SourcePaths"))); + m_tDestinationPath.StoreInConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("DestinationPath"))); + + break; + } + default: + BOOST_ASSERT(false); // unhandled case + } +} + +bool TShellMenuItem::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) +{ + Clear(); + + std::wstring wstrBuffer; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemType")), *(int*)&m_eItemType)) + return false; + switch(m_eItemType) + { + case eSeparatorItem: + break; + case eGroupItem: + { + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName)) + return false; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip)) + return false; + + chcore::TConfigArray vCfgs; + if(rConfig.ExtractMultiSubConfigs(Concat(wstrBuffer, pszNodeName, _T("Subitems.Subitem")), vCfgs)) + { + for(size_t stIndex = 0; stIndex < vCfgs.GetCount(); ++stIndex) + { + chcore::TConfig& rCfg = vCfgs.GetAt(stIndex); + + TShellMenuItemPtr spItem(std::make_shared()); + spItem->ReadFromConfig(rCfg, nullptr); + m_vChildItems.push_back(spItem); + } + } + + break; + } + case eStandardItem: + { + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemName")), m_strName)) + return false; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("ItemDescription")), m_strItemTip)) + return false; + + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("SpecialOperation")), m_bSpecialOperation)) + return false; + if(!GetConfigValue(rConfig, Concat(wstrBuffer, pszNodeName, _T("DefaultItemHint")), *(int*)&m_eDefaultItemHint)) + return false; + + if(!m_tOperationType.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("OperationType")))) + return false; + + if(!m_tSourcePaths.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("SourcePaths")))) + return false; + + if(!m_tDestinationPath.ReadFromConfig(rConfig, Concat(wstrBuffer, pszNodeName, _T("DestinationPath")))) + return false; + + break; + } + default: + BOOST_ASSERT(false); // unhandled case + return false; + } + + return true; +} + +TShellExtMenuConfig::TShellExtMenuConfig() : + m_bInterceptDragAndDrop(false), + m_bInterceptKeyboardActions(false), + m_bInterceptCtxMenuActions(false), + m_bShowShortcutIcons(false), + m_spDragAndDropRoot(std::make_shared(_T(""), _T(""))), + m_spNormalRoot(std::make_shared(_T(""), _T(""))), + m_spFmtSize(std::make_shared()) +{ +} + +TShellExtMenuConfig::~TShellExtMenuConfig() +{ +} + +void TShellExtMenuConfig::Clear() +{ + m_spDragAndDropRoot->Clear(); + + m_bInterceptDragAndDrop = false; + m_bInterceptKeyboardActions = false; + m_bInterceptCtxMenuActions = false; + m_bShowShortcutIcons = false; +} + +// commands support +TShellMenuItemPtr TShellExtMenuConfig::GetDragAndDropRoot() +{ + return m_spDragAndDropRoot; +} + +TShellMenuItemPtr TShellExtMenuConfig::GetNormalRoot() +{ + return m_spNormalRoot; +} + +chcore::TSizeFormatterPtr TShellExtMenuConfig::GetFormatter() const +{ + return m_spFmtSize; +} + +void TShellExtMenuConfig::StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const +{ + std::wstring strBuffer; + SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptDragAndDrop")), m_bInterceptDragAndDrop); + SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptKeyboardActions")), m_bInterceptKeyboardActions); + SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptCtxMenuActions")), m_bInterceptCtxMenuActions); + SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowShortcutIcons")), m_bShowShortcutIcons); + SetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowFreeSpace")), m_bShowFreeSpace); + + m_spFmtSize->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, L"Sizes")); + + m_spDragAndDropRoot->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, _T("DragAndDropRootItem"))); + m_spNormalRoot->StoreInConfig(rConfig, Concat(strBuffer, pszNodeName, _T("NormalRootItem"))); +} + +bool TShellExtMenuConfig::ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) +{ + Clear(); + + std::wstring strBuffer; + if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptDragAndDrop")), m_bInterceptDragAndDrop)) + return false; + if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptKeyboardActions")), m_bInterceptKeyboardActions)) + return false; + if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("InterceptCtxMenuActions")), m_bInterceptCtxMenuActions)) + return false; + if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowShortcutIcons")), m_bShowShortcutIcons)) + return false; + if(!GetConfigValue(rConfig, Concat(strBuffer, pszNodeName, _T("ShowFreeSpace")), m_bShowFreeSpace)) + return false; + + if(!m_spFmtSize->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, L"Sizes"))) + return false; + + if(!m_spDragAndDropRoot->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, _T("DragAndDropRootItem")))) + return false; + if(!m_spNormalRoot->ReadFromConfig(rConfig, Concat(strBuffer, pszNodeName, _T("NormalRootItem")))) + return false; + + return true; +} Index: src/common/TShellExtMenuConfig.h =================================================================== diff -u -r3c248d4f6d0fdb1e487cc868b2f0b219eec37ef4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/common/TShellExtMenuConfig.h (.../TShellExtMenuConfig.h) (revision 3c248d4f6d0fdb1e487cc868b2f0b219eec37ef4) +++ src/common/TShellExtMenuConfig.h (.../TShellExtMenuConfig.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,272 +1,272 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TShellExtMenuConfig.h -/// @date 2011/05/06 -/// @brief Contains class responsible for maintaining shell ext configuration (via shared mem). -// ============================================================================ -#ifndef __TSHELLEXTMENUCONFIG_H__ -#define __TSHELLEXTMENUCONFIG_H__ - -#include "../libchcore/EOperationTypes.h" -#include "../libchcore/TPath.h" -#include -#include "../libchcore/TSizeFormatter.h" - -namespace chcore { class TConfig; } - -class TShellMenuItem; - -typedef std::shared_ptr TShellMenuItemPtr; - -// specifies information about operation type -class TOperationTypeInfo -{ -public: - enum EOperationTypeSource - { - eOpType_Specified, - eOpType_Autodetect, - }; - -public: - TOperationTypeInfo(); - TOperationTypeInfo(EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType); - - void SetOperationTypeInfo(EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType); - - EOperationTypeSource GetOperationTypeSource() const; - chcore::EOperationType GetDefaultOperationType() const; - - void Clear(); - - void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); - -private: - EOperationTypeSource m_eOperationTypeSource; - chcore::EOperationType m_eDefaultOperationType; // default operation type -}; - -// specifies information about source paths -class TSourcePathsInfo -{ -public: - enum ESrcPathsSource - { - eSrcType_Clipboard, - eSrcType_InitializePidlFolder, - eSrcType_InitializeIDataObject, - eSrcType_InitializeAuto, - }; - -public: - TSourcePathsInfo(); - explicit TSourcePathsInfo(ESrcPathsSource eSrcPathSource); - - void SetSourcePathsInfo(ESrcPathsSource eSrcPathSource); - ESrcPathsSource GetSrcPathsSource() const; - - void Clear(); - - void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); - -private: - ESrcPathsSource m_eSrcPathsSource; -}; - -// specifies information about destination path -class TDestinationPathInfo -{ -public: - enum EDstPathsSource - { - eDstType_Specified, - eDstType_Clipboard, - eDstType_InitializePidlFolder, - eDstType_InitializeIDataObject, - eDstType_InitializeAuto, - eDstType_Choose, - }; - -public: - TDestinationPathInfo(); - TDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination); - - void SetDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& m_pathDestination); - EDstPathsSource GetDstPathSource() const; - chcore::TSmartPath GetDefaultDestinationPath() const; - - void Clear(); - - void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); - -private: - EDstPathsSource m_eDstPathSource; - chcore::TSmartPath m_pathDestination; -}; - -// class is not to be exported from DLL (because we're using wstrings here!) -class TShellMenuItem -{ -public: - enum EItemType - { - eStandardItem, - eGroupItem, - eSeparatorItem - }; - -public: - TShellMenuItem(); - TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, - bool bSpecialOperation, chcore::EOperationType eDefaultItemHint = chcore::eOperation_None); - TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip); - - ~TShellMenuItem(); - - // initializer for separator item - void InitSeparatorItem(); - - // initializer for standard item - void InitStandardItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, - bool bSpecialOperation, chcore::EOperationType eDefaultItemHint = chcore::eOperation_None); - - // initializer for group item - void InitGroupItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip); - - // clears everything - void Clear(); - - // retrieving attributes - common ones - const chcore::TString& GetName() const; - const chcore::TString& GetItemTip() const { return m_strItemTip; } - - const chcore::TString& GetLocalName(bool bUseFallback = true) const; - void SetLocalName(const chcore::TString& strLocalName); - - // retrieving attributes - standard items only - const TOperationTypeInfo& GetOperationTypeInfo() const { return m_tOperationType; } - const TDestinationPathInfo& GetDestinationPathInfo() const { return m_tDestinationPath; } - const TSourcePathsInfo& GetSourcePathsInfo() const { return m_tSourcePaths; } - - chcore::EOperationType GetDefaultItemHint() const { return m_eDefaultItemHint; } - - bool IsGroupItem() const { return m_eItemType == eGroupItem; } - bool IsSeparator() const { return m_eItemType == eSeparatorItem; } - bool IsStandardItem() const { return m_eItemType == eStandardItem; } - EItemType GetItemType() const { return m_eItemType; } - - bool IsSpecialOperation() const { return m_bSpecialOperation; } - - // helper - retrieves info if the destination path is already specified - bool SpecifiesDestinationPath() const; - // helper - retrieves info if this command requires some paths present in clipboard to be enabled - bool RequiresClipboardPaths() const; - - // operations on children - size_t GetChildrenCount() const; - TShellMenuItemPtr GetChildAt(size_t stIndex) const; - - void AddChild(const TShellMenuItemPtr& rItem); - void SetChildAt(size_t stIndex, const TShellMenuItemPtr& rItem); - void InsertChildAt(size_t stIndex, const TShellMenuItemPtr& rItem); - - void RemoveChildAt(size_t stIndex); - void RemoveAllChildren(); - - // serialization - void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); - -private: - EItemType m_eItemType; - - chcore::TString m_strName; - chcore::TString m_strLocalName; // locally updated name; not serialized - chcore::TString m_strItemTip; - - // where to get the operation type from? (specified here / autodetect (with fallback specified here)) - TOperationTypeInfo m_tOperationType; - - // where to get the destination path? (specified here / read from clipboard / retrieved in IShellExtInit::Initialize()) - TDestinationPathInfo m_tDestinationPath; - - // where to get source paths? (read from clipboard / retrieved in IShellExtInit::Initialize()) - TSourcePathsInfo m_tSourcePaths; - - // states if the operation allows for modifications before execution (special operation) - bool m_bSpecialOperation; - - // hints that this item is to be made default (bold), when detected operation type is equal to this operation type - chcore::EOperationType m_eDefaultItemHint; - - std::vector m_vChildItems; -}; - -class TShellExtMenuConfig -{ -public: - TShellExtMenuConfig(); - ~TShellExtMenuConfig(); - - void Clear(); - - // commands support - TShellMenuItemPtr GetDragAndDropRoot(); - TShellMenuItemPtr GetNormalRoot(); - - // formatter - chcore::TSizeFormatterPtr GetFormatter() const; - - // options - void SetInterceptDragAndDrop(bool bEnable) { m_bInterceptDragAndDrop = bEnable; } - bool GetInterceptDragAndDrop() const { return m_bInterceptDragAndDrop; } - - void SetInterceptKeyboardActions(bool bEnable) { m_bInterceptKeyboardActions = bEnable; } - bool GetInterceptKeyboardActions() const { return m_bInterceptKeyboardActions; } - - void SetInterceptCtxMenuActions(bool bEnable) { m_bInterceptCtxMenuActions = bEnable; } - bool GetInterceptCtxMenuActions() const { return m_bInterceptCtxMenuActions; } - - void SetShowShortcutIcons(bool bEnable) { m_bShowShortcutIcons = bEnable; } - bool GetShowShortcutIcons() const { return m_bShowShortcutIcons; } - - void SetShowFreeSpace(bool bEnable) { m_bShowFreeSpace = bEnable; } - bool GetShowFreeSpace() const { return m_bShowFreeSpace; } - - // serialize/unserialize - void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); - -private: - TShellMenuItemPtr m_spDragAndDropRoot; // root under which there are commands placed - TShellMenuItemPtr m_spNormalRoot; // root under which there are commands placed - - chcore::TSizeFormatterPtr m_spFmtSize; - - bool m_bInterceptDragAndDrop = false; - bool m_bInterceptKeyboardActions = false; - bool m_bInterceptCtxMenuActions = false; - bool m_bShowShortcutIcons = false; // show shell icons with shortcuts ? - bool m_bShowFreeSpace = false; -}; - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TShellExtMenuConfig.h +/// @date 2011/05/06 +/// @brief Contains class responsible for maintaining shell ext configuration (via shared mem). +// ============================================================================ +#ifndef __TSHELLEXTMENUCONFIG_H__ +#define __TSHELLEXTMENUCONFIG_H__ + +#include "../libchcore/EOperationTypes.h" +#include "../libchcore/TPath.h" +#include +#include "../libchcore/TSizeFormatter.h" + +namespace chcore { class TConfig; } + +class TShellMenuItem; + +typedef std::shared_ptr TShellMenuItemPtr; + +// specifies information about operation type +class TOperationTypeInfo +{ +public: + enum EOperationTypeSource + { + eOpType_Specified, + eOpType_Autodetect, + }; + +public: + TOperationTypeInfo(); + TOperationTypeInfo(EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType); + + void SetOperationTypeInfo(EOperationTypeSource eType, chcore::EOperationType eDefaultOperationType); + + EOperationTypeSource GetOperationTypeSource() const; + chcore::EOperationType GetDefaultOperationType() const; + + void Clear(); + + void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); + +private: + EOperationTypeSource m_eOperationTypeSource; + chcore::EOperationType m_eDefaultOperationType; // default operation type +}; + +// specifies information about source paths +class TSourcePathsInfo +{ +public: + enum ESrcPathsSource + { + eSrcType_Clipboard, + eSrcType_InitializePidlFolder, + eSrcType_InitializeIDataObject, + eSrcType_InitializeAuto, + }; + +public: + TSourcePathsInfo(); + explicit TSourcePathsInfo(ESrcPathsSource eSrcPathSource); + + void SetSourcePathsInfo(ESrcPathsSource eSrcPathSource); + ESrcPathsSource GetSrcPathsSource() const; + + void Clear(); + + void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); + +private: + ESrcPathsSource m_eSrcPathsSource; +}; + +// specifies information about destination path +class TDestinationPathInfo +{ +public: + enum EDstPathsSource + { + eDstType_Specified, + eDstType_Clipboard, + eDstType_InitializePidlFolder, + eDstType_InitializeIDataObject, + eDstType_InitializeAuto, + eDstType_Choose, + }; + +public: + TDestinationPathInfo(); + TDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& pathDestination); + + void SetDestinationPathInfo(EDstPathsSource eDstPathSource, const chcore::TSmartPath& m_pathDestination); + EDstPathsSource GetDstPathSource() const; + chcore::TSmartPath GetDefaultDestinationPath() const; + + void Clear(); + + void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); + +private: + EDstPathsSource m_eDstPathSource; + chcore::TSmartPath m_pathDestination; +}; + +// class is not to be exported from DLL (because we're using wstrings here!) +class TShellMenuItem +{ +public: + enum EItemType + { + eStandardItem, + eGroupItem, + eSeparatorItem + }; + +public: + TShellMenuItem(); + TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, + bool bSpecialOperation, chcore::EOperationType eDefaultItemHint = chcore::eOperation_None); + TShellMenuItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip); + + ~TShellMenuItem(); + + // initializer for separator item + void InitSeparatorItem(); + + // initializer for standard item + void InitStandardItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip, const TOperationTypeInfo& rOperationType, const TSourcePathsInfo& rSourcePaths, const TDestinationPathInfo& rDestinationPath, + bool bSpecialOperation, chcore::EOperationType eDefaultItemHint = chcore::eOperation_None); + + // initializer for group item + void InitGroupItem(const chcore::TString& wstrName, const chcore::TString& wstrItemTip); + + // clears everything + void Clear(); + + // retrieving attributes - common ones + const chcore::TString& GetName() const; + const chcore::TString& GetItemTip() const { return m_strItemTip; } + + const chcore::TString& GetLocalName(bool bUseFallback = true) const; + void SetLocalName(const chcore::TString& strLocalName); + + // retrieving attributes - standard items only + const TOperationTypeInfo& GetOperationTypeInfo() const { return m_tOperationType; } + const TDestinationPathInfo& GetDestinationPathInfo() const { return m_tDestinationPath; } + const TSourcePathsInfo& GetSourcePathsInfo() const { return m_tSourcePaths; } + + chcore::EOperationType GetDefaultItemHint() const { return m_eDefaultItemHint; } + + bool IsGroupItem() const { return m_eItemType == eGroupItem; } + bool IsSeparator() const { return m_eItemType == eSeparatorItem; } + bool IsStandardItem() const { return m_eItemType == eStandardItem; } + EItemType GetItemType() const { return m_eItemType; } + + bool IsSpecialOperation() const { return m_bSpecialOperation; } + + // helper - retrieves info if the destination path is already specified + bool SpecifiesDestinationPath() const; + // helper - retrieves info if this command requires some paths present in clipboard to be enabled + bool RequiresClipboardPaths() const; + + // operations on children + size_t GetChildrenCount() const; + TShellMenuItemPtr GetChildAt(size_t stIndex) const; + + void AddChild(const TShellMenuItemPtr& rItem); + void SetChildAt(size_t stIndex, const TShellMenuItemPtr& rItem); + void InsertChildAt(size_t stIndex, const TShellMenuItemPtr& rItem); + + void RemoveChildAt(size_t stIndex); + void RemoveAllChildren(); + + // serialization + void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); + +private: + EItemType m_eItemType; + + chcore::TString m_strName; + chcore::TString m_strLocalName; // locally updated name; not serialized + chcore::TString m_strItemTip; + + // where to get the operation type from? (specified here / autodetect (with fallback specified here)) + TOperationTypeInfo m_tOperationType; + + // where to get the destination path? (specified here / read from clipboard / retrieved in IShellExtInit::Initialize()) + TDestinationPathInfo m_tDestinationPath; + + // where to get source paths? (read from clipboard / retrieved in IShellExtInit::Initialize()) + TSourcePathsInfo m_tSourcePaths; + + // states if the operation allows for modifications before execution (special operation) + bool m_bSpecialOperation; + + // hints that this item is to be made default (bold), when detected operation type is equal to this operation type + chcore::EOperationType m_eDefaultItemHint; + + std::vector m_vChildItems; +}; + +class TShellExtMenuConfig +{ +public: + TShellExtMenuConfig(); + ~TShellExtMenuConfig(); + + void Clear(); + + // commands support + TShellMenuItemPtr GetDragAndDropRoot(); + TShellMenuItemPtr GetNormalRoot(); + + // formatter + chcore::TSizeFormatterPtr GetFormatter() const; + + // options + void SetInterceptDragAndDrop(bool bEnable) { m_bInterceptDragAndDrop = bEnable; } + bool GetInterceptDragAndDrop() const { return m_bInterceptDragAndDrop; } + + void SetInterceptKeyboardActions(bool bEnable) { m_bInterceptKeyboardActions = bEnable; } + bool GetInterceptKeyboardActions() const { return m_bInterceptKeyboardActions; } + + void SetInterceptCtxMenuActions(bool bEnable) { m_bInterceptCtxMenuActions = bEnable; } + bool GetInterceptCtxMenuActions() const { return m_bInterceptCtxMenuActions; } + + void SetShowShortcutIcons(bool bEnable) { m_bShowShortcutIcons = bEnable; } + bool GetShowShortcutIcons() const { return m_bShowShortcutIcons; } + + void SetShowFreeSpace(bool bEnable) { m_bShowFreeSpace = bEnable; } + bool GetShowFreeSpace() const { return m_bShowFreeSpace; } + + // serialize/unserialize + void StoreInConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(chcore::TConfig& rConfig, PCTSTR pszNodeName); + +private: + TShellMenuItemPtr m_spDragAndDropRoot; // root under which there are commands placed + TShellMenuItemPtr m_spNormalRoot; // root under which there are commands placed + + chcore::TSizeFormatterPtr m_spFmtSize; + + bool m_bInterceptDragAndDrop = false; + bool m_bInterceptKeyboardActions = false; + bool m_bInterceptCtxMenuActions = false; + bool m_bShowShortcutIcons = false; // show shell icons with shortcuts ? + bool m_bShowFreeSpace = false; +}; + +#endif Index: src/common/version.h.template =================================================================== diff -u -r7d8c9da741be09c4ed23dcee96ac0e736714eff5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/common/version.h.template (.../version.h.template) (revision 7d8c9da741be09c4ed23dcee96ac0e736714eff5) +++ src/common/version.h.template (.../version.h.template) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,43 +1,43 @@ -#ifndef __VERSION_H__ -#define __VERSION_H__ - -// note that this file is also being used by setup compiler; -// in this case the SETUP_COMPILER is defined with value 1 -// Product name -#define PRODUCT_NAME "Copy Handler" -// shell extension -#define SHELLEXT_PRODUCT_NAME "Copy Handler Shell Extension" - -// Version of program -#define PRODUCT_VERSION1 {major_version} -#define PRODUCT_VERSION2 {minor_version} -#define PRODUCT_VERSION3 {svn_version} -#define PRODUCT_VERSION4 {custom_version} - -#if SETUP_COMPILER != 1 - #define PRODUCT_FULL_NUMERIC_VERSION ((unsigned long long)PRODUCT_VERSION1) << 48 | ((unsigned long long)PRODUCT_VERSION2) << 32 | ((unsigned long long)PRODUCT_VERSION3) << 16 | ((unsigned long long)PRODUCT_VERSION4) - - #define STRINGIZE2(a) STRINGIZE(a) - #define STRINGIZE(a) L#a - - #define PRODUCT_NUMERIC_VERSION STRINGIZE2(PRODUCT_VERSION1) L"." STRINGIZE2(PRODUCT_VERSION2) L"." STRINGIZE2(PRODUCT_VERSION3) L"." STRINGIZE2(PRODUCT_VERSION4) -#endif - -#define PRODUCT_VERSION "{text_version}" - -#if SETUP_COMPILER != 1 - #define SHELLEXT_PRODUCT_FULL_VERSION SHELLEXT_PRODUCT_NAME " " PRODUCT_VERSION - #define SHELLEXT_PRODUCT_FULL_VERSION_T _T(SHELLEXT_PRODUCT_NAME) _T(" ") _T(PRODUCT_VERSION) - - #define PRODUCT_FULL_VERSION PRODUCT_NAME " " PRODUCT_VERSION - #define PRODUCT_FULL_VERSION_T _T(PRODUCT_NAME) _T(" ") _T(PRODUCT_VERSION) -#endif - -// copyright information -#define COPYRIGHT_INFO "Copyright (C) 2001-2016 J�zef Starosczyk" -#define PRODUCT_SITE "http://www.copyhandler.com" -#define UPDATE_CHECK_LINK_SECURE "https://www.copyhandler.com/update-check" -#define UPDATE_CHECK_LINK_NONSECURE "http://www.copyhandler.com/update-check" -#define CONTACT_INFO "http://www.copyhandler.com/contact" - -#endif +#ifndef __VERSION_H__ +#define __VERSION_H__ + +// note that this file is also being used by setup compiler; +// in this case the SETUP_COMPILER is defined with value 1 +// Product name +#define PRODUCT_NAME "Copy Handler" +// shell extension +#define SHELLEXT_PRODUCT_NAME "Copy Handler Shell Extension" + +// Version of program +#define PRODUCT_VERSION1 {major_version} +#define PRODUCT_VERSION2 {minor_version} +#define PRODUCT_VERSION3 {svn_version} +#define PRODUCT_VERSION4 {custom_version} + +#if SETUP_COMPILER != 1 + #define PRODUCT_FULL_NUMERIC_VERSION ((unsigned long long)PRODUCT_VERSION1) << 48 | ((unsigned long long)PRODUCT_VERSION2) << 32 | ((unsigned long long)PRODUCT_VERSION3) << 16 | ((unsigned long long)PRODUCT_VERSION4) + + #define STRINGIZE2(a) STRINGIZE(a) + #define STRINGIZE(a) L#a + + #define PRODUCT_NUMERIC_VERSION STRINGIZE2(PRODUCT_VERSION1) L"." STRINGIZE2(PRODUCT_VERSION2) L"." STRINGIZE2(PRODUCT_VERSION3) L"." STRINGIZE2(PRODUCT_VERSION4) +#endif + +#define PRODUCT_VERSION "{text_version}" + +#if SETUP_COMPILER != 1 + #define SHELLEXT_PRODUCT_FULL_VERSION SHELLEXT_PRODUCT_NAME " " PRODUCT_VERSION + #define SHELLEXT_PRODUCT_FULL_VERSION_T _T(SHELLEXT_PRODUCT_NAME) _T(" ") _T(PRODUCT_VERSION) + + #define PRODUCT_FULL_VERSION PRODUCT_NAME " " PRODUCT_VERSION + #define PRODUCT_FULL_VERSION_T _T(PRODUCT_NAME) _T(" ") _T(PRODUCT_VERSION) +#endif + +// copyright information +#define COPYRIGHT_INFO "Copyright (C) 2001-2016 J�zef Starosczyk" +#define PRODUCT_SITE "http://www.copyhandler.com" +#define UPDATE_CHECK_LINK_SECURE "https://www.copyhandler.com/update-check" +#define UPDATE_CHECK_LINK_NONSECURE "http://www.copyhandler.com/update-check" +#define CONTACT_INFO "http://www.copyhandler.com/contact" + +#endif Index: src/ictranslate/ictranslate.rc =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/ictranslate/ictranslate.rc (.../ictranslate.rc) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/ictranslate/ictranslate.rc (.../ictranslate.rc) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,253 +1,253 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#ifndef APSTUDIO_INVOKED -#include "targetver.h" -#endif -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Polish resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PLK) -#ifdef _WIN32 -LANGUAGE LANG_POLISH, SUBLANG_DEFAULT -#pragma code_page(1250) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#ifndef APSTUDIO_INVOKED\r\n" - "#include ""targetver.h""\r\n" - "#endif\r\n" - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#define _AFX_NO_SPLITTER_RESOURCES\r\n" - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#include ""res\\ictranslate.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#include ""afxres.rc"" // Standard components\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\ictranslate.ico" -IDI_NONEXISTENT_ICON ICON "res\\icon_nonexistent.ico" -IDI_VALID_ICON ICON "res\\icon_valid.ico" -IDI_INVALID_ICON ICON "res\\icon_invalid.ico" -IDI_OVERFLUOUS_ICON ICON "res\\icon_overfluous.ico" -IDI_WARNING_ICON ICON "res\\icon_warning.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MAIN_MENU MENU -BEGIN - POPUP "&File" - BEGIN - MENUITEM "&New translation...\tCtrl+N", ID_FILE_NEWTRANSLATION - MENUITEM "&Open base translation...\tCtrl+O", ID_FILE_OPENBASETRANSLATION - MENUITEM "Open your translation...\tCtrl+T", ID_FILE_OPENYOURTRANSLATION - MENUITEM "&Save translation\tCtrl+S", ID_FILE_SAVETRANSLATION - MENUITEM "S&ave translation as...", ID_FILE_SAVETRANSLATIONAS - END - POPUP "&Edit" - BEGIN - MENUITEM "&Cleanup translation", ID_EDIT_CLEANUP_TRANSLATION - MENUITEM SEPARATOR - MENUITEM "&Previous to translate\tCtrl+Up", ID_EDIT_PREVIOUS_TO_TRANSLATE - MENUITEM "&Next to translate\tCtrl+Down", ID_EDIT_NEXT_TO_TRANSLATE - MENUITEM "&Apply change", ID_EDIT_APPLY_CHANGE - MENUITEM "Apply&&next to t&ranslate\tCtrl+Enter", ID_EDIT_APPLY_AND_NEXT - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDR_ACCELERATOR ACCELERATORS -BEGIN - VK_DOWN, ID_EDIT_NEXT_TO_TRANSLATE, VIRTKEY, CONTROL, NOINVERT - VK_RETURN, ID_EDIT_APPLY_AND_NEXT, VIRTKEY, CONTROL, NOINVERT - "^S", ID_FILE_SAVETRANSLATION, ASCII, NOINVERT - "^N", ID_FILE_NEWTRANSLATION, ASCII, NOINVERT - VK_UP, ID_EDIT_PREVIOUS_TO_TRANSLATE, VIRTKEY, CONTROL, NOINVERT - "^O", ID_FILE_OPENBASETRANSLATION, ASCII, NOINVERT - "^T", ID_FILE_OPENYOURTRANSLATION, ASCII, NOINVERT -END - -#endif // Polish resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOGEX 0, 0, 170, 62 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About ictranslate" -FONT 8, "MS Shell Dlg", 0, 0, 0x1 -BEGIN - ICON IDR_MAINFRAME,IDC_STATIC,14,14,21,20 - LTEXT "ictranslate, Version 1.0",IDC_STATIC,42,14,114,8,SS_NOPREFIX - LTEXT "Copyright (C) 2008",IDC_STATIC,42,26,114,8 - DEFPUSHBUTTON "OK",IDOK,113,41,50,14,WS_GROUP -END - -IDD_ICTRANSLATE_DIALOG DIALOGEX 0, 0, 547, 335 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -EXSTYLE WS_EX_APPWINDOW -CAPTION "ICTranslate" -MENU IDR_MAIN_MENU -FONT 8, "MS Shell Dlg", 0, 0, 0x1 -BEGIN - EDITTEXT IDC_SRC_FILENAME_EDIT,69,7,201,14,ES_AUTOHSCROLL | ES_READONLY - EDITTEXT IDC_SRC_AUTHOR_EDIT,69,22,201,14,ES_AUTOHSCROLL | ES_READONLY - EDITTEXT IDC_SRC_LANGUAGE_NAME_EDIT,69,37,201,14,ES_AUTOHSCROLL | ES_READONLY - EDITTEXT IDC_SRC_HELP_FILENAME_EDIT,69,52,201,14,ES_AUTOHSCROLL | ES_READONLY - EDITTEXT IDC_SRC_FONT_EDIT,69,67,201,14,ES_AUTOHSCROLL | ES_READONLY - CONTROL "Right-to-left reading order",IDC_SRC_RTL_CHECK,"Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,7,84,263,10 - EDITTEXT IDC_DST_FILENAME_EDIT,339,7,201,14,ES_AUTOHSCROLL | ES_READONLY - EDITTEXT IDC_DST_AUTHOR_EDIT,339,22,201,14,ES_AUTOHSCROLL - EDITTEXT IDC_DST_LANGUAGE_NAME_EDIT,339,37,201,14,ES_AUTOHSCROLL - EDITTEXT IDC_DST_HELP_FILENAME_EDIT,339,52,201,14,ES_AUTOHSCROLL - EDITTEXT IDC_DST_FONT_EDIT,339,67,184,14,ES_AUTOHSCROLL | ES_READONLY - PUSHBUTTON "&...",IDC_CHOOSE_FONT_BUTTON,524,67,16,14 - CONTROL "Right-to-left reading order",IDC_DST_RTL_CHECK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,277,84,263,10 - CONTROL "",IDC_SRCDATA_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,7,114,263,151 - CONTROL "",IDC_DSTDATA_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,277,114,263,151 - PUSHBUTTON "&>\n>",IDC_COPY_BUTTON,267,271,15,37,BS_MULTILINE - PUSHBUTTON "&Apply change",IDAPPLY,471,314,69,14 - LTEXT "Base translation:",IDC_STATIC,7,104,262,8 - LTEXT "Your translation:",IDC_STATIC,277,104,263,8 - LTEXT "Author:",IDC_STATIC,7,25,58,8 - LTEXT "File:",IDC_STATIC,7,10,58,8 - LTEXT "Language name:",IDC_STATIC,7,40,58,8 - LTEXT "Font:",IDC_STATIC,7,70,58,8 - LTEXT "Help file name:",IDC_STATIC,7,55,58,8 - LTEXT "Author:",IDC_STATIC,277,25,58,8 - LTEXT "File:",IDC_STATIC,277,10,58,8 - LTEXT "Language name:",IDC_STATIC,277,40,58,8 - LTEXT "Font:",IDC_STATIC,277,70,58,8 - LTEXT "Help file name:",IDC_STATIC,277,55,58,8 - CONTROL "",IDC_SRCDATA_RICHEDIT,"RichEdit20W",ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | ES_WANTRETURN | WS_BORDER | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,7,266,257,62 - CONTROL "",IDC_DSTDATA_RICHEDIT,"RichEdit20W",ES_MULTILINE | ES_AUTOHSCROLL | ES_WANTRETURN | WS_BORDER | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,286,267,254,44 -END - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 163 - TOPMARGIN, 7 - BOTTOMMARGIN, 55 - END - - IDD_ICTRANSLATE_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 540 - TOPMARGIN, 7 - BOTTOMMARGIN, 328 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_ABOUTBOX "&About ictranslate..." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_SPLITTER_RESOURCES -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 -#pragma code_page(1252) -#include "res\ictranslate.rc2" // non-Microsoft Visual C++ edited resources -#include "afxres.rc" // Standard components -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#ifndef APSTUDIO_INVOKED +#include "targetver.h" +#endif +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Polish resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PLK) +#ifdef _WIN32 +LANGUAGE LANG_POLISH, SUBLANG_DEFAULT +#pragma code_page(1250) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#ifndef APSTUDIO_INVOKED\r\n" + "#include ""targetver.h""\r\n" + "#endif\r\n" + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#include ""res\\ictranslate.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\ictranslate.ico" +IDI_NONEXISTENT_ICON ICON "res\\icon_nonexistent.ico" +IDI_VALID_ICON ICON "res\\icon_valid.ico" +IDI_INVALID_ICON ICON "res\\icon_invalid.ico" +IDI_OVERFLUOUS_ICON ICON "res\\icon_overfluous.ico" +IDI_WARNING_ICON ICON "res\\icon_warning.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MAIN_MENU MENU +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&New translation...\tCtrl+N", ID_FILE_NEWTRANSLATION + MENUITEM "&Open base translation...\tCtrl+O", ID_FILE_OPENBASETRANSLATION + MENUITEM "Open your translation...\tCtrl+T", ID_FILE_OPENYOURTRANSLATION + MENUITEM "&Save translation\tCtrl+S", ID_FILE_SAVETRANSLATION + MENUITEM "S&ave translation as...", ID_FILE_SAVETRANSLATIONAS + END + POPUP "&Edit" + BEGIN + MENUITEM "&Cleanup translation", ID_EDIT_CLEANUP_TRANSLATION + MENUITEM SEPARATOR + MENUITEM "&Previous to translate\tCtrl+Up", ID_EDIT_PREVIOUS_TO_TRANSLATE + MENUITEM "&Next to translate\tCtrl+Down", ID_EDIT_NEXT_TO_TRANSLATE + MENUITEM "&Apply change", ID_EDIT_APPLY_CHANGE + MENUITEM "Apply&&next to t&ranslate\tCtrl+Enter", ID_EDIT_APPLY_AND_NEXT + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDR_ACCELERATOR ACCELERATORS +BEGIN + VK_DOWN, ID_EDIT_NEXT_TO_TRANSLATE, VIRTKEY, CONTROL, NOINVERT + VK_RETURN, ID_EDIT_APPLY_AND_NEXT, VIRTKEY, CONTROL, NOINVERT + "^S", ID_FILE_SAVETRANSLATION, ASCII, NOINVERT + "^N", ID_FILE_NEWTRANSLATION, ASCII, NOINVERT + VK_UP, ID_EDIT_PREVIOUS_TO_TRANSLATE, VIRTKEY, CONTROL, NOINVERT + "^O", ID_FILE_OPENBASETRANSLATION, ASCII, NOINVERT + "^T", ID_FILE_OPENYOURTRANSLATION, ASCII, NOINVERT +END + +#endif // Polish resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOGEX 0, 0, 170, 62 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About ictranslate" +FONT 8, "MS Shell Dlg", 0, 0, 0x1 +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,14,14,21,20 + LTEXT "ictranslate, Version 1.0",IDC_STATIC,42,14,114,8,SS_NOPREFIX + LTEXT "Copyright (C) 2008",IDC_STATIC,42,26,114,8 + DEFPUSHBUTTON "OK",IDOK,113,41,50,14,WS_GROUP +END + +IDD_ICTRANSLATE_DIALOG DIALOGEX 0, 0, 547, 335 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "ICTranslate" +MENU IDR_MAIN_MENU +FONT 8, "MS Shell Dlg", 0, 0, 0x1 +BEGIN + EDITTEXT IDC_SRC_FILENAME_EDIT,69,7,201,14,ES_AUTOHSCROLL | ES_READONLY + EDITTEXT IDC_SRC_AUTHOR_EDIT,69,22,201,14,ES_AUTOHSCROLL | ES_READONLY + EDITTEXT IDC_SRC_LANGUAGE_NAME_EDIT,69,37,201,14,ES_AUTOHSCROLL | ES_READONLY + EDITTEXT IDC_SRC_HELP_FILENAME_EDIT,69,52,201,14,ES_AUTOHSCROLL | ES_READONLY + EDITTEXT IDC_SRC_FONT_EDIT,69,67,201,14,ES_AUTOHSCROLL | ES_READONLY + CONTROL "Right-to-left reading order",IDC_SRC_RTL_CHECK,"Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,7,84,263,10 + EDITTEXT IDC_DST_FILENAME_EDIT,339,7,201,14,ES_AUTOHSCROLL | ES_READONLY + EDITTEXT IDC_DST_AUTHOR_EDIT,339,22,201,14,ES_AUTOHSCROLL + EDITTEXT IDC_DST_LANGUAGE_NAME_EDIT,339,37,201,14,ES_AUTOHSCROLL + EDITTEXT IDC_DST_HELP_FILENAME_EDIT,339,52,201,14,ES_AUTOHSCROLL + EDITTEXT IDC_DST_FONT_EDIT,339,67,184,14,ES_AUTOHSCROLL | ES_READONLY + PUSHBUTTON "&...",IDC_CHOOSE_FONT_BUTTON,524,67,16,14 + CONTROL "Right-to-left reading order",IDC_DST_RTL_CHECK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,277,84,263,10 + CONTROL "",IDC_SRCDATA_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,7,114,263,151 + CONTROL "",IDC_DSTDATA_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,277,114,263,151 + PUSHBUTTON "&>\n>",IDC_COPY_BUTTON,267,271,15,37,BS_MULTILINE + PUSHBUTTON "&Apply change",IDAPPLY,471,314,69,14 + LTEXT "Base translation:",IDC_STATIC,7,104,262,8 + LTEXT "Your translation:",IDC_STATIC,277,104,263,8 + LTEXT "Author:",IDC_STATIC,7,25,58,8 + LTEXT "File:",IDC_STATIC,7,10,58,8 + LTEXT "Language name:",IDC_STATIC,7,40,58,8 + LTEXT "Font:",IDC_STATIC,7,70,58,8 + LTEXT "Help file name:",IDC_STATIC,7,55,58,8 + LTEXT "Author:",IDC_STATIC,277,25,58,8 + LTEXT "File:",IDC_STATIC,277,10,58,8 + LTEXT "Language name:",IDC_STATIC,277,40,58,8 + LTEXT "Font:",IDC_STATIC,277,70,58,8 + LTEXT "Help file name:",IDC_STATIC,277,55,58,8 + CONTROL "",IDC_SRCDATA_RICHEDIT,"RichEdit20W",ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | ES_WANTRETURN | WS_BORDER | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,7,266,257,62 + CONTROL "",IDC_DSTDATA_RICHEDIT,"RichEdit20W",ES_MULTILINE | ES_AUTOHSCROLL | ES_WANTRETURN | WS_BORDER | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,286,267,254,44 +END + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 163 + TOPMARGIN, 7 + BOTTOMMARGIN, 55 + END + + IDD_ICTRANSLATE_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 540 + TOPMARGIN, 7 + BOTTOMMARGIN, 328 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_ABOUTBOX "&About ictranslate..." +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE 9, 1 +#pragma code_page(1252) +#include "res\ictranslate.rc2" // non-Microsoft Visual C++ edited resources +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + Index: src/ictranslate/ictranslate.vc140.vcxproj =================================================================== diff -u -rf0b3178897bcff99beb7fde44dfe952ccbf40bec -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/ictranslate/ictranslate.vc140.vcxproj (.../ictranslate.vc140.vcxproj) (revision f0b3178897bcff99beb7fde44dfe952ccbf40bec) +++ src/ictranslate/ictranslate.vc140.vcxproj (.../ictranslate.vc140.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,541 +1,541 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - Testing Debug - Win32 - - - Testing Debug - x64 - - - Testing Release - Win32 - - - Testing Release - x64 - - - - ictranslate - {B0292250-B70C-4395-9859-F181FB113DA8} - ictranslate - MFCProj - - - - Application - v120_xp - Dynamic - Unicode - true - - - Application - v120_xp - Dynamic - Unicode - true - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - true - - - Application - v120_xp - Dynamic - Unicode - true - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.51106.1 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64 - - - - _DEBUG;%(PreprocessorDefinitions) - false - true - - - Disabled - WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - NoExtensions - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Windows - MachineX86 - "$(OutDir)" - true - - - - - _DEBUG;%(PreprocessorDefinitions) - false - true - - - Disabled - WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - NoExtensions - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Console - MachineX86 - gmock32d.lib - "$(OutDir)" - true - - - cd "$(TargetDir)" -"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" - - - - - - _DEBUG;%(PreprocessorDefinitions) - false - X64 - - - Disabled - WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Windows - MachineX64 - "$(OutDir)" - false - - - - - _DEBUG;%(PreprocessorDefinitions) - false - X64 - - - Disabled - WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Console - MachineX64 - gmock64d.lib - "$(OutDir)" - false - - - cd "$(TargetDir)" -"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" - - - - - - NDEBUG;%(PreprocessorDefinitions) - false - true - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - NoExtensions - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Windows - true - true - MachineX86 - "$(OutDir)" - true - - - - - NDEBUG;%(PreprocessorDefinitions) - false - true - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) - false - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - NoExtensions - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Console - true - true - MachineX86 - gmock32.lib - "$(OutDir)" - true - - - cd "$(TargetDir)" -"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" - - - - - - NDEBUG;%(PreprocessorDefinitions) - false - X64 - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Windows - true - true - MachineX64 - "$(OutDir)" - false - - - - - NDEBUG;%(PreprocessorDefinitions) - false - X64 - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) - false - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - true - Console - true - true - MachineX64 - gmock64.lib - "$(OutDir)" - false - - - cd "$(TargetDir)" -"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" - - - - - - {dd1f3242-7ee4-4f41-8b8d-d833300c445f} - - - - - true - true - true - true - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + Testing Debug + Win32 + + + Testing Debug + x64 + + + Testing Release + Win32 + + + Testing Release + x64 + + + + ictranslate + {B0292250-B70C-4395-9859-F181FB113DA8} + ictranslate + MFCProj + + + + Application + v120_xp + Dynamic + Unicode + true + + + Application + v120_xp + Dynamic + Unicode + true + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + true + + + Application + v120_xp + Dynamic + Unicode + true + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>11.0.51106.1 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64 + + + + _DEBUG;%(PreprocessorDefinitions) + false + true + + + Disabled + WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + NoExtensions + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Windows + MachineX86 + "$(OutDir)" + true + + + + + _DEBUG;%(PreprocessorDefinitions) + false + true + + + Disabled + WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + NoExtensions + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Console + MachineX86 + gmock32d.lib + "$(OutDir)" + true + + + cd "$(TargetDir)" +"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" + + + + + + _DEBUG;%(PreprocessorDefinitions) + false + X64 + + + Disabled + WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Windows + MachineX64 + "$(OutDir)" + false + + + + + _DEBUG;%(PreprocessorDefinitions) + false + X64 + + + Disabled + WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Console + MachineX64 + gmock64d.lib + "$(OutDir)" + false + + + cd "$(TargetDir)" +"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" + + + + + + NDEBUG;%(PreprocessorDefinitions) + false + true + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + NoExtensions + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Windows + true + true + MachineX86 + "$(OutDir)" + true + + + + + NDEBUG;%(PreprocessorDefinitions) + false + true + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) + false + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + NoExtensions + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Console + true + true + MachineX86 + gmock32.lib + "$(OutDir)" + true + + + cd "$(TargetDir)" +"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" + + + + + + NDEBUG;%(PreprocessorDefinitions) + false + X64 + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Windows + true + true + MachineX64 + "$(OutDir)" + false + + + + + NDEBUG;%(PreprocessorDefinitions) + false + X64 + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;_CONSOLE;%(PreprocessorDefinitions) + false + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + true + Console + true + true + MachineX64 + gmock64.lib + "$(OutDir)" + false + + + cd "$(TargetDir)" +"$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" + + + + + + {dd1f3242-7ee4-4f41-8b8d-d833300c445f} + + + + + true + true + true + true + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + + + + + Create + Create + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file Index: src/ictranslate/ictranslate.vc140.vcxproj.filters =================================================================== diff -u -rcf548451bd35c97a8ae2643a4ffb311f93660962 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/ictranslate/ictranslate.vc140.vcxproj.filters (.../ictranslate.vc140.vcxproj.filters) (revision cf548451bd35c97a8ae2643a4ffb311f93660962) +++ src/ictranslate/ictranslate.vc140.vcxproj.filters (.../ictranslate.vc140.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,81 +1,81 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - {03f4b207-02d6-436e-ba87-91ae5a63ccdd} - - - - - Source Files - - - Source Files - - - Source Files - - - Tests - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - Resource Files - - - Resource Files - - - Resource Files - - - Resource Files - - - Resource Files - - - - - Resource Files - - - - - Resource Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + {03f4b207-02d6-436e-ba87-91ae5a63ccdd} + + + + + Source Files + + + Source Files + + + Source Files + + + Tests + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Resource Files + + + Resource Files + + + Resource Files + + + Resource Files + + + Resource Files + + + Resource Files + + + + + Resource Files + + + + + Resource Files + + \ No newline at end of file Index: src/ictranslate/res/ictranslate.rc2 =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/ictranslate/res/ictranslate.rc2 (.../ictranslate.rc2) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/ictranslate/res/ictranslate.rc2 (.../ictranslate.rc2) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,51 +1,51 @@ -// -// ictranslate.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED -#error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - -#include "../common/version.h" - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x29L -#else - FILEFLAGS 0x28L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Program for translating Copy Handler to various languages" - VALUE "CompanyName", " " - VALUE "FileDescription", "Copy Handler Translator" - VALUE "FileVersion", PRODUCT_VERSION - VALUE "LegalCopyright", COPYRIGHT_INFO - VALUE "LegalTrademarks", " " - VALUE "OriginalFilename", "ictranslate.exe" - VALUE "ProductName", "Copy Handler" - VALUE "ProductVersion", PRODUCT_VERSION - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END +// +// ictranslate.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED +#error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + +#include "../common/version.h" + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x29L +#else + FILEFLAGS 0x28L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Program for translating Copy Handler to various languages" + VALUE "CompanyName", " " + VALUE "FileDescription", "Copy Handler Translator" + VALUE "FileVersion", PRODUCT_VERSION + VALUE "LegalCopyright", COPYRIGHT_INFO + VALUE "LegalTrademarks", " " + VALUE "OriginalFilename", "ictranslate.exe" + VALUE "ProductName", "Copy Handler" + VALUE "ProductVersion", PRODUCT_VERSION + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END Index: src/libchcore/CommonDataTypes.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/CommonDataTypes.h (.../CommonDataTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/CommonDataTypes.h (.../CommonDataTypes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,28 +1,28 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __COMMONDATATYPES_H__ -#define __COMMONDATATYPES_H__ - -namespace chcore -{ - typedef unsigned long file_count_t; - typedef unsigned long long file_size_t; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __COMMONDATATYPES_H__ +#define __COMMONDATATYPES_H__ + +namespace chcore +{ + typedef unsigned long file_count_t; + typedef unsigned long long file_size_t; +} + +#endif Index: src/libchcore/ConfigNode.cpp =================================================================== diff -u -rcb4e9d4b60d62b25ae2cf556c0642601af56c787 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ConfigNode.cpp (.../ConfigNode.cpp) (revision cb4e9d4b60d62b25ae2cf556c0642601af56c787) +++ src/libchcore/ConfigNode.cpp (.../ConfigNode.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,68 +1,68 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ConfigNode.h" - -namespace chcore -{ - namespace details - { - ConfigNode::ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue) : - m_oidObjectID(oidObjectID), - m_iOrder(m_setModifications, iOrder), - m_strNodeName(m_setModifications, strNodeName), - m_strValue(m_setModifications, strValue) - { - m_setModifications[eMod_Added] = true; - } - - ConfigNode::ConfigNode(const ConfigNode& rSrc) : - m_oidObjectID(rSrc.m_oidObjectID), - m_iOrder(m_setModifications, rSrc.m_iOrder), - m_strNodeName(m_setModifications, rSrc.m_strNodeName), - m_strValue(m_setModifications, rSrc.m_strValue), - m_setModifications(rSrc.m_setModifications) - { - } - - ConfigNode& ConfigNode::operator=(const ConfigNode& rSrc) - { - if (this != &rSrc) - { - m_oidObjectID = rSrc.m_oidObjectID; - m_iOrder = rSrc.m_iOrder; - m_strNodeName = rSrc.m_strNodeName; - m_strValue = rSrc.m_strValue; - m_setModifications = rSrc.m_setModifications; - } - - return *this; - } - - TString ConfigNode::GetNodeName() const - { - return m_strNodeName; - } - - int ConfigNode::GetOrder() const - { - return m_iOrder; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ConfigNode.h" + +namespace chcore +{ + namespace details + { + ConfigNode::ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue) : + m_oidObjectID(oidObjectID), + m_iOrder(m_setModifications, iOrder), + m_strNodeName(m_setModifications, strNodeName), + m_strValue(m_setModifications, strValue) + { + m_setModifications[eMod_Added] = true; + } + + ConfigNode::ConfigNode(const ConfigNode& rSrc) : + m_oidObjectID(rSrc.m_oidObjectID), + m_iOrder(m_setModifications, rSrc.m_iOrder), + m_strNodeName(m_setModifications, rSrc.m_strNodeName), + m_strValue(m_setModifications, rSrc.m_strValue), + m_setModifications(rSrc.m_setModifications) + { + } + + ConfigNode& ConfigNode::operator=(const ConfigNode& rSrc) + { + if (this != &rSrc) + { + m_oidObjectID = rSrc.m_oidObjectID; + m_iOrder = rSrc.m_iOrder; + m_strNodeName = rSrc.m_strNodeName; + m_strValue = rSrc.m_strValue; + m_setModifications = rSrc.m_setModifications; + } + + return *this; + } + + TString ConfigNode::GetNodeName() const + { + return m_strNodeName; + } + + int ConfigNode::GetOrder() const + { + return m_iOrder; + } + } +} Index: src/libchcore/ConfigNode.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ConfigNode.h (.../ConfigNode.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ConfigNode.h (.../ConfigNode.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,65 +1,65 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TCONFIGNODE_H__ -#define __TCONFIGNODE_H__ - -#include "TString.h" -#include -#include "TSharedModificationTracker.h" -#include "SerializerDataTypes.h" - -namespace chcore -{ - namespace details - { - class ConfigNode - { - public: - ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue); - ConfigNode(const ConfigNode& rSrc); - - ConfigNode& operator=(const ConfigNode& rSrc); - - TString GetNodeName() const; - int GetOrder() const; - - public: - enum EModifications - { - eMod_None = 0, - eMod_Added = 1, - eMod_NodeName, - eMod_Value, - eMod_Order, - - eMod_Last - }; - - typedef std::bitset Bitset; - mutable Bitset m_setModifications; - - object_id_t m_oidObjectID; - TSharedModificationTracker m_iOrder; - TSharedModificationTracker m_strNodeName; - TSharedModificationTracker m_strValue; - }; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TCONFIGNODE_H__ +#define __TCONFIGNODE_H__ + +#include "TString.h" +#include +#include "TSharedModificationTracker.h" +#include "SerializerDataTypes.h" + +namespace chcore +{ + namespace details + { + class ConfigNode + { + public: + ConfigNode(object_id_t oidObjectID, const TString& strNodeName, int iOrder, const TString& strValue); + ConfigNode(const ConfigNode& rSrc); + + ConfigNode& operator=(const ConfigNode& rSrc); + + TString GetNodeName() const; + int GetOrder() const; + + public: + enum EModifications + { + eMod_None = 0, + eMod_Added = 1, + eMod_NodeName, + eMod_Value, + eMod_Order, + + eMod_Last + }; + + typedef std::bitset Bitset; + mutable Bitset m_setModifications; + + object_id_t m_oidObjectID; + TSharedModificationTracker m_iOrder; + TSharedModificationTracker m_strNodeName; + TSharedModificationTracker m_strValue; + }; + } +} + +#endif Index: src/libchcore/ConfigNodeContainer.cpp =================================================================== diff -u -rfb2161f6abec049da07b234f15229d008412fc8f -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ConfigNodeContainer.cpp (.../ConfigNodeContainer.cpp) (revision fb2161f6abec049da07b234f15229d008412fc8f) +++ src/libchcore/ConfigNodeContainer.cpp (.../ConfigNodeContainer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,603 +1,603 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ConfigNodeContainer.h" -#include -#include -#include "TCoreException.h" -#include "ErrorCodes.h" -#include - -namespace chcore -{ - namespace details - { - /////////////////////////////////////////////////////////////////////// - ChangeValue::ChangeValue(const TString& strNewValue) : m_strNewValue(strNewValue) - { - } - - void ChangeValue::operator()(ConfigNode& rNode) - { - m_bWasModified = false; - if (rNode.m_strValue.Get() != m_strNewValue) - { - rNode.m_strValue.Modify() = m_strNewValue; - m_bWasModified = true; - } - } - - bool ChangeValue::WasModified() const - { - return m_bWasModified; - } - - /////////////////////////////////////////////////////////////////////// - ChangeOrderAndValue::ChangeOrderAndValue(const TString& tNewValue, int iOrder) : - m_strNewValue(tNewValue), - m_iOrder(iOrder) - { - } - - void ChangeOrderAndValue::operator()(ConfigNode& rNode) - { - m_bWasModified = false; - if (rNode.m_strValue.Get() != m_strNewValue || rNode.m_iOrder != m_iOrder) - { - rNode.m_strValue = m_strNewValue; - rNode.m_iOrder = m_iOrder; - - m_bWasModified = true; - } - } - - bool ChangeOrderAndValue::WasModified() const - { - return m_bWasModified; - } - - /////////////////////////////////////////////////////////////////////// - ConfigNodeContainer::ConfigNodeContainer() : - m_bDelayedEnabled(false), - m_oidLastObjectID(0) - { - } - - ConfigNodeContainer::ConfigNodeContainer(const ConfigNodeContainer& rSrc) - { - boost::shared_lock lock(rSrc.m_lock); - m_mic = rSrc.m_mic; - m_strFilePath = rSrc.m_strFilePath; - m_setDelayedNotifications.Clear(); - m_bDelayedEnabled = false; - m_oidLastObjectID = rSrc.m_oidLastObjectID; - } - - ConfigNodeContainer& ConfigNodeContainer::operator=(const ConfigNodeContainer& rSrc) - { - if (this != &rSrc) - { - boost::unique_lock lock2(m_lock); - boost::shared_lock lock(rSrc.m_lock); - - m_mic = rSrc.m_mic; - m_strFilePath = rSrc.m_strFilePath; - m_bDelayedEnabled = false; - m_oidLastObjectID = rSrc.m_oidLastObjectID; - - m_setDelayedNotifications.Clear(); - } - - return *this; - } - - TStringArray ConfigNodeContainer::GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const - { - TStringArray tArray; - - boost::shared_lock lock(m_lock); - - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); - - if (pairFnd.first == m_mic.end()) - return rDefaultValue; - - while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) - { - tArray.Add((*pairFnd.first).m_strValue); - ++pairFnd.first; - } - - return tArray; - } - - bool ConfigNodeContainer::GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const - { - boost::shared_lock lock(m_lock); - - rValue.Clear(); - - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); - - if (pairFnd.first == m_mic.end()) - return false; - - while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) - { - rValue.Add((*pairFnd.first).m_strValue); - ++pairFnd.first; - } - - return true; - } - - bool ConfigNodeContainer::SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue) - { - boost::unique_lock lock(m_lock); - - std::pair pairFnd - = m_mic.equal_range(boost::make_tuple(pszPropName)); - - if (pairFnd.first == m_mic.end()) - { - // insert new items - for (size_t stIndex = 0; stIndex < rValue.GetCount(); ++stIndex) - { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); - } - - return false; - } - else - { - // insert/modify/delete items (diff mode) - size_t stIndex = 0; - while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) - { - if (stIndex < rValue.GetCount()) - { - // update existing item - ChangeOrderAndValue tChange(rValue.GetAt(stIndex), boost::numeric_cast(stIndex)); - m_mic.modify(pairFnd.first, std::ref(tChange)); - - ++pairFnd.first; - } - else - { - // delete this item - m_setRemovedObjects.Add(pairFnd.first->m_oidObjectID); - pairFnd.first = m_mic.erase(pairFnd.first); - } - - ++stIndex; - } - - while (stIndex < rValue.GetCount()) - { - // add items not added before (with new oids) - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); - ++stIndex; - } - - return true; - } - } - - namespace - { - struct PredIsPrefixedWith - { - public: - PredIsPrefixedWith(PCTSTR pszPrefix, TRemovedObjects& rRemovedObjects) : m_strPrefix(pszPrefix), m_rRemovedObjects(rRemovedObjects) {} - PredIsPrefixedWith(const PredIsPrefixedWith& rSrc) : m_strPrefix(rSrc.m_strPrefix), m_rRemovedObjects(rSrc.m_rRemovedObjects) {} - PredIsPrefixedWith() = delete; - - PredIsPrefixedWith& operator=(const PredIsPrefixedWith&) = delete; - - bool operator()(const ConfigNode& rNode) const - { - if (rNode.m_strNodeName.Get().StartsWith(m_strPrefix.c_str())) - { - m_rRemovedObjects.Add(rNode.m_oidObjectID); - return true; - } - return false; - } - - TString m_strPrefix; - TRemovedObjects& m_rRemovedObjects; - }; - } - - void ConfigNodeContainer::DeleteNode(PCTSTR pszPropName) - { - boost::unique_lock lock(m_lock); - - PredIsPrefixedWith pred(pszPropName, m_setRemovedObjects); - - bool bWasFoundBefore = false; - ConfigNodeContainer::NodeContainer::iterator iterCurrent = m_mic.begin(); - while (iterCurrent != m_mic.end()) - { - // NOTE: PredIsPrefixedWith registers the object IDs as deleted in m_setRemovedObjects (for change management purposes) - if (pred(*iterCurrent)) - { - iterCurrent = m_mic.erase(iterCurrent); - bWasFoundBefore = true; - } - else if (bWasFoundBefore) - break; // as the elements are sorted, when we matched something earlier and now we don't - it means that there are no more matching elements - else - ++iterCurrent; - } - } - - bool ConfigNodeContainer::ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const - { - bool bFound = false; - TString strReplace(pszNode); - strReplace += _T("."); - - boost::unique_lock dst_lock(tNewContainer.m_lock); - tNewContainer.m_mic.clear(); - - boost::shared_lock lock(m_lock); - - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) - { - bFound = true; - - TString strName = iter->m_strNodeName.Get(); - strName.MidSelf(strReplace.GetLength()); - - tNewContainer.m_mic.insert(ConfigNode(++tNewContainer.m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); - } - } - - return bFound; - } - - bool ConfigNodeContainer::ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const - { - bool bFound = false; - TString strReplace(pszNode); - strReplace += _T("["); - - boost::shared_lock lock(m_lock); - - size_t stLastIndex = std::numeric_limits::max(); - ConfigNodeContainer* pCurrentContainer = nullptr; - - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) - { - bFound = true; - - TString strName = iter->m_strNodeName.Get(); - strName.MidSelf(strReplace.GetLength()); - size_t stPos = strName.Find(_T("]")); - if (stPos == std::numeric_limits::max()) - throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); - if (strName.GetAt(stPos + 1) != _T('.')) - throw TCoreException(eErr_InvalidData, L". character not found", LOCATION); - - size_t stNodeIndex = boost::lexical_cast(strName.Left(stPos)); - if (stNodeIndex != stLastIndex) - { - tNewContainers.push_back(ConfigNodeContainer()); - pCurrentContainer = &tNewContainers.back(); - - stLastIndex = stNodeIndex; - } - - strName.Delete(0, stPos + 2); // skip "]." at the beginning - if (!pCurrentContainer) - throw TCoreException(eErr_InvalidPointer, L"pCurrentContainer", LOCATION); - - pCurrentContainer->m_mic.insert(ConfigNode(++pCurrentContainer->m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); - } - } - - return bFound; - } - - void ConfigNodeContainer::ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) - { - boost::shared_lock src_lock(tContainer.m_lock); - boost::unique_lock lock(m_lock); - - // search for nodes in this container that starts with pszNode - TString strSearch(pszNode); - strSearch += _T("."); - - typedef std::pair PairInfo; - std::set setExistingNames; - - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - if (iter->m_strNodeName.Get().StartsWith(strSearch.c_str())) - { - setExistingNames.insert(std::make_pair(iter->m_strNodeName.Get(), iter->m_iOrder.Get())); - } - } - - NodeContainer::const_iterator iter = tContainer.m_mic.begin(); - for (; iter != tContainer.m_mic.end(); ++iter) - { - TString strNodeName = pszNode; - strNodeName += _T(".") + iter->m_strNodeName; - - std::set::iterator iterExisting = setExistingNames.find(std::make_pair(strNodeName, iter->m_iOrder.Get())); - if (iterExisting != setExistingNames.end()) - { - // node already exists - modify instead of delete+add - m_mic.modify(iter, ChangeValue(iter->m_strValue)); - - setExistingNames.erase(iterExisting); - } - else - { - // node does not exist - need to add new one - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); - } - - // remove all nodes with names from setExisting - for(const PairInfo& pairNode : setExistingNames) - { - NodeContainer::iterator iterToRemove = m_mic.find(boost::make_tuple(pairNode.first, pairNode.second)); - if (iterToRemove != m_mic.end()) - m_setRemovedObjects.Add(iterToRemove->m_oidObjectID); - - m_mic.erase(iterToRemove); - } - } - } - - void ConfigNodeContainer::AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) - { - boost::shared_lock src_lock(tContainer.m_lock); - boost::unique_lock lock(m_lock); - - // determine the current (max) number associated with the node name - TString strSearch(pszNode); - strSearch += _T("["); - - size_t stMaxNodeNumber = 0; - - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - TString strCurrentNode = iter->m_strNodeName.Get(); - if (strCurrentNode.StartsWith(strSearch.c_str())) - { - strCurrentNode.MidSelf(strSearch.GetLength()); - size_t stPos = strCurrentNode.Find(_T("]")); - if (stPos == std::numeric_limits::max()) - throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); - - size_t stNumber = boost::lexical_cast(strCurrentNode.Left(stPos).c_str()); - stMaxNodeNumber = std::max(stMaxNodeNumber, stNumber + 1); - } - } - - TString strNodePrefix = pszNode; - strNodePrefix += TString(_T("[")) + boost::lexical_cast(stMaxNodeNumber).c_str() + _T("]."); - - NodeContainer::const_iterator iter = tContainer.m_mic.begin(); - for (; iter != tContainer.m_mic.end(); ++iter) - { - TString strNodeName = strNodePrefix + iter->m_strNodeName; - - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); - } - } - - void ConfigNodeContainer::ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree) - { - if (rTree.empty()) - return; - - // append separator for non-empty nodes - if (!strCurrentPath.IsEmpty()) - strCurrentPath += _T("."); - - TString strNewPath; - - // analyze subnodes (has only leaf-node(s), multiple non-leaf subnodes with same name, multiple subnodes with different names) - std::set setNodeNames; - bool bAllLeafNodes = true; - size_t stChildCount = 0; - for(const boost::property_tree::wiptree::value_type& rNode : rTree) - { - setNodeNames.insert(rNode.first.c_str()); - - if (!rNode.second.empty()) - bAllLeafNodes = false; - - ++stChildCount; - } - - // sanity check (either unique names or empty or an array with single name - size_t stNodeNamesCount = setNodeNames.size(); - if (stChildCount != stNodeNamesCount && stNodeNamesCount != 1) - throw TCoreException(eErr_InvalidData, L"Tree sanity check failed", LOCATION); - - enum EMode { eMode_LeafStringArrayEntries, eMode_LeafOrContainer, eMode_ContainerSplit }; - EMode eMode = eMode_LeafOrContainer; - - if (stNodeNamesCount == 1 && stChildCount > 1) - { - if (bAllLeafNodes) - eMode = eMode_LeafStringArrayEntries; - else - eMode = eMode_ContainerSplit; - } - - int iIndex = 0; - for(const boost::property_tree::wiptree::value_type& rNode : rTree) - { - switch (eMode) - { - case eMode_LeafStringArrayEntries: - { - strNewPath = strCurrentPath + rNode.first.c_str(); - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, iIndex++, rNode.second.get_value().c_str())); - break; - } - case eMode_LeafOrContainer: - { - strNewPath = strCurrentPath + rNode.first.c_str(); - if (rNode.second.empty()) - { - // get leaf info - m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, 0, rNode.second.get_value().c_str())); - } - else - { - // traverse through the container - ImportNode(strNewPath, rNode.second); - } - - break; - } - case eMode_ContainerSplit: - { - strNewPath = strCurrentPath + rNode.first.c_str() + _T("[") + boost::lexical_cast(iIndex++).c_str() + _T("]"); - ImportNode(strNewPath, rNode.second); - break; - } - } - } - } - - void ConfigNodeContainer::ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&) - { - // boost::unique_lock lock(m_lock); // do not lock - locking is done outside - m_mic.clear(); - - // iterate through property tree - ImportNode(_T(""), rTree); -#ifdef _DEBUG - Dump(); -#endif - } - - void ConfigNodeContainer::ExportToPropertyTree(boost::property_tree::wiptree& rTree) const - { - rTree.clear(); - - size_t stLastBracketID = std::numeric_limits::max(); - TString strGroupNode; - - boost::property_tree::wiptree treeSubnodes; - - boost::shared_lock lock(m_lock); - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - const TString& rNodeName = iter->m_strNodeName.Get(); - - TString strNodeName = rNodeName; - - size_t stBracketPos = strNodeName.Find(_T("[")); - if (stBracketPos != TString::npos) - { - // there is a bracket in the node name - this element is a part of a hierarchy of similar nodes - size_t stSecondBracketPos = strNodeName.Find(_T("]"), stBracketPos + 1); - if (stSecondBracketPos == TString::npos) - throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); - - strGroupNode = strNodeName.Left(stBracketPos); - TString strSubnodeName = strNodeName.Mid(stSecondBracketPos + 1); - wchar_t chDot = 0; - if (!strSubnodeName.GetAt(0, chDot) || chDot != L'.') - throw TCoreException(eErr_InvalidData, L". character not found", LOCATION); - strSubnodeName.Delete(0, 1); - - size_t stBracketID = boost::lexical_cast(strNodeName.Mid(stBracketPos + 1, stSecondBracketPos - stBracketPos - 1)); - if (stBracketID != stLastBracketID) - { - // new ID - add new property tree node - if (!treeSubnodes.empty()) - { - rTree.add_child(strGroupNode.c_str(), treeSubnodes); - treeSubnodes.clear(); - } - } - - // same ID - add new element to existing property tree node - treeSubnodes.put(strSubnodeName.c_str(), iter->m_strValue.Get()); - stLastBracketID = stBracketID; - } - else - { - // add the subnodes from previous bracket-based entries - if (!treeSubnodes.empty()) - { - rTree.add_child(strGroupNode.c_str(), treeSubnodes); - treeSubnodes.clear(); - } - - // no bracket in the node name - this is just a standard entry - rTree.add(strNodeName.c_str(), iter->m_strValue.Get()); - } - } - - // add the last subnode if not empty - if (!treeSubnodes.empty()) - rTree.add_child(strGroupNode.c_str(), treeSubnodes); - } - -#ifdef _DEBUG - void ConfigNodeContainer::Dump() - { - const size_t stBufferSize = 1024; - TCHAR szBuffer[stBufferSize]; - - for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) - { - unsigned long long ullID = iter->m_oidObjectID; - int iNodeNameModified = iter->m_strNodeName.IsModified() ? 1 : 0; - int iNodeNameModified2 = iter->m_setModifications[ConfigNode::eMod_NodeName]; - int iOrderModified = iter->m_iOrder.IsModified() ? 1 : 0; - int iOrderModified2 = iter->m_setModifications[ConfigNode::eMod_Order]; - int iValueModified = iter->m_strValue.IsModified() ? 1 : 0; - int iValueModified2 = iter->m_setModifications[ConfigNode::eMod_Value]; - bool bAdded = iter->m_setModifications[ConfigNode::eMod_Added]; - - _sntprintf_s(szBuffer, stBufferSize, _TRUNCATE, _T("Node (oid %I64u): %s(%d/%d).%d(%d/%d) = %s(%d/%d)%s\n"), ullID, - iter->m_strNodeName.Get().c_str(), iNodeNameModified, iNodeNameModified2, - iter->m_iOrder.Get(), iOrderModified, iOrderModified2, - iter->m_strValue.Get().c_str(), iValueModified, iValueModified2, - bAdded ? L" [added]" : L""); - OutputDebugString(szBuffer); - } - } -#endif - - void ConfigNodeContainer::AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue) - { - std::pair pairInsert = m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, iIndex, strValue)); - pairInsert.first->m_setModifications.reset(); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ConfigNodeContainer.h" +#include +#include +#include "TCoreException.h" +#include "ErrorCodes.h" +#include + +namespace chcore +{ + namespace details + { + /////////////////////////////////////////////////////////////////////// + ChangeValue::ChangeValue(const TString& strNewValue) : m_strNewValue(strNewValue) + { + } + + void ChangeValue::operator()(ConfigNode& rNode) + { + m_bWasModified = false; + if (rNode.m_strValue.Get() != m_strNewValue) + { + rNode.m_strValue.Modify() = m_strNewValue; + m_bWasModified = true; + } + } + + bool ChangeValue::WasModified() const + { + return m_bWasModified; + } + + /////////////////////////////////////////////////////////////////////// + ChangeOrderAndValue::ChangeOrderAndValue(const TString& tNewValue, int iOrder) : + m_strNewValue(tNewValue), + m_iOrder(iOrder) + { + } + + void ChangeOrderAndValue::operator()(ConfigNode& rNode) + { + m_bWasModified = false; + if (rNode.m_strValue.Get() != m_strNewValue || rNode.m_iOrder != m_iOrder) + { + rNode.m_strValue = m_strNewValue; + rNode.m_iOrder = m_iOrder; + + m_bWasModified = true; + } + } + + bool ChangeOrderAndValue::WasModified() const + { + return m_bWasModified; + } + + /////////////////////////////////////////////////////////////////////// + ConfigNodeContainer::ConfigNodeContainer() : + m_bDelayedEnabled(false), + m_oidLastObjectID(0) + { + } + + ConfigNodeContainer::ConfigNodeContainer(const ConfigNodeContainer& rSrc) + { + boost::shared_lock lock(rSrc.m_lock); + m_mic = rSrc.m_mic; + m_strFilePath = rSrc.m_strFilePath; + m_setDelayedNotifications.Clear(); + m_bDelayedEnabled = false; + m_oidLastObjectID = rSrc.m_oidLastObjectID; + } + + ConfigNodeContainer& ConfigNodeContainer::operator=(const ConfigNodeContainer& rSrc) + { + if (this != &rSrc) + { + boost::unique_lock lock2(m_lock); + boost::shared_lock lock(rSrc.m_lock); + + m_mic = rSrc.m_mic; + m_strFilePath = rSrc.m_strFilePath; + m_bDelayedEnabled = false; + m_oidLastObjectID = rSrc.m_oidLastObjectID; + + m_setDelayedNotifications.Clear(); + } + + return *this; + } + + TStringArray ConfigNodeContainer::GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const + { + TStringArray tArray; + + boost::shared_lock lock(m_lock); + + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); + + if (pairFnd.first == m_mic.end()) + return rDefaultValue; + + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + { + tArray.Add((*pairFnd.first).m_strValue); + ++pairFnd.first; + } + + return tArray; + } + + bool ConfigNodeContainer::GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const + { + boost::shared_lock lock(m_lock); + + rValue.Clear(); + + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); + + if (pairFnd.first == m_mic.end()) + return false; + + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + { + rValue.Add((*pairFnd.first).m_strValue); + ++pairFnd.first; + } + + return true; + } + + bool ConfigNodeContainer::SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue) + { + boost::unique_lock lock(m_lock); + + std::pair pairFnd + = m_mic.equal_range(boost::make_tuple(pszPropName)); + + if (pairFnd.first == m_mic.end()) + { + // insert new items + for (size_t stIndex = 0; stIndex < rValue.GetCount(); ++stIndex) + { + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); + } + + return false; + } + else + { + // insert/modify/delete items (diff mode) + size_t stIndex = 0; + while (pairFnd.first != m_mic.end() && pairFnd.first != pairFnd.second) + { + if (stIndex < rValue.GetCount()) + { + // update existing item + ChangeOrderAndValue tChange(rValue.GetAt(stIndex), boost::numeric_cast(stIndex)); + m_mic.modify(pairFnd.first, std::ref(tChange)); + + ++pairFnd.first; + } + else + { + // delete this item + m_setRemovedObjects.Add(pairFnd.first->m_oidObjectID); + pairFnd.first = m_mic.erase(pairFnd.first); + } + + ++stIndex; + } + + while (stIndex < rValue.GetCount()) + { + // add items not added before (with new oids) + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, boost::numeric_cast(stIndex), rValue.GetAt(stIndex))); + ++stIndex; + } + + return true; + } + } + + namespace + { + struct PredIsPrefixedWith + { + public: + PredIsPrefixedWith(PCTSTR pszPrefix, TRemovedObjects& rRemovedObjects) : m_strPrefix(pszPrefix), m_rRemovedObjects(rRemovedObjects) {} + PredIsPrefixedWith(const PredIsPrefixedWith& rSrc) : m_strPrefix(rSrc.m_strPrefix), m_rRemovedObjects(rSrc.m_rRemovedObjects) {} + PredIsPrefixedWith() = delete; + + PredIsPrefixedWith& operator=(const PredIsPrefixedWith&) = delete; + + bool operator()(const ConfigNode& rNode) const + { + if (rNode.m_strNodeName.Get().StartsWith(m_strPrefix.c_str())) + { + m_rRemovedObjects.Add(rNode.m_oidObjectID); + return true; + } + return false; + } + + TString m_strPrefix; + TRemovedObjects& m_rRemovedObjects; + }; + } + + void ConfigNodeContainer::DeleteNode(PCTSTR pszPropName) + { + boost::unique_lock lock(m_lock); + + PredIsPrefixedWith pred(pszPropName, m_setRemovedObjects); + + bool bWasFoundBefore = false; + ConfigNodeContainer::NodeContainer::iterator iterCurrent = m_mic.begin(); + while (iterCurrent != m_mic.end()) + { + // NOTE: PredIsPrefixedWith registers the object IDs as deleted in m_setRemovedObjects (for change management purposes) + if (pred(*iterCurrent)) + { + iterCurrent = m_mic.erase(iterCurrent); + bWasFoundBefore = true; + } + else if (bWasFoundBefore) + break; // as the elements are sorted, when we matched something earlier and now we don't - it means that there are no more matching elements + else + ++iterCurrent; + } + } + + bool ConfigNodeContainer::ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const + { + bool bFound = false; + TString strReplace(pszNode); + strReplace += _T("."); + + boost::unique_lock dst_lock(tNewContainer.m_lock); + tNewContainer.m_mic.clear(); + + boost::shared_lock lock(m_lock); + + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + { + bFound = true; + + TString strName = iter->m_strNodeName.Get(); + strName.MidSelf(strReplace.GetLength()); + + tNewContainer.m_mic.insert(ConfigNode(++tNewContainer.m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + } + } + + return bFound; + } + + bool ConfigNodeContainer::ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const + { + bool bFound = false; + TString strReplace(pszNode); + strReplace += _T("["); + + boost::shared_lock lock(m_lock); + + size_t stLastIndex = std::numeric_limits::max(); + ConfigNodeContainer* pCurrentContainer = nullptr; + + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + if (iter->m_strNodeName.Get().StartsWith(strReplace.c_str())) + { + bFound = true; + + TString strName = iter->m_strNodeName.Get(); + strName.MidSelf(strReplace.GetLength()); + size_t stPos = strName.Find(_T("]")); + if (stPos == std::numeric_limits::max()) + throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); + if (strName.GetAt(stPos + 1) != _T('.')) + throw TCoreException(eErr_InvalidData, L". character not found", LOCATION); + + size_t stNodeIndex = boost::lexical_cast(strName.Left(stPos)); + if (stNodeIndex != stLastIndex) + { + tNewContainers.push_back(ConfigNodeContainer()); + pCurrentContainer = &tNewContainers.back(); + + stLastIndex = stNodeIndex; + } + + strName.Delete(0, stPos + 2); // skip "]." at the beginning + if (!pCurrentContainer) + throw TCoreException(eErr_InvalidPointer, L"pCurrentContainer", LOCATION); + + pCurrentContainer->m_mic.insert(ConfigNode(++pCurrentContainer->m_oidLastObjectID, strName, iter->GetOrder(), iter->m_strValue)); + } + } + + return bFound; + } + + void ConfigNodeContainer::ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) + { + boost::shared_lock src_lock(tContainer.m_lock); + boost::unique_lock lock(m_lock); + + // search for nodes in this container that starts with pszNode + TString strSearch(pszNode); + strSearch += _T("."); + + typedef std::pair PairInfo; + std::set setExistingNames; + + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + if (iter->m_strNodeName.Get().StartsWith(strSearch.c_str())) + { + setExistingNames.insert(std::make_pair(iter->m_strNodeName.Get(), iter->m_iOrder.Get())); + } + } + + NodeContainer::const_iterator iter = tContainer.m_mic.begin(); + for (; iter != tContainer.m_mic.end(); ++iter) + { + TString strNodeName = pszNode; + strNodeName += _T(".") + iter->m_strNodeName; + + std::set::iterator iterExisting = setExistingNames.find(std::make_pair(strNodeName, iter->m_iOrder.Get())); + if (iterExisting != setExistingNames.end()) + { + // node already exists - modify instead of delete+add + m_mic.modify(iter, ChangeValue(iter->m_strValue)); + + setExistingNames.erase(iterExisting); + } + else + { + // node does not exist - need to add new one + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); + } + + // remove all nodes with names from setExisting + for(const PairInfo& pairNode : setExistingNames) + { + NodeContainer::iterator iterToRemove = m_mic.find(boost::make_tuple(pairNode.first, pairNode.second)); + if (iterToRemove != m_mic.end()) + m_setRemovedObjects.Add(iterToRemove->m_oidObjectID); + + m_mic.erase(iterToRemove); + } + } + } + + void ConfigNodeContainer::AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer) + { + boost::shared_lock src_lock(tContainer.m_lock); + boost::unique_lock lock(m_lock); + + // determine the current (max) number associated with the node name + TString strSearch(pszNode); + strSearch += _T("["); + + size_t stMaxNodeNumber = 0; + + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + TString strCurrentNode = iter->m_strNodeName.Get(); + if (strCurrentNode.StartsWith(strSearch.c_str())) + { + strCurrentNode.MidSelf(strSearch.GetLength()); + size_t stPos = strCurrentNode.Find(_T("]")); + if (stPos == std::numeric_limits::max()) + throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); + + size_t stNumber = boost::lexical_cast(strCurrentNode.Left(stPos).c_str()); + stMaxNodeNumber = std::max(stMaxNodeNumber, stNumber + 1); + } + } + + TString strNodePrefix = pszNode; + strNodePrefix += TString(_T("[")) + boost::lexical_cast(stMaxNodeNumber).c_str() + _T("]."); + + NodeContainer::const_iterator iter = tContainer.m_mic.begin(); + for (; iter != tContainer.m_mic.end(); ++iter) + { + TString strNodeName = strNodePrefix + iter->m_strNodeName; + + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNodeName, iter->GetOrder(), iter->m_strValue)); + } + } + + void ConfigNodeContainer::ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree) + { + if (rTree.empty()) + return; + + // append separator for non-empty nodes + if (!strCurrentPath.IsEmpty()) + strCurrentPath += _T("."); + + TString strNewPath; + + // analyze subnodes (has only leaf-node(s), multiple non-leaf subnodes with same name, multiple subnodes with different names) + std::set setNodeNames; + bool bAllLeafNodes = true; + size_t stChildCount = 0; + for(const boost::property_tree::wiptree::value_type& rNode : rTree) + { + setNodeNames.insert(rNode.first.c_str()); + + if (!rNode.second.empty()) + bAllLeafNodes = false; + + ++stChildCount; + } + + // sanity check (either unique names or empty or an array with single name + size_t stNodeNamesCount = setNodeNames.size(); + if (stChildCount != stNodeNamesCount && stNodeNamesCount != 1) + throw TCoreException(eErr_InvalidData, L"Tree sanity check failed", LOCATION); + + enum EMode { eMode_LeafStringArrayEntries, eMode_LeafOrContainer, eMode_ContainerSplit }; + EMode eMode = eMode_LeafOrContainer; + + if (stNodeNamesCount == 1 && stChildCount > 1) + { + if (bAllLeafNodes) + eMode = eMode_LeafStringArrayEntries; + else + eMode = eMode_ContainerSplit; + } + + int iIndex = 0; + for(const boost::property_tree::wiptree::value_type& rNode : rTree) + { + switch (eMode) + { + case eMode_LeafStringArrayEntries: + { + strNewPath = strCurrentPath + rNode.first.c_str(); + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, iIndex++, rNode.second.get_value().c_str())); + break; + } + case eMode_LeafOrContainer: + { + strNewPath = strCurrentPath + rNode.first.c_str(); + if (rNode.second.empty()) + { + // get leaf info + m_mic.insert(ConfigNode(++m_oidLastObjectID, strNewPath, 0, rNode.second.get_value().c_str())); + } + else + { + // traverse through the container + ImportNode(strNewPath, rNode.second); + } + + break; + } + case eMode_ContainerSplit: + { + strNewPath = strCurrentPath + rNode.first.c_str() + _T("[") + boost::lexical_cast(iIndex++).c_str() + _T("]"); + ImportNode(strNewPath, rNode.second); + break; + } + } + } + } + + void ConfigNodeContainer::ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&) + { + // boost::unique_lock lock(m_lock); // do not lock - locking is done outside + m_mic.clear(); + + // iterate through property tree + ImportNode(_T(""), rTree); +#ifdef _DEBUG + Dump(); +#endif + } + + void ConfigNodeContainer::ExportToPropertyTree(boost::property_tree::wiptree& rTree) const + { + rTree.clear(); + + size_t stLastBracketID = std::numeric_limits::max(); + TString strGroupNode; + + boost::property_tree::wiptree treeSubnodes; + + boost::shared_lock lock(m_lock); + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + const TString& rNodeName = iter->m_strNodeName.Get(); + + TString strNodeName = rNodeName; + + size_t stBracketPos = strNodeName.Find(_T("[")); + if (stBracketPos != TString::npos) + { + // there is a bracket in the node name - this element is a part of a hierarchy of similar nodes + size_t stSecondBracketPos = strNodeName.Find(_T("]"), stBracketPos + 1); + if (stSecondBracketPos == TString::npos) + throw TCoreException(eErr_InvalidData, L"] character not found", LOCATION); + + strGroupNode = strNodeName.Left(stBracketPos); + TString strSubnodeName = strNodeName.Mid(stSecondBracketPos + 1); + wchar_t chDot = 0; + if (!strSubnodeName.GetAt(0, chDot) || chDot != L'.') + throw TCoreException(eErr_InvalidData, L". character not found", LOCATION); + strSubnodeName.Delete(0, 1); + + size_t stBracketID = boost::lexical_cast(strNodeName.Mid(stBracketPos + 1, stSecondBracketPos - stBracketPos - 1)); + if (stBracketID != stLastBracketID) + { + // new ID - add new property tree node + if (!treeSubnodes.empty()) + { + rTree.add_child(strGroupNode.c_str(), treeSubnodes); + treeSubnodes.clear(); + } + } + + // same ID - add new element to existing property tree node + treeSubnodes.put(strSubnodeName.c_str(), iter->m_strValue.Get()); + stLastBracketID = stBracketID; + } + else + { + // add the subnodes from previous bracket-based entries + if (!treeSubnodes.empty()) + { + rTree.add_child(strGroupNode.c_str(), treeSubnodes); + treeSubnodes.clear(); + } + + // no bracket in the node name - this is just a standard entry + rTree.add(strNodeName.c_str(), iter->m_strValue.Get()); + } + } + + // add the last subnode if not empty + if (!treeSubnodes.empty()) + rTree.add_child(strGroupNode.c_str(), treeSubnodes); + } + +#ifdef _DEBUG + void ConfigNodeContainer::Dump() + { + const size_t stBufferSize = 1024; + TCHAR szBuffer[stBufferSize]; + + for (NodeContainer::const_iterator iter = m_mic.begin(); iter != m_mic.end(); ++iter) + { + unsigned long long ullID = iter->m_oidObjectID; + int iNodeNameModified = iter->m_strNodeName.IsModified() ? 1 : 0; + int iNodeNameModified2 = iter->m_setModifications[ConfigNode::eMod_NodeName]; + int iOrderModified = iter->m_iOrder.IsModified() ? 1 : 0; + int iOrderModified2 = iter->m_setModifications[ConfigNode::eMod_Order]; + int iValueModified = iter->m_strValue.IsModified() ? 1 : 0; + int iValueModified2 = iter->m_setModifications[ConfigNode::eMod_Value]; + bool bAdded = iter->m_setModifications[ConfigNode::eMod_Added]; + + _sntprintf_s(szBuffer, stBufferSize, _TRUNCATE, _T("Node (oid %I64u): %s(%d/%d).%d(%d/%d) = %s(%d/%d)%s\n"), ullID, + iter->m_strNodeName.Get().c_str(), iNodeNameModified, iNodeNameModified2, + iter->m_iOrder.Get(), iOrderModified, iOrderModified2, + iter->m_strValue.Get().c_str(), iValueModified, iValueModified2, + bAdded ? L" [added]" : L""); + OutputDebugString(szBuffer); + } + } +#endif + + void ConfigNodeContainer::AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue) + { + std::pair pairInsert = m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, iIndex, strValue)); + pairInsert.first->m_setModifications.reset(); + } + } +} Index: src/libchcore/ConfigNodeContainer.h =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ConfigNodeContainer.h (.../ConfigNodeContainer.h) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/ConfigNodeContainer.h (.../ConfigNodeContainer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,269 +1,269 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __CONFIGNODECONTAINER_H__ -#define __CONFIGNODECONTAINER_H__ - -#include "TSharedModificationTracker.h" -#include "ConfigNode.h" - -#include -#include -#include -#include - -#pragma warning(push) -#pragma warning(disable: 4100 4702 4512) - #include -#pragma warning(pop) -#include "TStringSet.h" -#include "TStringArray.h" -#include "TRemovedObjects.h" -#include -#include -#include - -namespace chcore -{ - namespace details - { - struct ChangeValue - { - explicit ChangeValue(const TString& strNewValue); - - void operator()(ConfigNode& rNode); - - bool WasModified() const; - - private: - TString m_strNewValue; - bool m_bWasModified = false; - }; - - struct ChangeOrderAndValue - { - ChangeOrderAndValue(const TString& tNewValue, int iOrder); - - void operator()(ConfigNode& rNode); - - bool WasModified() const; - - private: - TString m_strNewValue; - int m_iOrder = 0; - bool m_bWasModified = false; - }; - - struct ConfigNodeContainer - { - public: - ConfigNodeContainer(); - ConfigNodeContainer(const ConfigNodeContainer& rSrc); - - ConfigNodeContainer& operator=(const ConfigNodeContainer& rSrc); - - void AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue); - - // get/set single values - template - T GetValue(PCTSTR pszPropName, const T& rDefaultValue) const - { - boost::shared_lock lock(m_lock); - T tResult = rDefaultValue; - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - tResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - - return tResult; - } - - template<> - TString GetValue(PCTSTR pszPropName, const TString& rDefaultValue) const - { - boost::shared_lock lock(m_lock); - TString tResult = rDefaultValue; - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - tResult = (*iterFnd).m_strValue; - - return tResult; - } - - template<> - bool GetValue(PCTSTR pszPropName, const bool& bDefaultValue) const - { - boost::shared_lock lock(m_lock); - bool bResult = bDefaultValue; - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("false")) == 0) - bResult = false; - else if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("true")) == 0) - bResult = true; - else - bResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - } - - return bResult; - } - - template - bool GetValueNoDefault(PCTSTR pszPropName, T& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - rValue = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); - return true; - } - - return false; - } - - template<> - bool GetValueNoDefault(PCTSTR pszPropName, TString& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - rValue = (*iterFnd).m_strValue; - return true; - } - - return false; - } - - template<> - bool GetValueNoDefault(PCTSTR pszPropName, bool& rValue) const - { - boost::shared_lock lock(m_lock); - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - const TString& strValue = (*iterFnd).m_strValue.Get(); - if (strValue.CompareNoCase(_T("false")) == 0) - rValue = false; - else if (strValue.CompareNoCase(_T("true")) == 0) - rValue = true; - else - rValue = boost::lexical_cast(strValue.c_str()); - return true; - } - - return false; - } - - template - bool SetValue(PCTSTR pszPropName, const T& rValue) - { - boost::unique_lock lock(m_lock); - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - ChangeValue tChange(boost::lexical_cast(rValue).c_str()); - m_mic.modify(iterFnd, std::ref(tChange)); - return tChange.WasModified(); - } - else - { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, boost::lexical_cast(rValue).c_str())); - return true; - } - } - - template<> - bool SetValue(PCTSTR pszPropName, const bool& bValue) - { - boost::unique_lock lock(m_lock); - - ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); - if (iterFnd != m_mic.end()) - { - ChangeValue tChange(boost::lexical_cast(bValue ? _T("true") : _T("false")).c_str()); - m_mic.modify(iterFnd, std::ref(tChange)); - return tChange.WasModified(); - } - else - { - m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, bValue ? _T("true") : _T("false"))); - return true; - } - } - - // vector-based values - TStringArray GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const; - bool GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const; - bool SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue); - - // deletion - void DeleteNode(PCTSTR pszPropName); - - // extracting nodes - bool ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const; - bool ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const; - - void ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // replaces specified node with data from tContainer - void AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // adds specified config as a newly numbered node in this container - - void ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&); - void ExportToPropertyTree(boost::property_tree::wiptree& rTree) const; - -#ifdef _DEBUG - // debugging - void Dump(); -#endif - - private: - void ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree); - - public: - typedef boost::multi_index_container, - boost::multi_index::const_mem_fun - > - > - > - > NodeContainer; - - NodeContainer m_mic; - - TString m_strFilePath; - - boost::signals2::signal m_notifier; - TStringSet m_setDelayedNotifications; - bool m_bDelayedEnabled; - object_id_t m_oidLastObjectID; - - TRemovedObjects m_setRemovedObjects; - - mutable boost::shared_mutex m_lock; - }; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __CONFIGNODECONTAINER_H__ +#define __CONFIGNODECONTAINER_H__ + +#include "TSharedModificationTracker.h" +#include "ConfigNode.h" + +#include +#include +#include +#include + +#pragma warning(push) +#pragma warning(disable: 4100 4702 4512) + #include +#pragma warning(pop) +#include "TStringSet.h" +#include "TStringArray.h" +#include "TRemovedObjects.h" +#include +#include +#include + +namespace chcore +{ + namespace details + { + struct ChangeValue + { + explicit ChangeValue(const TString& strNewValue); + + void operator()(ConfigNode& rNode); + + bool WasModified() const; + + private: + TString m_strNewValue; + bool m_bWasModified = false; + }; + + struct ChangeOrderAndValue + { + ChangeOrderAndValue(const TString& tNewValue, int iOrder); + + void operator()(ConfigNode& rNode); + + bool WasModified() const; + + private: + TString m_strNewValue; + int m_iOrder = 0; + bool m_bWasModified = false; + }; + + struct ConfigNodeContainer + { + public: + ConfigNodeContainer(); + ConfigNodeContainer(const ConfigNodeContainer& rSrc); + + ConfigNodeContainer& operator=(const ConfigNodeContainer& rSrc); + + void AddEntry(PCTSTR pszPropName, int iIndex, const TString& strValue); + + // get/set single values + template + T GetValue(PCTSTR pszPropName, const T& rDefaultValue) const + { + boost::shared_lock lock(m_lock); + T tResult = rDefaultValue; + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + tResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + + return tResult; + } + + template<> + TString GetValue(PCTSTR pszPropName, const TString& rDefaultValue) const + { + boost::shared_lock lock(m_lock); + TString tResult = rDefaultValue; + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + tResult = (*iterFnd).m_strValue; + + return tResult; + } + + template<> + bool GetValue(PCTSTR pszPropName, const bool& bDefaultValue) const + { + boost::shared_lock lock(m_lock); + bool bResult = bDefaultValue; + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("false")) == 0) + bResult = false; + else if ((*iterFnd).m_strValue.Get().CompareNoCase(_T("true")) == 0) + bResult = true; + else + bResult = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + } + + return bResult; + } + + template + bool GetValueNoDefault(PCTSTR pszPropName, T& rValue) const + { + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + rValue = boost::lexical_cast((*iterFnd).m_strValue.Get().c_str()); + return true; + } + + return false; + } + + template<> + bool GetValueNoDefault(PCTSTR pszPropName, TString& rValue) const + { + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + rValue = (*iterFnd).m_strValue; + return true; + } + + return false; + } + + template<> + bool GetValueNoDefault(PCTSTR pszPropName, bool& rValue) const + { + boost::shared_lock lock(m_lock); + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + const TString& strValue = (*iterFnd).m_strValue.Get(); + if (strValue.CompareNoCase(_T("false")) == 0) + rValue = false; + else if (strValue.CompareNoCase(_T("true")) == 0) + rValue = true; + else + rValue = boost::lexical_cast(strValue.c_str()); + return true; + } + + return false; + } + + template + bool SetValue(PCTSTR pszPropName, const T& rValue) + { + boost::unique_lock lock(m_lock); + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + ChangeValue tChange(boost::lexical_cast(rValue).c_str()); + m_mic.modify(iterFnd, std::ref(tChange)); + return tChange.WasModified(); + } + else + { + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, boost::lexical_cast(rValue).c_str())); + return true; + } + } + + template<> + bool SetValue(PCTSTR pszPropName, const bool& bValue) + { + boost::unique_lock lock(m_lock); + + ConfigNodeContainer::NodeContainer::const_iterator iterFnd = m_mic.find(boost::make_tuple(pszPropName, 0)); + if (iterFnd != m_mic.end()) + { + ChangeValue tChange(boost::lexical_cast(bValue ? _T("true") : _T("false")).c_str()); + m_mic.modify(iterFnd, std::ref(tChange)); + return tChange.WasModified(); + } + else + { + m_mic.insert(ConfigNode(++m_oidLastObjectID, pszPropName, 0, bValue ? _T("true") : _T("false"))); + return true; + } + } + + // vector-based values + TStringArray GetArrayValue(PCTSTR pszPropName, const TStringArray& rDefaultValue) const; + bool GetArrayValueNoDefault(PCTSTR pszPropName, TStringArray& rValue) const; + bool SetArrayValue(PCTSTR pszPropName, const TStringArray& rValue); + + // deletion + void DeleteNode(PCTSTR pszPropName); + + // extracting nodes + bool ExtractNodes(PCTSTR pszNode, ConfigNodeContainer& tNewContainer) const; + bool ExtractMultipleNodes(PCTSTR pszNode, std::vector& tNewContainers) const; + + void ImportNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // replaces specified node with data from tContainer + void AddNodes(PCTSTR pszNode, const ConfigNodeContainer& tContainer); // adds specified config as a newly numbered node in this container + + void ImportFromPropertyTree(const boost::property_tree::wiptree& rTree, boost::unique_lock&); + void ExportToPropertyTree(boost::property_tree::wiptree& rTree) const; + +#ifdef _DEBUG + // debugging + void Dump(); +#endif + + private: + void ImportNode(TString strCurrentPath, const boost::property_tree::wiptree& rTree); + + public: + typedef boost::multi_index_container, + boost::multi_index::const_mem_fun + > + > + > + > NodeContainer; + + NodeContainer m_mic; + + TString m_strFilePath; + + boost::signals2::signal m_notifier; + TStringSet m_setDelayedNotifications; + bool m_bDelayedEnabled; + object_id_t m_oidLastObjectID; + + TRemovedObjects m_setRemovedObjects; + + mutable boost::shared_mutex m_lock; + }; + } +} + +#endif Index: src/libchcore/EFeedbackResult.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/EFeedbackResult.h (.../EFeedbackResult.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/EFeedbackResult.h (.../EFeedbackResult.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,37 +1,37 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __EFEEDBACKRESULT_H__ -#define __EFEEDBACKRESULT_H__ - -namespace chcore -{ - enum EFeedbackResult - { - eResult_Unknown = 0, - eResult_Overwrite, - eResult_CopyRest, - eResult_Skip, - eResult_Cancel, - eResult_Pause, - eResult_Retry, - eResult_Ignore - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __EFEEDBACKRESULT_H__ +#define __EFEEDBACKRESULT_H__ + +namespace chcore +{ + enum EFeedbackResult + { + eResult_Unknown = 0, + eResult_Overwrite, + eResult_CopyRest, + eResult_Skip, + eResult_Cancel, + eResult_Pause, + eResult_Retry, + eResult_Ignore + }; +} + +#endif Index: src/libchcore/EFileError.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/EFileError.h (.../EFileError.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/EFileError.h (.../EFileError.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -/*************************************************************************** -* Copyright (C) 2001-2015 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __EFILEERROR_H__ -#define __EFILEERROR_H__ - -namespace chcore -{ - enum class EFileError - { - eDeleteError, ///< Problem occurred when tried to delete the fs object - eSeekError, ///< Problem occurred when tried to set file pointer - eResizeError, ///< Problem occurred when tried to change size of the fs object - eReadError, ///< Problem occurred when tried to read data from file - eWriteError, ///< Problem occurred when tried to write data to a file - eFinalizeError, ///< Problem occurred when tried to finalize file - eFastMoveError, ///< Problem occurred when tried to perform fast move operation (that does not involve copying contents) - eCreateError, ///< Problem occurred when tried to create the fs object - eCheckForFreeSpace, ///< Problem occurred when tried to create the fs object - eRetrieveFileInfo ///< Error while retrieving file information - }; -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2015 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __EFILEERROR_H__ +#define __EFILEERROR_H__ + +namespace chcore +{ + enum class EFileError + { + eDeleteError, ///< Problem occurred when tried to delete the fs object + eSeekError, ///< Problem occurred when tried to set file pointer + eResizeError, ///< Problem occurred when tried to change size of the fs object + eReadError, ///< Problem occurred when tried to read data from file + eWriteError, ///< Problem occurred when tried to write data to a file + eFinalizeError, ///< Problem occurred when tried to finalize file + eFastMoveError, ///< Problem occurred when tried to perform fast move operation (that does not involve copying contents) + eCreateError, ///< Problem occurred when tried to create the fs object + eCheckForFreeSpace, ///< Problem occurred when tried to create the fs object + eRetrieveFileInfo ///< Error while retrieving file information + }; +} + +#endif Index: src/libchcore/EOperationTypes.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/EOperationTypes.h (.../EOperationTypes.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/EOperationTypes.h (.../EOperationTypes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,40 +1,40 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file EOperationTypes.h -/// @date 2011/05/26 -/// @brief Defines an enumeration type with supported operations. -// ============================================================================ -#ifndef __EOPERATIONTYPES_H__ -#define __EOPERATIONTYPES_H__ - -namespace chcore -{ - // enum represents type of the operation handled by the task - enum EOperationType - { - eOperation_None, - eOperation_Copy, - eOperation_Move, - - // add new operation types before this enum value - eOperation_Max - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file EOperationTypes.h +/// @date 2011/05/26 +/// @brief Defines an enumeration type with supported operations. +// ============================================================================ +#ifndef __EOPERATIONTYPES_H__ +#define __EOPERATIONTYPES_H__ + +namespace chcore +{ + // enum represents type of the operation handled by the task + enum EOperationType + { + eOperation_None, + eOperation_Copy, + eOperation_Move, + + // add new operation types before this enum value + eOperation_Max + }; +} + +#endif Index: src/libchcore/ESubTaskTypes.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ESubTaskTypes.h (.../ESubTaskTypes.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ESubTaskTypes.h (.../ESubTaskTypes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,41 +1,41 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file SubTaskTypes.h -/// @date 2011/11/12 -/// @brief File contains subtask types enumeration. -// ============================================================================ -#ifndef __SUBTASKTYPES_H__ -#define __SUBTASKTYPES_H__ - -namespace chcore -{ - enum ESubOperationType - { - eSubOperation_None, - eSubOperation_FastMove, - eSubOperation_Scanning, - eSubOperation_Copying, - eSubOperation_Deleting, - - // add new operation types before this one - eSubOperation_Max - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file SubTaskTypes.h +/// @date 2011/11/12 +/// @brief File contains subtask types enumeration. +// ============================================================================ +#ifndef __SUBTASKTYPES_H__ +#define __SUBTASKTYPES_H__ + +namespace chcore +{ + enum ESubOperationType + { + eSubOperation_None, + eSubOperation_FastMove, + eSubOperation_Scanning, + eSubOperation_Copying, + eSubOperation_Deleting, + + // add new operation types before this one + eSubOperation_Max + }; +} + +#endif Index: src/libchcore/ETaskCurrentState.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ETaskCurrentState.h (.../ETaskCurrentState.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ETaskCurrentState.h (.../ETaskCurrentState.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,41 +1,41 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ETASKCURRENTSTATE_H__ -#define __ETASKCURRENTSTATE_H__ - -namespace chcore -{ - // enum representing current processing state of the task - enum ETaskCurrentState - { - eTaskState_None, - eTaskState_Waiting, - eTaskState_Processing, - eTaskState_Paused, - eTaskState_Cancelled, - eTaskState_Error, - eTaskState_Finished, - eTaskState_LoadError, - - // insert new values before this one - eTaskState_Max - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ETASKCURRENTSTATE_H__ +#define __ETASKCURRENTSTATE_H__ + +namespace chcore +{ + // enum representing current processing state of the task + enum ETaskCurrentState + { + eTaskState_None, + eTaskState_Waiting, + eTaskState_Processing, + eTaskState_Paused, + eTaskState_Cancelled, + eTaskState_Error, + eTaskState_Finished, + eTaskState_LoadError, + + // insert new values before this one + eTaskState_Max + }; +} + +#endif Index: src/libchcore/EngineConstants.h =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/EngineConstants.h (.../EngineConstants.h) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/EngineConstants.h (.../EngineConstants.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ENGINECONSTANTS_H__ -#define __ENGINECONSTANTS_H__ - -namespace chcore -{ - static const unsigned long long AssumedFileMinDataSize = 4096; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ENGINECONSTANTS_H__ +#define __ENGINECONSTANTS_H__ + +namespace chcore +{ + static const unsigned long long AssumedFileMinDataSize = 4096; +} + +#endif Index: src/libchcore/ErrorCodes.h =================================================================== diff -u -r306fbe693c70290af9de9a5779084a697de22d75 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ErrorCodes.h (.../ErrorCodes.h) (revision 306fbe693c70290af9de9a5779084a697de22d75) +++ src/libchcore/ErrorCodes.h (.../ErrorCodes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,114 +1,114 @@ -/*************************************************************************** -* Copyright (C) 2001-2008 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __ERROR_CODES_H__ -#define __ERROR_CODES_H__ - -namespace chcore -{ - enum EGeneralErrors - { - // general errors - eErr_Success = 0, - eErr_BoundsExceeded = 1, - eErr_InvalidArgument = 2, - eErr_UnhandledCase = 3, - eErr_InternalProblem = 4, - eErr_UseOfUninitializedObject = 5, - eErr_InvalidData = 6, - eErr_InvalidPointer = 7, - - // shared memory (500+) - eErr_CannotOpenSharedMemory = 500, - eErr_SharedMemoryNotOpen = 501, - eErr_SharedMemoryInvalidFormat = 502, - eErr_SharedMemoryAlreadyExists = 503, - - // threading (1000+) - eErr_MutexTimedOut = 1000, - eErr_CannotCreateEvent = 1001, - eErr_ThreadAlreadyStarted = 1002, - eErr_CannotResetEvent = 1003, - eErr_CannotCreateThread = 1004, - eErr_CannotChangeThreadPriority = 1005, - eErr_CannotResumeThread = 1006, - eErr_WaitingFailed = 1007, - eErr_CannotSuspendThread = 1008, - eErr_CannotSetEvent = 1009, - eErr_CannotCreateMutex = 1010, - - // string errors (1500+) - - // Task definition errors (2000+) - eErr_UnsupportedVersion = 2000, - eErr_MissingXmlData = 2001, - eErr_TaskAlreadyExists = 2002, - - // Serialization errors (2500+) - eErr_CannotReadArchive = 2500, - eErr_SerializeLoadError = 2501, - eErr_SerializeStoreError = 2502, - eErr_ContainerObjectMismatch = 2503, - eErr_NodeDoesNotExist = 2504, - eErr_UnsupportedMultipleSubnodesLevels = 2505, - eErr_CannotWriteArchive = 2506, - eErr_InvalidSerializationData = 2507, - eErr_CannotSetDatabaseOptions = 2508, - eErr_InvalidSerializer = 2509, - - // Filesystem errors (3000+) - eErr_FixedDriveWithoutDriveLetter = 3000, - eErr_CannotGetFileInfo = 3001, - eErr_CannotDeleteFile = 3002, - eErr_CannotReadFile = 3003, - eErr_CannotWriteFile = 3004, - eErr_InvalidOverlappedPosition = 3005, - eErr_CannotOpenFile = 3006, - eErr_FileNotOpen = 3007, - eErr_SeekFailed = 3008, - eErr_CannotTruncate = 3009, - eErr_CannotSetFileTimes = 3010, - eErr_CannotSetFileAttributes = 3011, - eErr_CannotCreateDirectory = 3012, - eErr_CannotRemoveDirectory = 3013, - eErr_CannotFastMove = 3014, - eErr_CannotGetFreeSpace = 3015, - - // Task handling errors (4000+) - eErr_MissingTaskSerializationPath = 4000, - eErr_UndefinedOperation = 4001, - - // Memory allocation/deallocation (4500+) - eErr_CannotAllocateMemory = 4500, - - // database errors (5000+) - eErr_SQLiteCannotOpenDatabase = 5000, - eErr_SQLiteFinalizeError = 5001, - eErr_SQLitePrepareError = 5002, - eErr_SQLiteStatementNotPrepared = 5003, - eErr_SQLiteStepError = 5004, - eErr_SQLiteBindError = 5005, - eErr_SQLiteNoRowAvailable = 5006, - eErr_SQLiteCannotBeginTransaction = 5007, - eErr_SQLiteCannotRollbackTransaction = 5008, - eErr_SQLiteCannotCommitTransaction = 5009, - eErr_SQLiteReset = 5010, - }; -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2008 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __ERROR_CODES_H__ +#define __ERROR_CODES_H__ + +namespace chcore +{ + enum EGeneralErrors + { + // general errors + eErr_Success = 0, + eErr_BoundsExceeded = 1, + eErr_InvalidArgument = 2, + eErr_UnhandledCase = 3, + eErr_InternalProblem = 4, + eErr_UseOfUninitializedObject = 5, + eErr_InvalidData = 6, + eErr_InvalidPointer = 7, + + // shared memory (500+) + eErr_CannotOpenSharedMemory = 500, + eErr_SharedMemoryNotOpen = 501, + eErr_SharedMemoryInvalidFormat = 502, + eErr_SharedMemoryAlreadyExists = 503, + + // threading (1000+) + eErr_MutexTimedOut = 1000, + eErr_CannotCreateEvent = 1001, + eErr_ThreadAlreadyStarted = 1002, + eErr_CannotResetEvent = 1003, + eErr_CannotCreateThread = 1004, + eErr_CannotChangeThreadPriority = 1005, + eErr_CannotResumeThread = 1006, + eErr_WaitingFailed = 1007, + eErr_CannotSuspendThread = 1008, + eErr_CannotSetEvent = 1009, + eErr_CannotCreateMutex = 1010, + + // string errors (1500+) + + // Task definition errors (2000+) + eErr_UnsupportedVersion = 2000, + eErr_MissingXmlData = 2001, + eErr_TaskAlreadyExists = 2002, + + // Serialization errors (2500+) + eErr_CannotReadArchive = 2500, + eErr_SerializeLoadError = 2501, + eErr_SerializeStoreError = 2502, + eErr_ContainerObjectMismatch = 2503, + eErr_NodeDoesNotExist = 2504, + eErr_UnsupportedMultipleSubnodesLevels = 2505, + eErr_CannotWriteArchive = 2506, + eErr_InvalidSerializationData = 2507, + eErr_CannotSetDatabaseOptions = 2508, + eErr_InvalidSerializer = 2509, + + // Filesystem errors (3000+) + eErr_FixedDriveWithoutDriveLetter = 3000, + eErr_CannotGetFileInfo = 3001, + eErr_CannotDeleteFile = 3002, + eErr_CannotReadFile = 3003, + eErr_CannotWriteFile = 3004, + eErr_InvalidOverlappedPosition = 3005, + eErr_CannotOpenFile = 3006, + eErr_FileNotOpen = 3007, + eErr_SeekFailed = 3008, + eErr_CannotTruncate = 3009, + eErr_CannotSetFileTimes = 3010, + eErr_CannotSetFileAttributes = 3011, + eErr_CannotCreateDirectory = 3012, + eErr_CannotRemoveDirectory = 3013, + eErr_CannotFastMove = 3014, + eErr_CannotGetFreeSpace = 3015, + + // Task handling errors (4000+) + eErr_MissingTaskSerializationPath = 4000, + eErr_UndefinedOperation = 4001, + + // Memory allocation/deallocation (4500+) + eErr_CannotAllocateMemory = 4500, + + // database errors (5000+) + eErr_SQLiteCannotOpenDatabase = 5000, + eErr_SQLiteFinalizeError = 5001, + eErr_SQLitePrepareError = 5002, + eErr_SQLiteStatementNotPrepared = 5003, + eErr_SQLiteStepError = 5004, + eErr_SQLiteBindError = 5005, + eErr_SQLiteNoRowAvailable = 5006, + eErr_SQLiteCannotBeginTransaction = 5007, + eErr_SQLiteCannotRollbackTransaction = 5008, + eErr_SQLiteCannotCommitTransaction = 5009, + eErr_SQLiteReset = 5010, + }; +} + +#endif Index: src/libchcore/IColumnsDefinition.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IColumnsDefinition.cpp (.../IColumnsDefinition.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IColumnsDefinition.cpp (.../IColumnsDefinition.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IColumnsDefinition.h" - -namespace chcore -{ - IColumnsDefinition::~IColumnsDefinition() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IColumnsDefinition.h" + +namespace chcore +{ + IColumnsDefinition::~IColumnsDefinition() + { + } +} Index: src/libchcore/IColumnsDefinition.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IColumnsDefinition.h (.../IColumnsDefinition.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/IColumnsDefinition.h (.../IColumnsDefinition.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,82 +1,82 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ICOLUMNSDEFINITION_H__ -#define __ICOLUMNSDEFINITION_H__ - -#include "libchcore.h" -#include "TString.h" -#include "TPath.h" - -namespace chcore -{ - class LIBCHCORE_API IColumnsDefinition - { - public: - enum ETypes - { - eType_bool, - eType_short, - eType_ushort, - eType_int, - eType_uint, - eType_long, - eType_ulong, - eType_longlong, - eType_ulonglong, - eType_double, - eType_string, - eType_path, - - eType_Last - }; - - public: - virtual ~IColumnsDefinition(); - - virtual size_t AddColumn(const TString& strColumnName, ETypes eColType) = 0; - virtual void Clear() = 0; - - virtual size_t GetColumnIndex(const wchar_t* strColumnName) = 0; - virtual const TString& GetColumnName(size_t stIndex) const = 0; - virtual size_t GetCount() const = 0; - virtual bool IsEmpty() const = 0; - }; - - template struct ColumnType {}; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_bool; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_short; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ushort; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_int; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_uint; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_long; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulong; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_longlong; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulonglong; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_double; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_string; }; - template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_path; }; - - template - IColumnsDefinition::ETypes GetColumnType(const T&) - { - return ColumnType::value; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ICOLUMNSDEFINITION_H__ +#define __ICOLUMNSDEFINITION_H__ + +#include "libchcore.h" +#include "TString.h" +#include "TPath.h" + +namespace chcore +{ + class LIBCHCORE_API IColumnsDefinition + { + public: + enum ETypes + { + eType_bool, + eType_short, + eType_ushort, + eType_int, + eType_uint, + eType_long, + eType_ulong, + eType_longlong, + eType_ulonglong, + eType_double, + eType_string, + eType_path, + + eType_Last + }; + + public: + virtual ~IColumnsDefinition(); + + virtual size_t AddColumn(const TString& strColumnName, ETypes eColType) = 0; + virtual void Clear() = 0; + + virtual size_t GetColumnIndex(const wchar_t* strColumnName) = 0; + virtual const TString& GetColumnName(size_t stIndex) const = 0; + virtual size_t GetCount() const = 0; + virtual bool IsEmpty() const = 0; + }; + + template struct ColumnType {}; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_bool; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_short; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ushort; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_int; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_uint; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_long; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_longlong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_ulonglong; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_double; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_string; }; + template<> struct ColumnType { static const IColumnsDefinition::ETypes value = IColumnsDefinition::eType_path; }; + + template + IColumnsDefinition::ETypes GetColumnType(const T&) + { + return ColumnType::value; + } +} + +#endif Index: src/libchcore/IFeedbackHandler.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFeedbackHandler.cpp (.../IFeedbackHandler.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IFeedbackHandler.cpp (.../IFeedbackHandler.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IFeedbackHandler.h" - -namespace chcore -{ - IFeedbackHandler::~IFeedbackHandler() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IFeedbackHandler.h" + +namespace chcore +{ + IFeedbackHandler::~IFeedbackHandler() + { + } +} Index: src/libchcore/IFeedbackHandlerFactory.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFeedbackHandlerFactory.cpp (.../IFeedbackHandlerFactory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IFeedbackHandlerFactory.cpp (.../IFeedbackHandlerFactory.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IFeedbackHandlerFactory.h" - -namespace chcore -{ - IFeedbackHandlerFactory::~IFeedbackHandlerFactory() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IFeedbackHandlerFactory.h" + +namespace chcore +{ + IFeedbackHandlerFactory::~IFeedbackHandlerFactory() + { + } +} Index: src/libchcore/IFeedbackHandlerFactory.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFeedbackHandlerFactory.h (.../IFeedbackHandlerFactory.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/IFeedbackHandlerFactory.h (.../IFeedbackHandlerFactory.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,37 +1,37 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __IFEEDBACKHANDLERFACTORY_H__ -#define __IFEEDBACKHANDLERFACTORY_H__ - -#include "libchcore.h" -#include "IFeedbackHandler.h" - -namespace chcore -{ - class LIBCHCORE_API IFeedbackHandlerFactory - { - public: - virtual ~IFeedbackHandlerFactory(); - virtual IFeedbackHandlerPtr Create() = 0; - }; - - typedef std::shared_ptr IFeedbackHandlerFactoryPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __IFEEDBACKHANDLERFACTORY_H__ +#define __IFEEDBACKHANDLERFACTORY_H__ + +#include "libchcore.h" +#include "IFeedbackHandler.h" + +namespace chcore +{ + class LIBCHCORE_API IFeedbackHandlerFactory + { + public: + virtual ~IFeedbackHandlerFactory(); + virtual IFeedbackHandlerPtr Create() = 0; + }; + + typedef std::shared_ptr IFeedbackHandlerFactoryPtr; +} + +#endif Index: src/libchcore/IFilesystem.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystem.cpp (.../IFilesystem.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IFilesystem.cpp (.../IFilesystem.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IFilesystem.h" - -namespace chcore -{ - IFilesystem::~IFilesystem() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IFilesystem.h" + +namespace chcore +{ + IFilesystem::~IFilesystem() + { + } +} Index: src/libchcore/IFilesystem.h =================================================================== diff -u -r789d0908abf8db57e27cfeac7045d9962f4b522a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystem.h (.../IFilesystem.h) (revision 789d0908abf8db57e27cfeac7045d9962f4b522a) +++ src/libchcore/IFilesystem.h (.../IFilesystem.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,70 +1,70 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __IFILESYSTEM_H__ -#define __IFILESYSTEM_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "TFileInfoFwd.h" -#include "TBasePathDataFwd.h" -#include "TFileTime.h" -#include "IFilesystemFind.h" -#include "IFilesystemFile.h" - -namespace chcore -{ - class LIBCHCORE_API IFilesystem - { - public: - enum EPathsRelation - { - eRelation_Network, // at least one of the paths is network one - eRelation_CDRom, // at least one of the paths relates to cd/dvd drive - eRelation_TwoPhysicalDisks, // paths lies on two separate physical disks - eRelation_SinglePhysicalDisk, // paths lies on the same physical disk - eRelation_Other // other type of relation - }; - - public: - virtual ~IFilesystem(); - - virtual bool PathExist(const TSmartPath& strPath) = 0; - - virtual void SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) = 0; - virtual void SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) = 0; - - virtual void CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) = 0; - virtual void RemoveDirectory(const TSmartPath& pathFile) = 0; - virtual void DeleteFile(const TSmartPath& pathFile) = 0; - - virtual void GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) = 0; - virtual void FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) = 0; - - virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) = 0; - virtual IFilesystemFilePtr CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) = 0; - - virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) = 0; - - virtual void GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) = 0; - }; - - typedef std::shared_ptr IFilesystemPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __IFILESYSTEM_H__ +#define __IFILESYSTEM_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "TFileInfoFwd.h" +#include "TBasePathDataFwd.h" +#include "TFileTime.h" +#include "IFilesystemFind.h" +#include "IFilesystemFile.h" + +namespace chcore +{ + class LIBCHCORE_API IFilesystem + { + public: + enum EPathsRelation + { + eRelation_Network, // at least one of the paths is network one + eRelation_CDRom, // at least one of the paths relates to cd/dvd drive + eRelation_TwoPhysicalDisks, // paths lies on two separate physical disks + eRelation_SinglePhysicalDisk, // paths lies on the same physical disk + eRelation_Other // other type of relation + }; + + public: + virtual ~IFilesystem(); + + virtual bool PathExist(const TSmartPath& strPath) = 0; + + virtual void SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) = 0; + virtual void SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) = 0; + + virtual void CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) = 0; + virtual void RemoveDirectory(const TSmartPath& pathFile) = 0; + virtual void DeleteFile(const TSmartPath& pathFile) = 0; + + virtual void GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) = 0; + virtual void FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) = 0; + + virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) = 0; + virtual IFilesystemFilePtr CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) = 0; + + virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) = 0; + + virtual void GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) = 0; + }; + + typedef std::shared_ptr IFilesystemPtr; +} + +#endif Index: src/libchcore/IFilesystemFile.cpp =================================================================== diff -u -r27c262eb9cae55720e10f4886af6b5a82cb94fe9 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystemFile.cpp (.../IFilesystemFile.cpp) (revision 27c262eb9cae55720e10f4886af6b5a82cb94fe9) +++ src/libchcore/IFilesystemFile.cpp (.../IFilesystemFile.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IFilesystemFile.h" - -namespace chcore -{ - IFilesystemFile::~IFilesystemFile() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IFilesystemFile.h" + +namespace chcore +{ + IFilesystemFile::~IFilesystemFile() + { + } +} Index: src/libchcore/IFilesystemFile.h =================================================================== diff -u -r789d0908abf8db57e27cfeac7045d9962f4b522a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystemFile.h (.../IFilesystemFile.h) (revision 789d0908abf8db57e27cfeac7045d9962f4b522a) +++ src/libchcore/IFilesystemFile.h (.../IFilesystemFile.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,67 +1,67 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __IFILESYSTEMFILE_H__ -#define __IFILESYSTEMFILE_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "CommonDataTypes.h" - -namespace chcore -{ - class TOverlappedDataBuffer; - class TFileInfo; - - class LIBCHCORE_API IFilesystemFile - { - public: - enum EOpenMode - { - eMode_Read, - eMode_Write - }; - - public: - static const unsigned int MaxSectorSize = 4096; - - public: - virtual ~IFilesystemFile(); - - virtual void Truncate(file_size_t fsNewSize) = 0; - - virtual void ReadFile(TOverlappedDataBuffer& rBuffer) = 0; - virtual void WriteFile(TOverlappedDataBuffer& rBuffer) = 0; - virtual void FinalizeFile(TOverlappedDataBuffer& rBuffer) = 0; - - virtual void Close() = 0; - - virtual bool IsOpen() const = 0; - virtual bool IsFreshlyCreated() = 0; - - virtual file_size_t GetFileSize() = 0; - virtual void GetFileInfo(TFileInfo& tFileInfo) = 0; - - virtual TSmartPath GetFilePath() const = 0; - virtual file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition) = 0; - }; - - typedef std::shared_ptr IFilesystemFilePtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __IFILESYSTEMFILE_H__ +#define __IFILESYSTEMFILE_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "CommonDataTypes.h" + +namespace chcore +{ + class TOverlappedDataBuffer; + class TFileInfo; + + class LIBCHCORE_API IFilesystemFile + { + public: + enum EOpenMode + { + eMode_Read, + eMode_Write + }; + + public: + static const unsigned int MaxSectorSize = 4096; + + public: + virtual ~IFilesystemFile(); + + virtual void Truncate(file_size_t fsNewSize) = 0; + + virtual void ReadFile(TOverlappedDataBuffer& rBuffer) = 0; + virtual void WriteFile(TOverlappedDataBuffer& rBuffer) = 0; + virtual void FinalizeFile(TOverlappedDataBuffer& rBuffer) = 0; + + virtual void Close() = 0; + + virtual bool IsOpen() const = 0; + virtual bool IsFreshlyCreated() = 0; + + virtual file_size_t GetFileSize() = 0; + virtual void GetFileInfo(TFileInfo& tFileInfo) = 0; + + virtual TSmartPath GetFilePath() const = 0; + virtual file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition) = 0; + }; + + typedef std::shared_ptr IFilesystemFilePtr; +} + +#endif Index: src/libchcore/IFilesystemFind.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystemFind.cpp (.../IFilesystemFind.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IFilesystemFind.cpp (.../IFilesystemFind.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IFilesystemFind.h" - -namespace chcore -{ - IFilesystemFind::~IFilesystemFind() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IFilesystemFind.h" + +namespace chcore +{ + IFilesystemFind::~IFilesystemFind() + { + } +} Index: src/libchcore/IFilesystemFind.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IFilesystemFind.h (.../IFilesystemFind.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IFilesystemFind.h (.../IFilesystemFind.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __IFILESYSTEMFIND_H__ -#define __IFILESYSTEMFIND_H__ - -#include "libchcore.h" -#include "TFileInfoFwd.h" - -namespace chcore -{ - class LIBCHCORE_API IFilesystemFind - { - public: - virtual ~IFilesystemFind(); - - virtual bool FindNext(TFileInfoPtr& rspFileInfo) = 0; - virtual void Close() = 0; - }; - - typedef std::shared_ptr IFilesystemFindPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __IFILESYSTEMFIND_H__ +#define __IFILESYSTEMFIND_H__ + +#include "libchcore.h" +#include "TFileInfoFwd.h" + +namespace chcore +{ + class LIBCHCORE_API IFilesystemFind + { + public: + virtual ~IFilesystemFind(); + + virtual bool FindNext(TFileInfoPtr& rspFileInfo) = 0; + virtual void Close() = 0; + }; + + typedef std::shared_ptr IFilesystemFindPtr; +} + +#endif Index: src/libchcore/IRunningTimeControl.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IRunningTimeControl.cpp (.../IRunningTimeControl.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/IRunningTimeControl.cpp (.../IRunningTimeControl.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "IRunningTimeControl.h" - -namespace chcore -{ - IRunningTimeControl::~IRunningTimeControl() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "IRunningTimeControl.h" + +namespace chcore +{ + IRunningTimeControl::~IRunningTimeControl() + { + } +} Index: src/libchcore/IRunningTimeControl.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/IRunningTimeControl.h (.../IRunningTimeControl.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/IRunningTimeControl.h (.../IRunningTimeControl.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __IRUNNINGTIMESTATS_H__ -#define __IRUNNINGTIMESTATS_H__ - -namespace chcore -{ - class IRunningTimeControl - { - public: - virtual ~IRunningTimeControl(); - - // time tracking - virtual void EnableTimeTracking() = 0; - virtual void DisableTimeTracking() = 0; - - // running/not running state - virtual void MarkAsRunning() = 0; - virtual void MarkAsNotRunning() = 0; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __IRUNNINGTIMESTATS_H__ +#define __IRUNNINGTIMESTATS_H__ + +namespace chcore +{ + class IRunningTimeControl + { + public: + virtual ~IRunningTimeControl(); + + // time tracking + virtual void EnableTimeTracking() = 0; + virtual void DisableTimeTracking() = 0; + + // running/not running state + virtual void MarkAsRunning() = 0; + virtual void MarkAsNotRunning() = 0; + }; +} + +#endif Index: src/libchcore/ISQLiteSerializerSchema.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISQLiteSerializerSchema.cpp (.../ISQLiteSerializerSchema.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISQLiteSerializerSchema.cpp (.../ISQLiteSerializerSchema.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISQLiteSerializerSchema.h" - -namespace chcore -{ - ISQLiteSerializerSchema::~ISQLiteSerializerSchema() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISQLiteSerializerSchema.h" + +namespace chcore +{ + ISQLiteSerializerSchema::~ISQLiteSerializerSchema() + { + } +} Index: src/libchcore/ISQLiteSerializerSchema.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISQLiteSerializerSchema.h (.../ISQLiteSerializerSchema.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISQLiteSerializerSchema.h (.../ISQLiteSerializerSchema.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,38 +1,38 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZERSCHEMA_H__ -#define __ISERIALIZERSCHEMA_H__ - -#include "libchcore.h" -#include "TSQLiteDatabase.h" - -namespace chcore -{ - class LIBCHCORE_API ISQLiteSerializerSchema - { - public: - virtual ~ISQLiteSerializerSchema(); - - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) = 0; - }; - - typedef std::shared_ptr ISerializerSchemaPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZERSCHEMA_H__ +#define __ISERIALIZERSCHEMA_H__ + +#include "libchcore.h" +#include "TSQLiteDatabase.h" + +namespace chcore +{ + class LIBCHCORE_API ISQLiteSerializerSchema + { + public: + virtual ~ISQLiteSerializerSchema(); + + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) = 0; + }; + + typedef std::shared_ptr ISerializerSchemaPtr; +} + +#endif Index: src/libchcore/ISerializer.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializer.cpp (.../ISerializer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISerializer.cpp (.../ISerializer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISerializer.h" - -namespace chcore -{ - ISerializer::~ISerializer() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISerializer.h" + +namespace chcore +{ + ISerializer::~ISerializer() + { + } +} Index: src/libchcore/ISerializer.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializer.h (.../ISerializer.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISerializer.h (.../ISerializer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,42 +1,42 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZER_H__ -#define __ISERIALIZER_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "ISerializerContainer.h" - -namespace chcore -{ - class LIBCHCORE_API ISerializer - { - public: - virtual ~ISerializer(); - - virtual TSmartPath GetLocation() const = 0; - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) = 0; - - virtual void Flush() = 0; - }; - - typedef std::shared_ptr ISerializerPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZER_H__ +#define __ISERIALIZER_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "ISerializerContainer.h" + +namespace chcore +{ + class LIBCHCORE_API ISerializer + { + public: + virtual ~ISerializer(); + + virtual TSmartPath GetLocation() const = 0; + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) = 0; + + virtual void Flush() = 0; + }; + + typedef std::shared_ptr ISerializerPtr; +} + +#endif Index: src/libchcore/ISerializerContainer.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerContainer.cpp (.../ISerializerContainer.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISerializerContainer.cpp (.../ISerializerContainer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISerializerContainer.h" - -namespace chcore -{ - ISerializerContainer::~ISerializerContainer() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISerializerContainer.h" + +namespace chcore +{ + ISerializerContainer::~ISerializerContainer() + { + } +} Index: src/libchcore/ISerializerContainer.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerContainer.h (.../ISerializerContainer.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISerializerContainer.h (.../ISerializerContainer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZERCONTAINER_H__ -#define __ISERIALIZERCONTAINER_H__ - -#include "libchcore.h" -#include "IColumnsDefinition.h" -#include "ISerializerRowReader.h" -#include "SerializerDataTypes.h" - -namespace chcore -{ - class ISerializerRowData; - class TRemovedObjects; - - class LIBCHCORE_API ISerializerContainer - { - public: - virtual ~ISerializerContainer(); - - // columns - virtual IColumnsDefinition& GetColumnsDefinition() = 0; - - // prepare data to be stored - virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded) = 0; - virtual void DeleteRow(object_id_t oidRowID) = 0; - virtual void DeleteRows(const TRemovedObjects& setObjects) = 0; - - // getting data from the serialized archive - virtual ISerializerRowReaderPtr GetRowReader() = 0; - }; - - using ISerializerContainerPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZERCONTAINER_H__ +#define __ISERIALIZERCONTAINER_H__ + +#include "libchcore.h" +#include "IColumnsDefinition.h" +#include "ISerializerRowReader.h" +#include "SerializerDataTypes.h" + +namespace chcore +{ + class ISerializerRowData; + class TRemovedObjects; + + class LIBCHCORE_API ISerializerContainer + { + public: + virtual ~ISerializerContainer(); + + // columns + virtual IColumnsDefinition& GetColumnsDefinition() = 0; + + // prepare data to be stored + virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded) = 0; + virtual void DeleteRow(object_id_t oidRowID) = 0; + virtual void DeleteRows(const TRemovedObjects& setObjects) = 0; + + // getting data from the serialized archive + virtual ISerializerRowReaderPtr GetRowReader() = 0; + }; + + using ISerializerContainerPtr = std::shared_ptr; +} + +#endif Index: src/libchcore/ISerializerFactory.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerFactory.cpp (.../ISerializerFactory.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISerializerFactory.cpp (.../ISerializerFactory.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISerializerFactory.h" - -namespace chcore -{ - ISerializerFactory::~ISerializerFactory() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISerializerFactory.h" + +namespace chcore +{ + ISerializerFactory::~ISerializerFactory() + { + } +} Index: src/libchcore/ISerializerFactory.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerFactory.h (.../ISerializerFactory.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISerializerFactory.h (.../ISerializerFactory.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,40 +1,40 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZERFACTORY_H__ -#define __ISERIALIZERFACTORY_H__ - -#include "libchcore.h" -#include "TString.h" -#include "ISerializer.h" - -namespace chcore -{ - class LIBCHCORE_API ISerializerFactory - { - public: - virtual ~ISerializerFactory(); - - virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) = 0; - virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) = 0; - }; - - typedef std::shared_ptr ISerializerFactoryPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZERFACTORY_H__ +#define __ISERIALIZERFACTORY_H__ + +#include "libchcore.h" +#include "TString.h" +#include "ISerializer.h" + +namespace chcore +{ + class LIBCHCORE_API ISerializerFactory + { + public: + virtual ~ISerializerFactory(); + + virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) = 0; + virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) = 0; + }; + + typedef std::shared_ptr ISerializerFactoryPtr; +} + +#endif Index: src/libchcore/ISerializerRowData.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerRowData.cpp (.../ISerializerRowData.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISerializerRowData.cpp (.../ISerializerRowData.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISerializerRowData.h" - -namespace chcore -{ - ISerializerRowData::~ISerializerRowData() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISerializerRowData.h" + +namespace chcore +{ + ISerializerRowData::~ISerializerRowData() + { + } +} Index: src/libchcore/ISerializerRowData.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerRowData.h (.../ISerializerRowData.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISerializerRowData.h (.../ISerializerRowData.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,64 +1,64 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZERROWWRITER_H__ -#define __ISERIALIZERROWWRITER_H__ - -#include "libchcore.h" -#include "TString.h" -#include "TPath.h" - -namespace chcore -{ - class ISerializerContainer; - using ISerializerContainerPtr = std::shared_ptr; - - class LIBCHCORE_API ISerializerRowData - { - public: - virtual ~ISerializerRowData(); - - virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue) = 0; - virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue) = 0; - - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue) = 0; - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) = 0; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZERROWWRITER_H__ +#define __ISERIALIZERROWWRITER_H__ + +#include "libchcore.h" +#include "TString.h" +#include "TPath.h" + +namespace chcore +{ + class ISerializerContainer; + using ISerializerContainerPtr = std::shared_ptr; + + class LIBCHCORE_API ISerializerRowData + { + public: + virtual ~ISerializerRowData(); + + virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue) = 0; + virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue) = 0; + + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue) = 0; + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) = 0; + }; +} + +#endif Index: src/libchcore/ISerializerRowReader.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerRowReader.cpp (.../ISerializerRowReader.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/ISerializerRowReader.cpp (.../ISerializerRowReader.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "ISerializerRowReader.h" - -namespace chcore -{ - ISerializerRowReader::~ISerializerRowReader() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "ISerializerRowReader.h" + +namespace chcore +{ + ISerializerRowReader::~ISerializerRowReader() + { + } +} Index: src/libchcore/ISerializerRowReader.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ISerializerRowReader.h (.../ISerializerRowReader.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ISerializerRowReader.h (.../ISerializerRowReader.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,53 +1,53 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ISERIALIZERROWREADER_H__ -#define __ISERIALIZERROWREADER_H__ - -#include "libchcore.h" -#include "TString.h" -#include "TPath.h" -#include "IColumnsDefinition.h" - -namespace chcore -{ - class LIBCHCORE_API ISerializerRowReader - { - public: - virtual ~ISerializerRowReader(); - - virtual bool Next() = 0; - - virtual void GetValue(const TString& strColName, bool& bValue) = 0; - virtual void GetValue(const TString& strColName, short& iValue) = 0; - virtual void GetValue(const TString& strColName, unsigned short& uiValue) = 0; - virtual void GetValue(const TString& strColName, int& iValue) = 0; - virtual void GetValue(const TString& strColName, unsigned int& uiValue) = 0; - virtual void GetValue(const TString& strColName, long& lValue) = 0; - virtual void GetValue(const TString& strColName, unsigned long& ulValue) = 0; - virtual void GetValue(const TString& strColName, long long& llValue) = 0; - virtual void GetValue(const TString& strColName, unsigned long long& llValue) = 0; - virtual void GetValue(const TString& strColName, double& dValue) = 0; - virtual void GetValue(const TString& strColName, TString& strValue) = 0; - virtual void GetValue(const TString& strColName, TSmartPath& pathValue) = 0; - }; - - typedef std::shared_ptr ISerializerRowReaderPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ISERIALIZERROWREADER_H__ +#define __ISERIALIZERROWREADER_H__ + +#include "libchcore.h" +#include "TString.h" +#include "TPath.h" +#include "IColumnsDefinition.h" + +namespace chcore +{ + class LIBCHCORE_API ISerializerRowReader + { + public: + virtual ~ISerializerRowReader(); + + virtual bool Next() = 0; + + virtual void GetValue(const TString& strColName, bool& bValue) = 0; + virtual void GetValue(const TString& strColName, short& iValue) = 0; + virtual void GetValue(const TString& strColName, unsigned short& uiValue) = 0; + virtual void GetValue(const TString& strColName, int& iValue) = 0; + virtual void GetValue(const TString& strColName, unsigned int& uiValue) = 0; + virtual void GetValue(const TString& strColName, long& lValue) = 0; + virtual void GetValue(const TString& strColName, unsigned long& ulValue) = 0; + virtual void GetValue(const TString& strColName, long long& llValue) = 0; + virtual void GetValue(const TString& strColName, unsigned long long& llValue) = 0; + virtual void GetValue(const TString& strColName, double& dValue) = 0; + virtual void GetValue(const TString& strColName, TString& strValue) = 0; + virtual void GetValue(const TString& strColName, TSmartPath& pathValue) = 0; + }; + + typedef std::shared_ptr ISerializerRowReaderPtr; +} + +#endif Index: src/libchcore/ITimestampProvider.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/ITimestampProvider.h (.../ITimestampProvider.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/ITimestampProvider.h (.../ITimestampProvider.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,36 +1,36 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ITIMESTAMPPROVIDER_H__ -#define __ITIMESTAMPPROVIDER_H__ - -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API ITimestampProvider - { - public: - virtual ~ITimestampProvider() {} - virtual unsigned long long GetCurrentTimestamp() const = 0; - }; - - using ITimestampProviderPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ITIMESTAMPPROVIDER_H__ +#define __ITIMESTAMPPROVIDER_H__ + +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API ITimestampProvider + { + public: + virtual ~ITimestampProvider() {} + virtual unsigned long long GetCurrentTimestamp() const = 0; + }; + + using ITimestampProviderPtr = std::shared_ptr; +} + +#endif Index: src/libchcore/MathFunctions.cpp =================================================================== diff -u -r2e4c7ba0816e80183fd5964d0608d53eea415893 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/MathFunctions.cpp (.../MathFunctions.cpp) (revision 2e4c7ba0816e80183fd5964d0608d53eea415893) +++ src/libchcore/MathFunctions.cpp (.../MathFunctions.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,22 +1,22 @@ -#include "stdafx.h" -#include "MathFunctions.h" -#include - -namespace chcore -{ - namespace Math - { - double Div64(unsigned long long ullNumber, unsigned long long ullDenominator) - { - if (ullDenominator == 0) - return 0.0; - - return (double)ullNumber / (double)ullDenominator; - } - - LIBCHCORE_API double Div64(unsigned long long ullNumber, double dDenominator) - { - return ullNumber / dDenominator; - } - } -} +#include "stdafx.h" +#include "MathFunctions.h" +#include + +namespace chcore +{ + namespace Math + { + double Div64(unsigned long long ullNumber, unsigned long long ullDenominator) + { + if (ullDenominator == 0) + return 0.0; + + return (double)ullNumber / (double)ullDenominator; + } + + LIBCHCORE_API double Div64(unsigned long long ullNumber, double dDenominator) + { + return ullNumber / dDenominator; + } + } +} Index: src/libchcore/MathFunctions.h =================================================================== diff -u -r2e4c7ba0816e80183fd5964d0608d53eea415893 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/MathFunctions.h (.../MathFunctions.h) (revision 2e4c7ba0816e80183fd5964d0608d53eea415893) +++ src/libchcore/MathFunctions.h (.../MathFunctions.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,33 +1,33 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __MATHFUNCTIONS_H__ -#define __MATHFUNCTIONS_H__ - -#include "libchcore.h" - -namespace chcore -{ - namespace Math - { - LIBCHCORE_API double Div64(unsigned long long ullNumber, unsigned long long ullDenominator); - LIBCHCORE_API double Div64(unsigned long long ullNumber, double dDenominator); - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __MATHFUNCTIONS_H__ +#define __MATHFUNCTIONS_H__ + +#include "libchcore.h" + +namespace chcore +{ + namespace Math + { + LIBCHCORE_API double Div64(unsigned long long ullNumber, unsigned long long ullDenominator); + LIBCHCORE_API double Div64(unsigned long long ullNumber, double dDenominator); + } +} + +#endif Index: src/libchcore/RoundingFunctions.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/RoundingFunctions.h (.../RoundingFunctions.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/RoundingFunctions.h (.../RoundingFunctions.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,28 +1,28 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __ROUNDINGFUNCTIONS_H__ -#define __ROUNDINGFUNCTIONS_H__ - -namespace chcore -{ - template T RoundUp(T number, T roundValue) { return ((number + roundValue - 1) & ~(roundValue - 1)); } - template T RoundDown(T number, T roundValue) { return (number & ~(roundValue - 1)); } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __ROUNDINGFUNCTIONS_H__ +#define __ROUNDINGFUNCTIONS_H__ + +namespace chcore +{ + template T RoundUp(T number, T roundValue) { return ((number + roundValue - 1) & ~(roundValue - 1)); } + template T RoundDown(T number, T roundValue) { return (number & ~(roundValue - 1)); } +} + +#endif Index: src/libchcore/SerializerDataTypes.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/SerializerDataTypes.h (.../SerializerDataTypes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/SerializerDataTypes.h (.../SerializerDataTypes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,27 +1,27 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __SERIALIZERDATATYPES_H__ -#define __SERIALIZERDATATYPES_H__ - -namespace chcore -{ - typedef unsigned long object_id_t; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __SERIALIZERDATATYPES_H__ +#define __SERIALIZERDATATYPES_H__ + +namespace chcore +{ + typedef unsigned long object_id_t; +} + +#endif Index: src/libchcore/SerializerTrace.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/SerializerTrace.h (.../SerializerTrace.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/SerializerTrace.h (.../SerializerTrace.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,99 +1,99 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __SERIALIZERTRACE_H__ -#define __SERIALIZERTRACE_H__ - -#include - -// enables tracing -#define ENABLE_TRACE - -// general tracking -#define TRACK_GENERAL - -// db-related tracking -#define TRACK_DB_QUERIES -//#define TRACK_DB_QUERIES_DETAILED - -#ifdef ENABLE_TRACE - inline void trace0(PCTSTR pszFmt) - { - OutputDebugString(pszFmt); - } - - template - inline void trace1(PCTSTR pszFmt, const T& tData) - { - CString strVal; - strVal.Format(pszFmt, tData); - OutputDebugString((PCTSTR)strVal); - } - - template - inline void trace2(PCTSTR pszFmt, const T1& tData1, const T2& tData2) - { - CString strVal; - strVal.Format(pszFmt, tData1, tData2); - OutputDebugString((PCTSTR)strVal); - } - - #define MYTRACE0 trace0 - #define MYTRACE1 trace1 - #define MYTRACE2 trace2 -#else - #define MYTRACE0(fmt) __noop - #define MYTRACE1(fmt, val) __noop - #define MYTRACE2(fmt, val1, val2) __noop -#endif - -#ifdef TRACK_GENERAL - #define GTRACE0 MYTRACE0 - #define GTRACE1 MYTRACE1 - #define GTRACE2 MYTRACE2 -#else - #define GTRACE0(fmt) __noop - #define GTRACE1(fmt, val) __noop - #define GTRACE2(fmt, val1, val2) __noop -#endif - - -#ifdef TRACK_DB_QUERIES - #define DBTRACE0 MYTRACE0 - #define DBTRACE1 MYTRACE1 - #define DBTRACE2 MYTRACE2 - - #ifdef TRACK_DB_QUERIES_DETAILED - #define DBTRACE0_D MYTRACE0 - #define DBTRACE1_D MYTRACE1 - #define DBTRACE2_D MYTRACE2 - #else - #define DBTRACE0_D(fmt) __noop - #define DBTRACE1_D(fmt, val) __noop - #define DBTRACE2_D(fmt, val1, val2) __noop - #endif -#else - #define DBTRACE0(fmt) __noop - #define DBTRACE1(fmt, val) __noop - #define DBTRACE2(fmt, val1, val2) __noop - #define DBTRACE0_D(fmt) __noop - #define DBTRACE1_D(fmt, val) __noop - #define DBTRACE2_D(fmt, val1, val2) __noop -#endif - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __SERIALIZERTRACE_H__ +#define __SERIALIZERTRACE_H__ + +#include + +// enables tracing +#define ENABLE_TRACE + +// general tracking +#define TRACK_GENERAL + +// db-related tracking +#define TRACK_DB_QUERIES +//#define TRACK_DB_QUERIES_DETAILED + +#ifdef ENABLE_TRACE + inline void trace0(PCTSTR pszFmt) + { + OutputDebugString(pszFmt); + } + + template + inline void trace1(PCTSTR pszFmt, const T& tData) + { + CString strVal; + strVal.Format(pszFmt, tData); + OutputDebugString((PCTSTR)strVal); + } + + template + inline void trace2(PCTSTR pszFmt, const T1& tData1, const T2& tData2) + { + CString strVal; + strVal.Format(pszFmt, tData1, tData2); + OutputDebugString((PCTSTR)strVal); + } + + #define MYTRACE0 trace0 + #define MYTRACE1 trace1 + #define MYTRACE2 trace2 +#else + #define MYTRACE0(fmt) __noop + #define MYTRACE1(fmt, val) __noop + #define MYTRACE2(fmt, val1, val2) __noop +#endif + +#ifdef TRACK_GENERAL + #define GTRACE0 MYTRACE0 + #define GTRACE1 MYTRACE1 + #define GTRACE2 MYTRACE2 +#else + #define GTRACE0(fmt) __noop + #define GTRACE1(fmt, val) __noop + #define GTRACE2(fmt, val1, val2) __noop +#endif + + +#ifdef TRACK_DB_QUERIES + #define DBTRACE0 MYTRACE0 + #define DBTRACE1 MYTRACE1 + #define DBTRACE2 MYTRACE2 + + #ifdef TRACK_DB_QUERIES_DETAILED + #define DBTRACE0_D MYTRACE0 + #define DBTRACE1_D MYTRACE1 + #define DBTRACE2_D MYTRACE2 + #else + #define DBTRACE0_D(fmt) __noop + #define DBTRACE1_D(fmt, val) __noop + #define DBTRACE2_D(fmt, val1, val2) __noop + #endif +#else + #define DBTRACE0(fmt) __noop + #define DBTRACE1(fmt, val) __noop + #define DBTRACE2(fmt, val1, val2) __noop + #define DBTRACE0_D(fmt) __noop + #define DBTRACE1_D(fmt, val) __noop + #define DBTRACE2_D(fmt, val1, val2) __noop +#endif + +#endif Index: src/libchcore/TAutoHandles.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TAutoHandles.h (.../TAutoHandles.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TAutoHandles.h (.../TAutoHandles.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,134 +1,134 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TAutoHandles.h -/// @date 2010/09/18 -/// @brief Contains implementation of auto-close handles. -// ============================================================================ -#ifndef __TAUTOHANDLES_H__ -#define __TAUTOHANDLES_H__ - -namespace chcore -{ - /// class encapsulates windows HANDLE, allowing automatic closing it in destructor. - class TAutoFileHandle - { - public: - // ============================================================================ - /// TAutoFileHandle::TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Constructs the TAutoFileHandle object. - // ============================================================================ - TAutoFileHandle() : - m_hHandle(INVALID_HANDLE_VALUE) - { - } - - // ============================================================================ - /// TAutoFileHandle::TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Constructs the TAutoFileHandle object with specified handle. - /// @param[in] hHandle - System handle to be managed by this class. - // ============================================================================ - explicit TAutoFileHandle(HANDLE hHandle) : - m_hHandle(hHandle) - { - } - - // ============================================================================ - /// TAutoFileHandle::~TAutoFileHandle - /// @date 2010/08/26 - /// - /// @brief Destructs the TAutoFileHandle object and closes handle if not closed already. - // ============================================================================ - ~TAutoFileHandle() - { - Close(); - } - - // ============================================================================ - /// TAutoFileHandle::operator= - /// @date 2010/08/26 - /// - /// @brief Assignment operator. - /// @param[in] hHandle - Handle to be assigned. - /// @return Reference to this object, - // ============================================================================ - TAutoFileHandle& operator=(HANDLE hHandle) - { - if (m_hHandle != hHandle) - { - Close(); - m_hHandle = hHandle; - } - return *this; - } - - // ============================================================================ - /// TAutoFileHandle::operator HANDLE - /// @date 2010/08/26 - /// - /// @brief Retrieves the system handle. - /// @return HANDLE value. - // ============================================================================ - operator HANDLE() - { - return m_hHandle; - } - - // ============================================================================ - /// TAutoFileHandle::Close - /// @date 2010/08/26 - /// - /// @brief Closes the internal handle if needed. - /// @return Result of the CloseHandle() function. - // ============================================================================ - BOOL Close() - { - BOOL bResult = TRUE; - if (m_hHandle != INVALID_HANDLE_VALUE) - { - bResult = CloseHandle(m_hHandle); - m_hHandle = INVALID_HANDLE_VALUE; - } - - return bResult; - } - - // ============================================================================ - /// TAutoFileHandle::Detach - /// @date 2010/09/12 - /// - /// @brief Detaches the handle, so it won't be closed in destructor. - /// @return Returns current handle. - // ============================================================================ - HANDLE Detach() - { - HANDLE hHandle = m_hHandle; - m_hHandle = INVALID_HANDLE_VALUE; - return hHandle; - } - - private: - HANDLE m_hHandle; ///< System handle - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TAutoHandles.h +/// @date 2010/09/18 +/// @brief Contains implementation of auto-close handles. +// ============================================================================ +#ifndef __TAUTOHANDLES_H__ +#define __TAUTOHANDLES_H__ + +namespace chcore +{ + /// class encapsulates windows HANDLE, allowing automatic closing it in destructor. + class TAutoFileHandle + { + public: + // ============================================================================ + /// TAutoFileHandle::TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Constructs the TAutoFileHandle object. + // ============================================================================ + TAutoFileHandle() : + m_hHandle(INVALID_HANDLE_VALUE) + { + } + + // ============================================================================ + /// TAutoFileHandle::TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Constructs the TAutoFileHandle object with specified handle. + /// @param[in] hHandle - System handle to be managed by this class. + // ============================================================================ + explicit TAutoFileHandle(HANDLE hHandle) : + m_hHandle(hHandle) + { + } + + // ============================================================================ + /// TAutoFileHandle::~TAutoFileHandle + /// @date 2010/08/26 + /// + /// @brief Destructs the TAutoFileHandle object and closes handle if not closed already. + // ============================================================================ + ~TAutoFileHandle() + { + Close(); + } + + // ============================================================================ + /// TAutoFileHandle::operator= + /// @date 2010/08/26 + /// + /// @brief Assignment operator. + /// @param[in] hHandle - Handle to be assigned. + /// @return Reference to this object, + // ============================================================================ + TAutoFileHandle& operator=(HANDLE hHandle) + { + if (m_hHandle != hHandle) + { + Close(); + m_hHandle = hHandle; + } + return *this; + } + + // ============================================================================ + /// TAutoFileHandle::operator HANDLE + /// @date 2010/08/26 + /// + /// @brief Retrieves the system handle. + /// @return HANDLE value. + // ============================================================================ + operator HANDLE() + { + return m_hHandle; + } + + // ============================================================================ + /// TAutoFileHandle::Close + /// @date 2010/08/26 + /// + /// @brief Closes the internal handle if needed. + /// @return Result of the CloseHandle() function. + // ============================================================================ + BOOL Close() + { + BOOL bResult = TRUE; + if (m_hHandle != INVALID_HANDLE_VALUE) + { + bResult = CloseHandle(m_hHandle); + m_hHandle = INVALID_HANDLE_VALUE; + } + + return bResult; + } + + // ============================================================================ + /// TAutoFileHandle::Detach + /// @date 2010/09/12 + /// + /// @brief Detaches the handle, so it won't be closed in destructor. + /// @return Returns current handle. + // ============================================================================ + HANDLE Detach() + { + HANDLE hHandle = m_hHandle; + m_hHandle = INVALID_HANDLE_VALUE; + return hHandle; + } + + private: + HANDLE m_hHandle; ///< System handle + }; +} + +#endif Index: src/libchcore/TBaseException.cpp =================================================================== diff -u -r71c49ab6ac2e657dee997cb9129c7d0d4dde21b6 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TBaseException.cpp (.../TBaseException.cpp) (revision 71c49ab6ac2e657dee997cb9129c7d0d4dde21b6) +++ src/libchcore/TBaseException.cpp (.../TBaseException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,74 +1,74 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TBaseException.h" -#include - -namespace chcore -{ - TBaseException::TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - m_eErrorCode(eErrorCode), - m_pszMsg(pszMsg), - m_bDeleteMsg(false), - m_pszFile(pszFile), - m_stLineNumber(stLineNumber), - m_pszFunction(pszFunction) - { - ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %s\n\tError code: %d\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); - } - - TBaseException::TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - m_eErrorCode(eErrorCode), - m_pszMsg(nullptr), - m_bDeleteMsg(false), - m_pszFile(pszFile), - m_stLineNumber(stLineNumber), - m_pszFunction(pszFunction) - { - ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %S\n\tError code: %d\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); - if (pszMsg) - { - size_t stMsgLen = strlen(pszMsg); - m_pszMsg = new wchar_t[stMsgLen + 1]; - - size_t stResult = 0; - mbstowcs_s(&stResult, const_cast(m_pszMsg), stMsgLen + 1, pszMsg, _TRUNCATE); - } - } - - TBaseException::~TBaseException() - { - if (m_bDeleteMsg) - delete[] m_pszMsg; - } - - void TBaseException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d)"), - m_pszMsg, m_eErrorCode); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } - - void TBaseException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), - m_pszMsg, m_eErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TBaseException.h" +#include + +namespace chcore +{ + TBaseException::TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + m_eErrorCode(eErrorCode), + m_pszMsg(pszMsg), + m_bDeleteMsg(false), + m_pszFile(pszFile), + m_stLineNumber(stLineNumber), + m_pszFunction(pszFunction) + { + ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %s\n\tError code: %d\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); + } + + TBaseException::TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + m_eErrorCode(eErrorCode), + m_pszMsg(nullptr), + m_bDeleteMsg(false), + m_pszFile(pszFile), + m_stLineNumber(stLineNumber), + m_pszFunction(pszFunction) + { + ATLTRACE(_T("*** Base Exception is being thrown:\n\tMsg: %S\n\tError code: %d\n\tFile: %s\n\tLine number: %ld\n\tFunction: %s\n"), pszMsg, eErrorCode, pszFile, stLineNumber, pszFunction); + if (pszMsg) + { + size_t stMsgLen = strlen(pszMsg); + m_pszMsg = new wchar_t[stMsgLen + 1]; + + size_t stResult = 0; + mbstowcs_s(&stResult, const_cast(m_pszMsg), stMsgLen + 1, pszMsg, _TRUNCATE); + } + } + + TBaseException::~TBaseException() + { + if (m_bDeleteMsg) + delete[] m_pszMsg; + } + + void TBaseException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d)"), + m_pszMsg, m_eErrorCode); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } + + void TBaseException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), + m_pszMsg, m_eErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } +} Index: src/libchcore/TBaseException.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TBaseException.h (.../TBaseException.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TBaseException.h (.../TBaseException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,68 +1,68 @@ -/*************************************************************************** -* Copyright (C) 2001-2013 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __TBASEEXCEPTION_H__ -#define __TBASEEXCEPTION_H__ - -#include "libchcore.h" -#include "ErrorCodes.h" - -#define LOCATION __FILEW__, __LINE__, __FUNCTIONW__ - -namespace chcore -{ -#pragma warning(push) -#pragma warning(disable: 4275) - class LIBCHCORE_API TBaseException : public virtual std::exception - { - public: - TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TBaseException() = delete; - - virtual ~TBaseException(); - - // error information - EGeneralErrors GetErrorCode() const { return m_eErrorCode; } - - virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - - private: - // location info - const wchar_t* GetSourceFile() const { return m_pszFile; } - size_t GetSourceLineNumber() const { return m_stLineNumber; } - const wchar_t* GetFunctionName() const { return m_pszFunction; } - - protected: - // what happened? - EGeneralErrors m_eErrorCode; - - // where it happened? - const wchar_t* m_pszMsg; - bool m_bDeleteMsg; - - const wchar_t* m_pszFile; - const wchar_t* m_pszFunction; - size_t m_stLineNumber; - }; - -#pragma warning(pop) -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2013 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __TBASEEXCEPTION_H__ +#define __TBASEEXCEPTION_H__ + +#include "libchcore.h" +#include "ErrorCodes.h" + +#define LOCATION __FILEW__, __LINE__, __FUNCTIONW__ + +namespace chcore +{ +#pragma warning(push) +#pragma warning(disable: 4275) + class LIBCHCORE_API TBaseException : public virtual std::exception + { + public: + TBaseException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TBaseException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TBaseException() = delete; + + virtual ~TBaseException(); + + // error information + EGeneralErrors GetErrorCode() const { return m_eErrorCode; } + + virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + + private: + // location info + const wchar_t* GetSourceFile() const { return m_pszFile; } + size_t GetSourceLineNumber() const { return m_stLineNumber; } + const wchar_t* GetFunctionName() const { return m_pszFunction; } + + protected: + // what happened? + EGeneralErrors m_eErrorCode; + + // where it happened? + const wchar_t* m_pszMsg; + bool m_bDeleteMsg; + + const wchar_t* m_pszFile; + const wchar_t* m_pszFunction; + size_t m_stLineNumber; + }; + +#pragma warning(pop) +} + +#endif Index: src/libchcore/TBasePathData.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TBasePathData.cpp (.../TBasePathData.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TBasePathData.cpp (.../TBasePathData.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,319 +1,319 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TBasePathData.cpp -/// @date 2010/10/13 -/// @brief Contains implementations of classes related to keeping path data. -// ============================================================================ -#include "stdafx.h" -#include "TBasePathData.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "ISerializerContainer.h" -#include "ISerializerRowData.h" -#include "TPathContainer.h" -#include -#include - -namespace chcore -{ - ////////////////////////////////////////////////////////////////////////////// - // TBasePathData - - TBasePathData::TBasePathData() : - m_oidObjectID(0), - m_pathSrc(m_setModifications), - m_bSkipFurtherProcessing(m_setModifications, false), - m_pathDst(m_setModifications) - { - m_setModifications[eMod_Added] = true; - } - - TBasePathData::TBasePathData(const TBasePathData& rEntry) : - m_oidObjectID(rEntry.m_oidObjectID), - m_pathSrc(m_setModifications, rEntry.m_pathSrc), - m_pathDst(m_setModifications, rEntry.m_pathDst), - m_bSkipFurtherProcessing(m_setModifications, rEntry.m_bSkipFurtherProcessing), - m_setModifications(rEntry.m_setModifications) - { - } - - TBasePathData::TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath) : - m_oidObjectID(oidObjectID), - m_pathSrc(m_setModifications, spSrcPath), - m_bSkipFurtherProcessing(m_setModifications, false), - m_pathDst(m_setModifications) - { - m_pathSrc.Modify().StripSeparatorAtEnd(); - m_setModifications[eMod_Added] = true; - } - - void TBasePathData::SetDestinationPath(const TSmartPath& tPath) - { - m_pathDst = tPath; - m_pathDst.Modify().StripSeparatorAtEnd(); - } - - TSmartPath TBasePathData::GetDestinationPath() const - { - return m_pathDst; - } - - bool TBasePathData::GetSkipFurtherProcessing() const - { - return m_bSkipFurtherProcessing; - } - - void TBasePathData::SetSkipFurtherProcessing(bool bSkipFurtherProcessing) - { - m_bSkipFurtherProcessing = bSkipFurtherProcessing; - } - - bool TBasePathData::IsDestinationPathSet() const - { - return !m_pathDst.Get().IsEmpty(); - } - - void TBasePathData::Store(const ISerializerContainerPtr& spContainer) const - { - if (!spContainer) - throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); - - bool bAdded = m_setModifications[eMod_Added]; - if (m_setModifications.any()) - { - ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); - if (bAdded || m_setModifications[eMod_SrcPath]) - rRow.SetValue(_T("src_path"), m_pathSrc); - if (bAdded || m_setModifications[eMod_SkipProcessing]) - rRow.SetValue(_T("skip_processing"), m_bSkipFurtherProcessing); - if (bAdded || m_setModifications[eMod_DstPath]) - rRow.SetValue(_T("dst_path"), m_pathDst); - - m_setModifications.reset(); - } - } - - void TBasePathData::InitColumns(IColumnsDefinition& rColumns) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("src_path"), IColumnsDefinition::eType_path); - rColumns.AddColumn(_T("skip_processing"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("dst_path"), IColumnsDefinition::eType_path); - } - - void TBasePathData::Load(const ISerializerRowReaderPtr& spRowReader) - { - spRowReader->GetValue(_T("id"), m_oidObjectID); - spRowReader->GetValue(_T("src_path"), m_pathSrc.Modify()); - spRowReader->GetValue(_T("skip_processing"), m_bSkipFurtherProcessing.Modify()); - spRowReader->GetValue(_T("dst_path"), m_pathDst.Modify()); - - m_pathSrc.Modify().StripSeparatorAtEnd(); - m_pathDst.Modify().StripSeparatorAtEnd(); - - m_setModifications.reset(); - } - - TSmartPath TBasePathData::GetSrcPath() const - { - return m_pathSrc; - } - - void TBasePathData::SetSrcPath(const TSmartPath& pathSrc) - { - m_pathSrc = pathSrc; - m_pathSrc.Modify().StripSeparatorAtEnd(); - } - - object_id_t TBasePathData::GetObjectID() const - { - return m_oidObjectID; - } - - void TBasePathData::SetObjectID(object_id_t oidObjectID) - { - m_oidObjectID = oidObjectID; - } - - ////////////////////////////////////////////////////////////////////////////// - // TBasePathDataContainer - - TBasePathDataContainer::TBasePathDataContainer() : - m_oidLastObjectID(0) - { - } - - TBasePathDataContainer::~TBasePathDataContainer() - { - // clear works with critical section to avoid destruction while item in use - Clear(); - } - - void TBasePathDataContainer::Store(const ISerializerContainerPtr& spContainer) const - { - if (!spContainer) - throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); - - boost::shared_lock lock(m_lock); - - InitColumns(spContainer); - - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); - - for(const TBasePathDataPtr& spEntry : m_vEntries) - { - spEntry->Store(spContainer); - } - } - - void TBasePathDataContainer::Load(const ISerializerContainerPtr& spContainer) - { - if (!spContainer) - throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); - - boost::unique_lock lock(m_lock); - m_setRemovedObjects.Clear(); - m_vEntries.clear(); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - while (spRowReader->Next()) - { - TBasePathDataPtr spPathData(new TBasePathData); - - spPathData->Load(spRowReader); - - m_vEntries.push_back(spPathData); - } - } - - void TBasePathDataContainer::Add(const TBasePathDataPtr& spEntry) - { - boost::unique_lock lock(m_lock); - spEntry->SetObjectID(++m_oidLastObjectID); - m_vEntries.push_back(spEntry); - } - - void TBasePathDataContainer::RemoveAt(file_count_t fcIndex) - { - boost::unique_lock lock(m_lock); - if (fcIndex >= m_vEntries.size()) - throw TCoreException(eErr_BoundsExceeded, L"fcIndex", LOCATION); - - m_setRemovedObjects.Add(m_vEntries[boost::numeric_cast(fcIndex)]->GetObjectID()); - m_vEntries.erase(m_vEntries.begin() + boost::numeric_cast(fcIndex)); - } - - TBasePathDataPtr TBasePathDataContainer::GetAt(file_count_t fcIndex) const - { - boost::shared_lock lock(m_lock); - return m_vEntries.at(boost::numeric_cast(fcIndex)); - } - - TBasePathDataPtr TBasePathDataContainer::FindByID(size_t stObjectID) const - { - boost::shared_lock lock(m_lock); - for(const TBasePathDataPtr& spItem : m_vEntries) - { - if (spItem->GetObjectID() == stObjectID) - return spItem; - } - - throw TCoreException(eErr_InvalidArgument, L"Object id does not exist", LOCATION); - } - - void TBasePathDataContainer::ClearNL() - { - for(const TBasePathDataPtr& spItem : m_vEntries) - { - m_setRemovedObjects.Add(spItem->GetObjectID()); - } - - m_vEntries.clear(); - } - - void TBasePathDataContainer::Clear() - { - boost::unique_lock lock(m_lock); - ClearNL(); - } - - bool TBasePathDataContainer::IsEmpty() const - { - boost::shared_lock lock(m_lock); - - return m_vEntries.empty(); - } - - file_count_t TBasePathDataContainer::GetCount() const - { - boost::shared_lock lock(m_lock); - return boost::numeric_cast(m_vEntries.size()); - } - - bool TBasePathDataContainer::AllMarkedAsSkipFurtherProcessing() const - { - boost::shared_lock lock(m_lock); - - for (const TBasePathDataPtr& spBasePath : m_vEntries) - { - if (!spBasePath->GetSkipFurtherProcessing()) - return false; - } - - return true; - } - - void TBasePathDataContainer::ResetProcessingFlags() - { - boost::unique_lock lock(m_lock); - - for(const TBasePathDataPtr& spBasePath : m_vEntries) - { - spBasePath->SetSkipFurtherProcessing(false); - } - } - - TBasePathDataContainer& TBasePathDataContainer::operator=(const TPathContainer& tPaths) - { - boost::unique_lock lock(m_lock); - ClearNL(); - - for (size_t stIndex = 0; stIndex < tPaths.GetCount(); ++stIndex) - { - TSmartPath path = tPaths.GetAt(stIndex); - path.StripSeparatorAtEnd(); - - TBasePathDataPtr spPathData = std::make_shared(++m_oidLastObjectID, path); - m_vEntries.push_back(spPathData); - } - - return *this; - } - - void TBasePathDataContainer::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - TBasePathData::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TBasePathData.cpp +/// @date 2010/10/13 +/// @brief Contains implementations of classes related to keeping path data. +// ============================================================================ +#include "stdafx.h" +#include "TBasePathData.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "ISerializerContainer.h" +#include "ISerializerRowData.h" +#include "TPathContainer.h" +#include +#include + +namespace chcore +{ + ////////////////////////////////////////////////////////////////////////////// + // TBasePathData + + TBasePathData::TBasePathData() : + m_oidObjectID(0), + m_pathSrc(m_setModifications), + m_bSkipFurtherProcessing(m_setModifications, false), + m_pathDst(m_setModifications) + { + m_setModifications[eMod_Added] = true; + } + + TBasePathData::TBasePathData(const TBasePathData& rEntry) : + m_oidObjectID(rEntry.m_oidObjectID), + m_pathSrc(m_setModifications, rEntry.m_pathSrc), + m_pathDst(m_setModifications, rEntry.m_pathDst), + m_bSkipFurtherProcessing(m_setModifications, rEntry.m_bSkipFurtherProcessing), + m_setModifications(rEntry.m_setModifications) + { + } + + TBasePathData::TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath) : + m_oidObjectID(oidObjectID), + m_pathSrc(m_setModifications, spSrcPath), + m_bSkipFurtherProcessing(m_setModifications, false), + m_pathDst(m_setModifications) + { + m_pathSrc.Modify().StripSeparatorAtEnd(); + m_setModifications[eMod_Added] = true; + } + + void TBasePathData::SetDestinationPath(const TSmartPath& tPath) + { + m_pathDst = tPath; + m_pathDst.Modify().StripSeparatorAtEnd(); + } + + TSmartPath TBasePathData::GetDestinationPath() const + { + return m_pathDst; + } + + bool TBasePathData::GetSkipFurtherProcessing() const + { + return m_bSkipFurtherProcessing; + } + + void TBasePathData::SetSkipFurtherProcessing(bool bSkipFurtherProcessing) + { + m_bSkipFurtherProcessing = bSkipFurtherProcessing; + } + + bool TBasePathData::IsDestinationPathSet() const + { + return !m_pathDst.Get().IsEmpty(); + } + + void TBasePathData::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); + + bool bAdded = m_setModifications[eMod_Added]; + if (m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); + if (bAdded || m_setModifications[eMod_SrcPath]) + rRow.SetValue(_T("src_path"), m_pathSrc); + if (bAdded || m_setModifications[eMod_SkipProcessing]) + rRow.SetValue(_T("skip_processing"), m_bSkipFurtherProcessing); + if (bAdded || m_setModifications[eMod_DstPath]) + rRow.SetValue(_T("dst_path"), m_pathDst); + + m_setModifications.reset(); + } + } + + void TBasePathData::InitColumns(IColumnsDefinition& rColumns) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("src_path"), IColumnsDefinition::eType_path); + rColumns.AddColumn(_T("skip_processing"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("dst_path"), IColumnsDefinition::eType_path); + } + + void TBasePathData::Load(const ISerializerRowReaderPtr& spRowReader) + { + spRowReader->GetValue(_T("id"), m_oidObjectID); + spRowReader->GetValue(_T("src_path"), m_pathSrc.Modify()); + spRowReader->GetValue(_T("skip_processing"), m_bSkipFurtherProcessing.Modify()); + spRowReader->GetValue(_T("dst_path"), m_pathDst.Modify()); + + m_pathSrc.Modify().StripSeparatorAtEnd(); + m_pathDst.Modify().StripSeparatorAtEnd(); + + m_setModifications.reset(); + } + + TSmartPath TBasePathData::GetSrcPath() const + { + return m_pathSrc; + } + + void TBasePathData::SetSrcPath(const TSmartPath& pathSrc) + { + m_pathSrc = pathSrc; + m_pathSrc.Modify().StripSeparatorAtEnd(); + } + + object_id_t TBasePathData::GetObjectID() const + { + return m_oidObjectID; + } + + void TBasePathData::SetObjectID(object_id_t oidObjectID) + { + m_oidObjectID = oidObjectID; + } + + ////////////////////////////////////////////////////////////////////////////// + // TBasePathDataContainer + + TBasePathDataContainer::TBasePathDataContainer() : + m_oidLastObjectID(0) + { + } + + TBasePathDataContainer::~TBasePathDataContainer() + { + // clear works with critical section to avoid destruction while item in use + Clear(); + } + + void TBasePathDataContainer::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); + + boost::shared_lock lock(m_lock); + + InitColumns(spContainer); + + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); + + for(const TBasePathDataPtr& spEntry : m_vEntries) + { + spEntry->Store(spContainer); + } + } + + void TBasePathDataContainer::Load(const ISerializerContainerPtr& spContainer) + { + if (!spContainer) + throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); + + boost::unique_lock lock(m_lock); + m_setRemovedObjects.Clear(); + m_vEntries.clear(); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + while (spRowReader->Next()) + { + TBasePathDataPtr spPathData(new TBasePathData); + + spPathData->Load(spRowReader); + + m_vEntries.push_back(spPathData); + } + } + + void TBasePathDataContainer::Add(const TBasePathDataPtr& spEntry) + { + boost::unique_lock lock(m_lock); + spEntry->SetObjectID(++m_oidLastObjectID); + m_vEntries.push_back(spEntry); + } + + void TBasePathDataContainer::RemoveAt(file_count_t fcIndex) + { + boost::unique_lock lock(m_lock); + if (fcIndex >= m_vEntries.size()) + throw TCoreException(eErr_BoundsExceeded, L"fcIndex", LOCATION); + + m_setRemovedObjects.Add(m_vEntries[boost::numeric_cast(fcIndex)]->GetObjectID()); + m_vEntries.erase(m_vEntries.begin() + boost::numeric_cast(fcIndex)); + } + + TBasePathDataPtr TBasePathDataContainer::GetAt(file_count_t fcIndex) const + { + boost::shared_lock lock(m_lock); + return m_vEntries.at(boost::numeric_cast(fcIndex)); + } + + TBasePathDataPtr TBasePathDataContainer::FindByID(size_t stObjectID) const + { + boost::shared_lock lock(m_lock); + for(const TBasePathDataPtr& spItem : m_vEntries) + { + if (spItem->GetObjectID() == stObjectID) + return spItem; + } + + throw TCoreException(eErr_InvalidArgument, L"Object id does not exist", LOCATION); + } + + void TBasePathDataContainer::ClearNL() + { + for(const TBasePathDataPtr& spItem : m_vEntries) + { + m_setRemovedObjects.Add(spItem->GetObjectID()); + } + + m_vEntries.clear(); + } + + void TBasePathDataContainer::Clear() + { + boost::unique_lock lock(m_lock); + ClearNL(); + } + + bool TBasePathDataContainer::IsEmpty() const + { + boost::shared_lock lock(m_lock); + + return m_vEntries.empty(); + } + + file_count_t TBasePathDataContainer::GetCount() const + { + boost::shared_lock lock(m_lock); + return boost::numeric_cast(m_vEntries.size()); + } + + bool TBasePathDataContainer::AllMarkedAsSkipFurtherProcessing() const + { + boost::shared_lock lock(m_lock); + + for (const TBasePathDataPtr& spBasePath : m_vEntries) + { + if (!spBasePath->GetSkipFurtherProcessing()) + return false; + } + + return true; + } + + void TBasePathDataContainer::ResetProcessingFlags() + { + boost::unique_lock lock(m_lock); + + for(const TBasePathDataPtr& spBasePath : m_vEntries) + { + spBasePath->SetSkipFurtherProcessing(false); + } + } + + TBasePathDataContainer& TBasePathDataContainer::operator=(const TPathContainer& tPaths) + { + boost::unique_lock lock(m_lock); + ClearNL(); + + for (size_t stIndex = 0; stIndex < tPaths.GetCount(); ++stIndex) + { + TSmartPath path = tPaths.GetAt(stIndex); + path.StripSeparatorAtEnd(); + + TBasePathDataPtr spPathData = std::make_shared(++m_oidLastObjectID, path); + m_vEntries.push_back(spPathData); + } + + return *this; + } + + void TBasePathDataContainer::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TBasePathData::InitColumns(rColumns); + } +} Index: src/libchcore/TBasePathData.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TBasePathData.h (.../TBasePathData.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TBasePathData.h (.../TBasePathData.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,147 +1,147 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TBasePathData.h -/// @date 2010/10/13 -/// @brief Contains declarations of classes related to keeping additional path data. -// ============================================================================ -#ifndef __TBASEPATHDATA_H__ -#define __TBASEPATHDATA_H__ - -#include "libchcore.h" -#include "TPath.h" -#include -#include "TSharedModificationTracker.h" -#include "TRemovedObjects.h" -#include "ISerializerRowData.h" -#include "IColumnsDefinition.h" -#include "ISerializerRowReader.h" -#include "CommonDataTypes.h" - -namespace chcore -{ - class TPathContainer; - - ///////////////////////////////////////////////////////////////////////////// - // TBasePathData - class LIBCHCORE_API TBasePathData - { - private: - enum EModifications - { - eMod_Added, - eMod_SrcPath, - eMod_SkipProcessing, - eMod_DstPath, - - eMod_Last - }; - - public: - TBasePathData(); - TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath); - TBasePathData(const TBasePathData& rEntry); - - object_id_t GetObjectID() const; - void SetObjectID(object_id_t oidObjectID); - - TSmartPath GetSrcPath() const; - void SetSrcPath(const TSmartPath& pathSrc); - - bool GetSkipFurtherProcessing() const; - void SetSkipFurtherProcessing(bool bSkipFurtherProcessing); - - void SetDestinationPath(const TSmartPath& strPath); - TSmartPath GetDestinationPath() const; - bool IsDestinationPathSet() const; - - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - // modification management - typedef std::bitset BitSet; - mutable BitSet m_setModifications; - - // attributes - object_id_t m_oidObjectID; - TSharedModificationTracker m_pathSrc; - TSharedModificationTracker m_bSkipFurtherProcessing; // specifies if the path should be (or not) processed further - TSharedModificationTracker m_pathDst; -#pragma warning(pop) - }; - - typedef std::shared_ptr TBasePathDataPtr; - - ////////////////////////////////////////////////////////////////////////// - // TBasePathDataContainer - - class LIBCHCORE_API TBasePathDataContainer - { - public: - // constructors/destructor - TBasePathDataContainer(); - ~TBasePathDataContainer(); - - TBasePathDataContainer& operator=(const TPathContainer& tPaths); - - // standard access to data - void Add(const TBasePathDataPtr& spEntry); - void RemoveAt(file_count_t fcIndex); - TBasePathDataPtr GetAt(file_count_t fcIndex) const; - TBasePathDataPtr FindByID(size_t fcObjectID) const; - - void Clear(); - - bool IsEmpty() const; - file_count_t GetCount() const; - - // processing flags - bool AllMarkedAsSkipFurtherProcessing() const; - void ResetProcessingFlags(); - - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - private: - TBasePathDataContainer(const TBasePathDataContainer& rSrc); - TBasePathDataContainer& operator=(const TBasePathDataContainer& rSrc); - - void ClearNL(); - - protected: -#pragma warning(push) -#pragma warning(disable: 4251) - typedef std::vector VecEntries; - VecEntries m_vEntries; - mutable TRemovedObjects m_setRemovedObjects; - - mutable boost::shared_mutex m_lock; -#pragma warning(pop) - object_id_t m_oidLastObjectID; - }; - - typedef std::shared_ptr TBasePathDataContainerPtr; -} - -#endif // __TBASEPATHDATA_H__ +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TBasePathData.h +/// @date 2010/10/13 +/// @brief Contains declarations of classes related to keeping additional path data. +// ============================================================================ +#ifndef __TBASEPATHDATA_H__ +#define __TBASEPATHDATA_H__ + +#include "libchcore.h" +#include "TPath.h" +#include +#include "TSharedModificationTracker.h" +#include "TRemovedObjects.h" +#include "ISerializerRowData.h" +#include "IColumnsDefinition.h" +#include "ISerializerRowReader.h" +#include "CommonDataTypes.h" + +namespace chcore +{ + class TPathContainer; + + ///////////////////////////////////////////////////////////////////////////// + // TBasePathData + class LIBCHCORE_API TBasePathData + { + private: + enum EModifications + { + eMod_Added, + eMod_SrcPath, + eMod_SkipProcessing, + eMod_DstPath, + + eMod_Last + }; + + public: + TBasePathData(); + TBasePathData(object_id_t oidObjectID, const TSmartPath& spSrcPath); + TBasePathData(const TBasePathData& rEntry); + + object_id_t GetObjectID() const; + void SetObjectID(object_id_t oidObjectID); + + TSmartPath GetSrcPath() const; + void SetSrcPath(const TSmartPath& pathSrc); + + bool GetSkipFurtherProcessing() const; + void SetSkipFurtherProcessing(bool bSkipFurtherProcessing); + + void SetDestinationPath(const TSmartPath& strPath); + TSmartPath GetDestinationPath() const; + bool IsDestinationPathSet() const; + + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + // modification management + typedef std::bitset BitSet; + mutable BitSet m_setModifications; + + // attributes + object_id_t m_oidObjectID; + TSharedModificationTracker m_pathSrc; + TSharedModificationTracker m_bSkipFurtherProcessing; // specifies if the path should be (or not) processed further + TSharedModificationTracker m_pathDst; +#pragma warning(pop) + }; + + typedef std::shared_ptr TBasePathDataPtr; + + ////////////////////////////////////////////////////////////////////////// + // TBasePathDataContainer + + class LIBCHCORE_API TBasePathDataContainer + { + public: + // constructors/destructor + TBasePathDataContainer(); + ~TBasePathDataContainer(); + + TBasePathDataContainer& operator=(const TPathContainer& tPaths); + + // standard access to data + void Add(const TBasePathDataPtr& spEntry); + void RemoveAt(file_count_t fcIndex); + TBasePathDataPtr GetAt(file_count_t fcIndex) const; + TBasePathDataPtr FindByID(size_t fcObjectID) const; + + void Clear(); + + bool IsEmpty() const; + file_count_t GetCount() const; + + // processing flags + bool AllMarkedAsSkipFurtherProcessing() const; + void ResetProcessingFlags(); + + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + private: + TBasePathDataContainer(const TBasePathDataContainer& rSrc); + TBasePathDataContainer& operator=(const TBasePathDataContainer& rSrc); + + void ClearNL(); + + protected: +#pragma warning(push) +#pragma warning(disable: 4251) + typedef std::vector VecEntries; + VecEntries m_vEntries; + mutable TRemovedObjects m_setRemovedObjects; + + mutable boost::shared_mutex m_lock; +#pragma warning(pop) + object_id_t m_oidLastObjectID; + }; + + typedef std::shared_ptr TBasePathDataContainerPtr; +} + +#endif // __TBASEPATHDATA_H__ Index: src/libchcore/TBasePathDataFwd.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TBasePathDataFwd.h (.../TBasePathDataFwd.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TBasePathDataFwd.h (.../TBasePathDataFwd.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,28 +1,28 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TBASEPATHDATAFWD_H__ -#define __TBASEPATHDATAFWD_H__ - -namespace chcore -{ - class TBasePathData; - typedef std::shared_ptr TBasePathDataPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TBASEPATHDATAFWD_H__ +#define __TBASEPATHDATAFWD_H__ + +namespace chcore +{ + class TBasePathData; + typedef std::shared_ptr TBasePathDataPtr; +} + +#endif Index: src/libchcore/TConfig.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfig.cpp (.../TConfig.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TConfig.cpp (.../TConfig.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,536 +1,536 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TConfig.cpp -/// @date 2010/09/27 -/// @brief Contains implementations of classes related to configuration handling. -// ============================================================================ -#include "stdafx.h" -#include "TConfig.h" -#include -#include -#include -#include "TConfigArray.h" - -#pragma warning(push) -#pragma warning(disable: 4702 4512) - #include -#pragma warning(pop) - -#include -#include -#include "TConfigNotifier.h" -#include "ConfigNodeContainer.h" -#include "ErrorCodes.h" -#include "TCoreException.h" -#include "ISerializerRowData.h" -#include - -namespace chcore -{ - ///////////////////////////////////////////////////////////////////////////////////////////// - // class TConfig - - using namespace details; - - TConfig::TConfig() : - m_pImpl(new details::ConfigNodeContainer) - { - } - - TConfig::TConfig(const TConfig& rSrc) : - m_pImpl(new details::ConfigNodeContainer(*rSrc.m_pImpl)) - { - } - - TConfig& TConfig::operator=(const TConfig& rSrc) - { - if (this != &rSrc) - *m_pImpl = *rSrc.m_pImpl; - - return *this; - } - - TConfig::~TConfig() - { - delete m_pImpl; - } - - // read/write - void TConfig::Read(PCTSTR pszFile) - { - if (!pszFile) - throw TCoreException(eErr_InvalidArgument, L"pszFile", LOCATION); - - { - boost::unique_lock lock(GetImpl()->m_lock); - // Note: we need to store filename for later use BEFORE trying to open a file - // since it might be nonexistent, but we still would like to store config to this file later - ClearNL(); - GetImpl()->m_strFilePath = pszFile; - } - - // convert our underlying data to a property tree (currently probably the easiest way to convert data to xml - boost::property_tree::wiptree tPropertyTree; - - std::wifstream ifs(pszFile, std::ios_base::in); - std::locale utf8bom(std::locale(), new std::codecvt_utf8); - ifs.imbue(utf8bom); - - boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); - - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); - } - - void TConfig::Write() - { - // NOTE: locking is done inside ExportToPropertyTree() - boost::property_tree::wiptree tPropertyTree; - GetImpl()->ExportToPropertyTree(tPropertyTree); - - std::wofstream ofs(GetImpl()->m_strFilePath.c_str(), std::ios_base::out); - - std::locale utf8bom(std::locale(), new std::codecvt_utf8); - ofs.imbue(utf8bom); - - boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); - } - - void TConfig::ReadFromString(const TString& strInput) - { - if (strInput.IsEmpty()) - throw TCoreException(eErr_InvalidArgument, L"pszFile", LOCATION); - - boost::property_tree::wiptree tPropertyTree; - - std::wistringstream ifs(strInput.c_str(), std::ios_base::in); - boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); - - boost::unique_lock lock(GetImpl()->m_lock); - - ClearNL(); - - GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); - } - - void TConfig::WriteToString(TString& strOutput) - { - // NOTE: locking is done inside ExportToPropertyTree() - - boost::property_tree::wiptree tPropertyTree; - GetImpl()->ExportToPropertyTree(tPropertyTree); - - std::wostringstream ofs(std::ios_base::out); - boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); - - strOutput = ofs.str().c_str(); - } - - - void TConfig::Store(const ISerializerContainerPtr& spContainer) const - { - if (!spContainer) - throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); - - boost::shared_lock lock(GetImpl()->m_lock); - - InitColumns(spContainer); - - spContainer->DeleteRows(m_pImpl->m_setRemovedObjects); - m_pImpl->m_setRemovedObjects.Clear(); - - for(const ConfigNode& rNode : m_pImpl->m_mic) - { - bool bAdded = rNode.m_setModifications[ConfigNode::eMod_Added]; - if (rNode.m_setModifications.any()) - { - ISerializerRowData& rRow = spContainer->GetRow(rNode.m_oidObjectID, bAdded); - if (bAdded || rNode.m_setModifications[ConfigNode::eMod_NodeName]) - rRow.SetValue(_T("name"), rNode.GetNodeName()); - if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Order]) - rRow.SetValue(_T("node_order"), rNode.GetOrder()); - if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Value]) - rRow.SetValue(_T("value"), rNode.m_strValue.Get()); - - rNode.m_setModifications.reset(); - } - } - } - - void TConfig::Load(const ISerializerContainerPtr& spContainer) const - { - if (!spContainer) - throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); - - boost::unique_lock lock(GetImpl()->m_lock); - m_pImpl->m_setRemovedObjects.Clear(); - m_pImpl->m_mic.clear(); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - while (spRowReader->Next()) - { - TString strName; - int iOrder = 0; - TString strValue; - - spRowReader->GetValue(_T("name"), strName); - spRowReader->GetValue(_T("node_order"), iOrder); - spRowReader->GetValue(_T("value"), strValue); - - m_pImpl->AddEntry(strName.c_str(), iOrder, strValue); // also resets modification state inside - } - } - - void TConfig::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("node_order"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("value"), IColumnsDefinition::eType_string); - } - } - - void TConfig::SetFilePath(PCTSTR pszPath) - { - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_strFilePath = pszPath; - } - - void TConfig::Clear() - { - boost::unique_lock lock(GetImpl()->m_lock); - - ClearNL(); - } - - void TConfig::ClearNL() - { - GetImpl()->m_mic.clear(); - GetImpl()->m_setDelayedNotifications.Clear(); - GetImpl()->m_bDelayedEnabled = false; - GetImpl()->m_strFilePath.Clear(); - } - - // value setting/retrieval - bool TConfig::GetBool(PCTSTR pszPropName, bool bDefault) const - { - return GetImpl()->GetValue(pszPropName, bDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, bool& bValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, bValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, bool bValue) - { - if (GetImpl()->SetValue(pszPropName, bValue)) - SendNotification(pszPropName); - - return *this; - } - - int TConfig::GetInt(PCTSTR pszPropName, int iDefault) const - { - return GetImpl()->GetValue(pszPropName, iDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, int& iValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, iValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, int iValue) - { - if (GetImpl()->SetValue(pszPropName, iValue)) - SendNotification(pszPropName); - - return *this; - } - - unsigned int TConfig::GetUInt(PCTSTR pszPropName, unsigned int uiDefault) const - { - return GetImpl()->GetValue(pszPropName, uiDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, unsigned int& uiValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, uiValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned int uiValue) - { - if (GetImpl()->SetValue(pszPropName, uiValue)) - SendNotification(pszPropName); - - return *this; - } - - long long TConfig::GetLongLong(PCTSTR pszPropName, long long llDefault) const - { - return GetImpl()->GetValue(pszPropName, llDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, long long& llValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, llValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, long long llValue) - { - if (GetImpl()->SetValue(pszPropName, llValue)) - SendNotification(pszPropName); - - return *this; - } - - unsigned long long TConfig::GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault) const - { - return GetImpl()->GetValue(pszPropName, ullDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, ullValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned long long ullValue) - { - if (GetImpl()->SetValue(pszPropName, ullValue)) - SendNotification(pszPropName); - - return *this; - } - - double TConfig::GetDouble(PCTSTR pszPropName, double dDefault) const - { - return GetImpl()->GetValue(pszPropName, dDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, double& dValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, dValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, double dValue) - { - if (GetImpl()->SetValue(pszPropName, dValue)) - SendNotification(pszPropName); - - return *this; - } - - TString TConfig::GetString(PCTSTR pszPropName, const TString& strDefault) const - { - return GetImpl()->GetValue(pszPropName, strDefault); - } - - bool TConfig::GetValue(PCTSTR pszPropName, TString& rstrValue) const - { - return GetImpl()->GetValueNoDefault(pszPropName, rstrValue); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, const TString& strValue) - { - if (GetImpl()->SetValue(pszPropName, strValue)) - SendNotification(pszPropName); - - return *this; - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, PCTSTR pszValue) - { - return SetValue(pszPropName, TString(pszValue)); - } - - bool TConfig::GetValue(PCTSTR pszPropName, TStringArray& rvValues) const - { - return GetImpl()->GetArrayValueNoDefault(pszPropName, rvValues); - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, const TStringArray& rvValues) - { - if (GetImpl()->SetArrayValue(pszPropName, rvValues)) - SendNotification(pszPropName); - - return *this; - } - - void TConfig::DeleteNode(PCTSTR pszNodeName) - { - GetImpl()->DeleteNode(pszNodeName); - } - - // extraction of subtrees - bool TConfig::ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const - { - return GetImpl()->ExtractNodes(pszSubTreeName, *rSubConfig.m_pImpl); - } - - bool TConfig::ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const - { - rSubConfigs.Clear(); - - std::vector vNodeContainers; - if (!GetImpl()->ExtractMultipleNodes(pszSubTreeName, vNodeContainers)) - return false; - - for(const ConfigNodeContainer& rNode : vNodeContainers) - { - TConfig cfg; - *cfg.m_pImpl = rNode; - - rSubConfigs.Add(cfg); - } - - return true; - } - - void TConfig::PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) - { - GetImpl()->ImportNodes(pszSubTreeName, *rSubConfig.m_pImpl); - } - - void TConfig::AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) - { - GetImpl()->AddNodes(pszSubTreeName, *rSubConfig.m_pImpl); - } - - void TConfig::ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) - { - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_notifier.connect(TConfigNotifier(pfnCallback, pParam)); - } - - void TConfig::DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)) - { - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_notifier.disconnect(TConfigNotifier(pfnCallback, nullptr)); - } - - void TConfig::DelayNotifications() - { - boost::unique_lock lock(GetImpl()->m_lock); - GetImpl()->m_bDelayedEnabled = true; - } - - void TConfig::ResumeNotifications() - { - TStringSet setNotifications; - - // separate scope for shared mutex (to avoid calling notifier inside critical section) - { - boost::upgrade_lock lock(GetImpl()->m_lock); - if (GetImpl()->m_bDelayedEnabled) - { - GetImpl()->m_bDelayedEnabled = false; - if (!GetImpl()->m_setDelayedNotifications.IsEmpty()) - { - setNotifications = GetImpl()->m_setDelayedNotifications; - - boost::upgrade_to_unique_lock upgraded_lock(lock); - GetImpl()->m_setDelayedNotifications.Clear(); - } - } - } - - // NOTE: no locking here! - if (!setNotifications.IsEmpty()) - SendNotification(setNotifications); - } - - void TConfig::SendNotification(const TStringSet& rsetInfo) - { - // separate scope for shared mutex (to avoid calling notifier inside critical section) - { - boost::upgrade_lock lock(GetImpl()->m_lock); - if (GetImpl()->m_bDelayedEnabled) - { - boost::upgrade_to_unique_lock upgraded_lock(lock); - - GetImpl()->m_setDelayedNotifications.Insert(rsetInfo); - return; - } - } - - // NOTE: we don't lock here - GetImpl()->m_notifier(rsetInfo); - } - - void TConfig::SendNotification(PCTSTR pszInfo) - { - // separate scope for shared mutex (to avoid calling notifier inside critical section) - { - boost::upgrade_lock lock(GetImpl()->m_lock); - if (GetImpl()->m_bDelayedEnabled) - { - boost::upgrade_to_unique_lock upgraded_lock(lock); - - GetImpl()->m_setDelayedNotifications.Insert(pszInfo); - return; - } - } - - // NOTE: we don't lock here - TStringSet setData; - setData.Insert(pszInfo); - GetImpl()->m_notifier(setData); - } - - details::ConfigNodeContainer* TConfig::GetImpl() - { - return m_pImpl; - } - - const details::ConfigNodeContainer* TConfig::GetImpl() const - { - return m_pImpl; - } - - TSmartPath TConfig::GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault) const - { - return PathFromWString(GetString(pszPropName, pathDefault.ToWString())); - } - - bool TConfig::GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const - { - TString strPath; - bool bResult = GetValue(pszPropName, strPath); - rpathValue = PathFromWString(strPath); - return bResult; - } - - TConfig& TConfig::SetValue(PCTSTR pszPropName, const TSmartPath& pathValue) - { - return SetValue(pszPropName, pathValue.ToWString()); - } - -#ifdef _DEBUG - void TConfig::Dump() - { - GetImpl()->Dump(); - } -#endif -} +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TConfig.cpp +/// @date 2010/09/27 +/// @brief Contains implementations of classes related to configuration handling. +// ============================================================================ +#include "stdafx.h" +#include "TConfig.h" +#include +#include +#include +#include "TConfigArray.h" + +#pragma warning(push) +#pragma warning(disable: 4702 4512) + #include +#pragma warning(pop) + +#include +#include +#include "TConfigNotifier.h" +#include "ConfigNodeContainer.h" +#include "ErrorCodes.h" +#include "TCoreException.h" +#include "ISerializerRowData.h" +#include + +namespace chcore +{ + ///////////////////////////////////////////////////////////////////////////////////////////// + // class TConfig + + using namespace details; + + TConfig::TConfig() : + m_pImpl(new details::ConfigNodeContainer) + { + } + + TConfig::TConfig(const TConfig& rSrc) : + m_pImpl(new details::ConfigNodeContainer(*rSrc.m_pImpl)) + { + } + + TConfig& TConfig::operator=(const TConfig& rSrc) + { + if (this != &rSrc) + *m_pImpl = *rSrc.m_pImpl; + + return *this; + } + + TConfig::~TConfig() + { + delete m_pImpl; + } + + // read/write + void TConfig::Read(PCTSTR pszFile) + { + if (!pszFile) + throw TCoreException(eErr_InvalidArgument, L"pszFile", LOCATION); + + { + boost::unique_lock lock(GetImpl()->m_lock); + // Note: we need to store filename for later use BEFORE trying to open a file + // since it might be nonexistent, but we still would like to store config to this file later + ClearNL(); + GetImpl()->m_strFilePath = pszFile; + } + + // convert our underlying data to a property tree (currently probably the easiest way to convert data to xml + boost::property_tree::wiptree tPropertyTree; + + std::wifstream ifs(pszFile, std::ios_base::in); + std::locale utf8bom(std::locale(), new std::codecvt_utf8); + ifs.imbue(utf8bom); + + boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); + + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); + } + + void TConfig::Write() + { + // NOTE: locking is done inside ExportToPropertyTree() + boost::property_tree::wiptree tPropertyTree; + GetImpl()->ExportToPropertyTree(tPropertyTree); + + std::wofstream ofs(GetImpl()->m_strFilePath.c_str(), std::ios_base::out); + + std::locale utf8bom(std::locale(), new std::codecvt_utf8); + ofs.imbue(utf8bom); + + boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); + } + + void TConfig::ReadFromString(const TString& strInput) + { + if (strInput.IsEmpty()) + throw TCoreException(eErr_InvalidArgument, L"pszFile", LOCATION); + + boost::property_tree::wiptree tPropertyTree; + + std::wistringstream ifs(strInput.c_str(), std::ios_base::in); + boost::property_tree::xml_parser::read_xml(ifs, tPropertyTree); + + boost::unique_lock lock(GetImpl()->m_lock); + + ClearNL(); + + GetImpl()->ImportFromPropertyTree(tPropertyTree, lock); + } + + void TConfig::WriteToString(TString& strOutput) + { + // NOTE: locking is done inside ExportToPropertyTree() + + boost::property_tree::wiptree tPropertyTree; + GetImpl()->ExportToPropertyTree(tPropertyTree); + + std::wostringstream ofs(std::ios_base::out); + boost::property_tree::xml_parser::write_xml(ofs, tPropertyTree); + + strOutput = ofs.str().c_str(); + } + + + void TConfig::Store(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); + + boost::shared_lock lock(GetImpl()->m_lock); + + InitColumns(spContainer); + + spContainer->DeleteRows(m_pImpl->m_setRemovedObjects); + m_pImpl->m_setRemovedObjects.Clear(); + + for(const ConfigNode& rNode : m_pImpl->m_mic) + { + bool bAdded = rNode.m_setModifications[ConfigNode::eMod_Added]; + if (rNode.m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(rNode.m_oidObjectID, bAdded); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_NodeName]) + rRow.SetValue(_T("name"), rNode.GetNodeName()); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Order]) + rRow.SetValue(_T("node_order"), rNode.GetOrder()); + if (bAdded || rNode.m_setModifications[ConfigNode::eMod_Value]) + rRow.SetValue(_T("value"), rNode.m_strValue.Get()); + + rNode.m_setModifications.reset(); + } + } + } + + void TConfig::Load(const ISerializerContainerPtr& spContainer) const + { + if (!spContainer) + throw TCoreException(eErr_InvalidPointer, L"spContainer", LOCATION); + + boost::unique_lock lock(GetImpl()->m_lock); + m_pImpl->m_setRemovedObjects.Clear(); + m_pImpl->m_mic.clear(); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + while (spRowReader->Next()) + { + TString strName; + int iOrder = 0; + TString strValue; + + spRowReader->GetValue(_T("name"), strName); + spRowReader->GetValue(_T("node_order"), iOrder); + spRowReader->GetValue(_T("value"), strValue); + + m_pImpl->AddEntry(strName.c_str(), iOrder, strValue); // also resets modification state inside + } + } + + void TConfig::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("node_order"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("value"), IColumnsDefinition::eType_string); + } + } + + void TConfig::SetFilePath(PCTSTR pszPath) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_strFilePath = pszPath; + } + + void TConfig::Clear() + { + boost::unique_lock lock(GetImpl()->m_lock); + + ClearNL(); + } + + void TConfig::ClearNL() + { + GetImpl()->m_mic.clear(); + GetImpl()->m_setDelayedNotifications.Clear(); + GetImpl()->m_bDelayedEnabled = false; + GetImpl()->m_strFilePath.Clear(); + } + + // value setting/retrieval + bool TConfig::GetBool(PCTSTR pszPropName, bool bDefault) const + { + return GetImpl()->GetValue(pszPropName, bDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, bool& bValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, bValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, bool bValue) + { + if (GetImpl()->SetValue(pszPropName, bValue)) + SendNotification(pszPropName); + + return *this; + } + + int TConfig::GetInt(PCTSTR pszPropName, int iDefault) const + { + return GetImpl()->GetValue(pszPropName, iDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, int& iValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, iValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, int iValue) + { + if (GetImpl()->SetValue(pszPropName, iValue)) + SendNotification(pszPropName); + + return *this; + } + + unsigned int TConfig::GetUInt(PCTSTR pszPropName, unsigned int uiDefault) const + { + return GetImpl()->GetValue(pszPropName, uiDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, unsigned int& uiValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, uiValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned int uiValue) + { + if (GetImpl()->SetValue(pszPropName, uiValue)) + SendNotification(pszPropName); + + return *this; + } + + long long TConfig::GetLongLong(PCTSTR pszPropName, long long llDefault) const + { + return GetImpl()->GetValue(pszPropName, llDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, long long& llValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, llValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, long long llValue) + { + if (GetImpl()->SetValue(pszPropName, llValue)) + SendNotification(pszPropName); + + return *this; + } + + unsigned long long TConfig::GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault) const + { + return GetImpl()->GetValue(pszPropName, ullDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, ullValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, unsigned long long ullValue) + { + if (GetImpl()->SetValue(pszPropName, ullValue)) + SendNotification(pszPropName); + + return *this; + } + + double TConfig::GetDouble(PCTSTR pszPropName, double dDefault) const + { + return GetImpl()->GetValue(pszPropName, dDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, double& dValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, dValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, double dValue) + { + if (GetImpl()->SetValue(pszPropName, dValue)) + SendNotification(pszPropName); + + return *this; + } + + TString TConfig::GetString(PCTSTR pszPropName, const TString& strDefault) const + { + return GetImpl()->GetValue(pszPropName, strDefault); + } + + bool TConfig::GetValue(PCTSTR pszPropName, TString& rstrValue) const + { + return GetImpl()->GetValueNoDefault(pszPropName, rstrValue); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TString& strValue) + { + if (GetImpl()->SetValue(pszPropName, strValue)) + SendNotification(pszPropName); + + return *this; + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, PCTSTR pszValue) + { + return SetValue(pszPropName, TString(pszValue)); + } + + bool TConfig::GetValue(PCTSTR pszPropName, TStringArray& rvValues) const + { + return GetImpl()->GetArrayValueNoDefault(pszPropName, rvValues); + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TStringArray& rvValues) + { + if (GetImpl()->SetArrayValue(pszPropName, rvValues)) + SendNotification(pszPropName); + + return *this; + } + + void TConfig::DeleteNode(PCTSTR pszNodeName) + { + GetImpl()->DeleteNode(pszNodeName); + } + + // extraction of subtrees + bool TConfig::ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const + { + return GetImpl()->ExtractNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } + + bool TConfig::ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const + { + rSubConfigs.Clear(); + + std::vector vNodeContainers; + if (!GetImpl()->ExtractMultipleNodes(pszSubTreeName, vNodeContainers)) + return false; + + for(const ConfigNodeContainer& rNode : vNodeContainers) + { + TConfig cfg; + *cfg.m_pImpl = rNode; + + rSubConfigs.Add(cfg); + } + + return true; + } + + void TConfig::PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) + { + GetImpl()->ImportNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } + + void TConfig::AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig) + { + GetImpl()->AddNodes(pszSubTreeName, *rSubConfig.m_pImpl); + } + + void TConfig::ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_notifier.connect(TConfigNotifier(pfnCallback, pParam)); + } + + void TConfig::DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)) + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_notifier.disconnect(TConfigNotifier(pfnCallback, nullptr)); + } + + void TConfig::DelayNotifications() + { + boost::unique_lock lock(GetImpl()->m_lock); + GetImpl()->m_bDelayedEnabled = true; + } + + void TConfig::ResumeNotifications() + { + TStringSet setNotifications; + + // separate scope for shared mutex (to avoid calling notifier inside critical section) + { + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) + { + GetImpl()->m_bDelayedEnabled = false; + if (!GetImpl()->m_setDelayedNotifications.IsEmpty()) + { + setNotifications = GetImpl()->m_setDelayedNotifications; + + boost::upgrade_to_unique_lock upgraded_lock(lock); + GetImpl()->m_setDelayedNotifications.Clear(); + } + } + } + + // NOTE: no locking here! + if (!setNotifications.IsEmpty()) + SendNotification(setNotifications); + } + + void TConfig::SendNotification(const TStringSet& rsetInfo) + { + // separate scope for shared mutex (to avoid calling notifier inside critical section) + { + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + + GetImpl()->m_setDelayedNotifications.Insert(rsetInfo); + return; + } + } + + // NOTE: we don't lock here + GetImpl()->m_notifier(rsetInfo); + } + + void TConfig::SendNotification(PCTSTR pszInfo) + { + // separate scope for shared mutex (to avoid calling notifier inside critical section) + { + boost::upgrade_lock lock(GetImpl()->m_lock); + if (GetImpl()->m_bDelayedEnabled) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + + GetImpl()->m_setDelayedNotifications.Insert(pszInfo); + return; + } + } + + // NOTE: we don't lock here + TStringSet setData; + setData.Insert(pszInfo); + GetImpl()->m_notifier(setData); + } + + details::ConfigNodeContainer* TConfig::GetImpl() + { + return m_pImpl; + } + + const details::ConfigNodeContainer* TConfig::GetImpl() const + { + return m_pImpl; + } + + TSmartPath TConfig::GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault) const + { + return PathFromWString(GetString(pszPropName, pathDefault.ToWString())); + } + + bool TConfig::GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const + { + TString strPath; + bool bResult = GetValue(pszPropName, strPath); + rpathValue = PathFromWString(strPath); + return bResult; + } + + TConfig& TConfig::SetValue(PCTSTR pszPropName, const TSmartPath& pathValue) + { + return SetValue(pszPropName, pathValue.ToWString()); + } + +#ifdef _DEBUG + void TConfig::Dump() + { + GetImpl()->Dump(); + } +#endif +} Index: src/libchcore/TConfig.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfig.h (.../TConfig.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TConfig.h (.../TConfig.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,206 +1,206 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TConfig.h -/// @date 2010/09/27 -/// @brief Contains declaration of classes related to configuration handling. -// ============================================================================ -#ifndef __TCONFIG_H__ -#define __TCONFIG_H__ - -#include "libchcore.h" -#include "ISerializerContainer.h" - -namespace chcore -{ - class TConfigArray; - class TStringSet; - - namespace details - { - struct ConfigNodeContainer; - } - - // class for handling configuration settings - class LIBCHCORE_API TConfig - { - public: - TConfig(); - TConfig(const TConfig& rSrc); - ~TConfig(); - - TConfig& operator=(const TConfig& rSrc); - - void Clear(); - - // read/write - void Read(PCTSTR pszFile); - void Write(); - void SetFilePath(PCTSTR pszPath); - - void ReadFromString(const TString& strInput); - void WriteToString(TString& strOutput); - - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer) const; - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - // value setting/retrieval - bool GetBool(PCTSTR pszPropName, bool bDefault = false) const; - bool GetValue(PCTSTR pszPropName, bool& bValue) const; - TConfig& SetValue(PCTSTR pszPropName, bool bValue); - - int GetInt(PCTSTR pszPropName, int iDefault = 0) const; - bool GetValue(PCTSTR pszPropName, int& iValue) const; - TConfig& SetValue(PCTSTR pszPropName, int iValue); - - unsigned int GetUInt(PCTSTR pszPropName, unsigned int uiDefault = 0) const; - bool GetValue(PCTSTR pszPropName, unsigned int& uiValue) const; - TConfig& SetValue(PCTSTR pszPropName, unsigned int uiValue); - - long long GetLongLong(PCTSTR pszPropName, long long llDefault = 0) const; - bool GetValue(PCTSTR pszPropName, long long& llValue) const; - TConfig& SetValue(PCTSTR pszPropName, long long llValue); - - unsigned long long GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault = 0) const; - bool GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const; - TConfig& SetValue(PCTSTR pszPropName, unsigned long long ullValue); - - double GetDouble(PCTSTR pszPropName, double dDefault = 0.0) const; - bool GetValue(PCTSTR pszPropName, double& dValue) const; - TConfig& SetValue(PCTSTR pszPropName, double dValue); - - TString GetString(PCTSTR pszPropName, const TString& strDefault = TString()) const; - bool GetValue(PCTSTR pszPropName, TString& rstrValue) const; - TConfig& SetValue(PCTSTR pszPropName, const TString& strValue); - TConfig& SetValue(PCTSTR pszPropName, PCTSTR pszValue); - - TSmartPath GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault = TSmartPath()) const; - bool GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const; - TConfig& SetValue(PCTSTR pszPropName, const TSmartPath& pathValue); - - bool GetValue(PCTSTR pszPropName, TStringArray& rvValues) const; - TConfig& SetValue(PCTSTR pszPropName, const TStringArray& rvValues); - - void DeleteNode(PCTSTR pszNodeName); - - // extraction of subtrees - bool ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const; - bool ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const; - void PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); - void AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); - - // property change notification - void ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); - void DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)); - - void DelayNotifications(); - void ResumeNotifications(); - -#ifdef _DEBUG - void Dump(); -#endif - - protected: - void SendNotification(const TStringSet& rsetInfo); - void SendNotification(PCTSTR pszInfo); - - void ClearNL(); - - private: - details::ConfigNodeContainer* GetImpl(); - const details::ConfigNodeContainer* GetImpl() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - details::ConfigNodeContainer* m_pImpl; -#pragma warning(pop) - }; - - template - inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const Type& rValue) - { - rConfig.SetValue(pszPropName, rValue); - } - - template - inline Type GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const Type& rDefault) - { - Type tValue; - if (!rConfig.GetValue(pszPropName, tValue)) - tValue = rDefault; - return tValue; - } - - template - inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, Type& rValue) - { - return rConfig.GetValue(pszPropName, rValue); - } - -#define CONFIG_MEMBER_SERIALIZATION(cls)\ - namespace chcore {\ - template<>\ - inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const cls& rValue)\ - {\ - rValue.StoreInConfig(rConfig, pszPropName);\ - }\ -\ - template<>\ - inline cls GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const cls& rDefault)\ - {\ - cls tValue;\ - if(!tValue.ReadFromConfig(rConfig, pszPropName))\ - tValue = rDefault;\ - return tValue;\ - }\ -\ - template<>\ - inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, cls& rValue)\ - {\ - return rValue.ReadFromConfig(rConfig, pszPropName);\ - }\ - } - -#define CONFIG_STANDALONE_SERIALIZATION(cls)\ - namespace chcore {\ - template<>\ - inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const cls& rValue)\ - {\ - StoreInConfig(rValue, rConfig, pszPropName);\ - }\ -\ - template<>\ - inline cls GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const cls& rDefault)\ - {\ - cls tValue;\ - if(!ReadFromConfig(tValue, rConfig, pszPropName))\ - tValue = rDefault;\ - return tValue;\ - }\ -\ - template<>\ - inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, cls& rValue)\ - {\ - return ReadFromConfig(rValue, rConfig, pszPropName);\ - }\ - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TConfig.h +/// @date 2010/09/27 +/// @brief Contains declaration of classes related to configuration handling. +// ============================================================================ +#ifndef __TCONFIG_H__ +#define __TCONFIG_H__ + +#include "libchcore.h" +#include "ISerializerContainer.h" + +namespace chcore +{ + class TConfigArray; + class TStringSet; + + namespace details + { + struct ConfigNodeContainer; + } + + // class for handling configuration settings + class LIBCHCORE_API TConfig + { + public: + TConfig(); + TConfig(const TConfig& rSrc); + ~TConfig(); + + TConfig& operator=(const TConfig& rSrc); + + void Clear(); + + // read/write + void Read(PCTSTR pszFile); + void Write(); + void SetFilePath(PCTSTR pszPath); + + void ReadFromString(const TString& strInput); + void WriteToString(TString& strOutput); + + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer) const; + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + // value setting/retrieval + bool GetBool(PCTSTR pszPropName, bool bDefault = false) const; + bool GetValue(PCTSTR pszPropName, bool& bValue) const; + TConfig& SetValue(PCTSTR pszPropName, bool bValue); + + int GetInt(PCTSTR pszPropName, int iDefault = 0) const; + bool GetValue(PCTSTR pszPropName, int& iValue) const; + TConfig& SetValue(PCTSTR pszPropName, int iValue); + + unsigned int GetUInt(PCTSTR pszPropName, unsigned int uiDefault = 0) const; + bool GetValue(PCTSTR pszPropName, unsigned int& uiValue) const; + TConfig& SetValue(PCTSTR pszPropName, unsigned int uiValue); + + long long GetLongLong(PCTSTR pszPropName, long long llDefault = 0) const; + bool GetValue(PCTSTR pszPropName, long long& llValue) const; + TConfig& SetValue(PCTSTR pszPropName, long long llValue); + + unsigned long long GetULongLong(PCTSTR pszPropName, unsigned long long ullDefault = 0) const; + bool GetValue(PCTSTR pszPropName, unsigned long long& ullValue) const; + TConfig& SetValue(PCTSTR pszPropName, unsigned long long ullValue); + + double GetDouble(PCTSTR pszPropName, double dDefault = 0.0) const; + bool GetValue(PCTSTR pszPropName, double& dValue) const; + TConfig& SetValue(PCTSTR pszPropName, double dValue); + + TString GetString(PCTSTR pszPropName, const TString& strDefault = TString()) const; + bool GetValue(PCTSTR pszPropName, TString& rstrValue) const; + TConfig& SetValue(PCTSTR pszPropName, const TString& strValue); + TConfig& SetValue(PCTSTR pszPropName, PCTSTR pszValue); + + TSmartPath GetPath(PCTSTR pszPropName, const TSmartPath& pathDefault = TSmartPath()) const; + bool GetValue(PCTSTR pszPropName, TSmartPath& rpathValue) const; + TConfig& SetValue(PCTSTR pszPropName, const TSmartPath& pathValue); + + bool GetValue(PCTSTR pszPropName, TStringArray& rvValues) const; + TConfig& SetValue(PCTSTR pszPropName, const TStringArray& rvValues); + + void DeleteNode(PCTSTR pszNodeName); + + // extraction of subtrees + bool ExtractSubConfig(PCTSTR pszSubTreeName, TConfig& rSubConfig) const; + bool ExtractMultiSubConfigs(PCTSTR pszSubTreeName, TConfigArray& rSubConfigs) const; + void PutSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); + void AddSubConfig(PCTSTR pszSubTreeName, const TConfig& rSubConfig); + + // property change notification + void ConnectToNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); + void DisconnectFromNotifier(void(*pfnCallback)(const TStringSet&, void*)); + + void DelayNotifications(); + void ResumeNotifications(); + +#ifdef _DEBUG + void Dump(); +#endif + + protected: + void SendNotification(const TStringSet& rsetInfo); + void SendNotification(PCTSTR pszInfo); + + void ClearNL(); + + private: + details::ConfigNodeContainer* GetImpl(); + const details::ConfigNodeContainer* GetImpl() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + details::ConfigNodeContainer* m_pImpl; +#pragma warning(pop) + }; + + template + inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const Type& rValue) + { + rConfig.SetValue(pszPropName, rValue); + } + + template + inline Type GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const Type& rDefault) + { + Type tValue; + if (!rConfig.GetValue(pszPropName, tValue)) + tValue = rDefault; + return tValue; + } + + template + inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, Type& rValue) + { + return rConfig.GetValue(pszPropName, rValue); + } + +#define CONFIG_MEMBER_SERIALIZATION(cls)\ + namespace chcore {\ + template<>\ + inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const cls& rValue)\ + {\ + rValue.StoreInConfig(rConfig, pszPropName);\ + }\ +\ + template<>\ + inline cls GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const cls& rDefault)\ + {\ + cls tValue;\ + if(!tValue.ReadFromConfig(rConfig, pszPropName))\ + tValue = rDefault;\ + return tValue;\ + }\ +\ + template<>\ + inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, cls& rValue)\ + {\ + return rValue.ReadFromConfig(rConfig, pszPropName);\ + }\ + } + +#define CONFIG_STANDALONE_SERIALIZATION(cls)\ + namespace chcore {\ + template<>\ + inline void SetConfigValue(TConfig& rConfig, PCTSTR pszPropName, const cls& rValue)\ + {\ + StoreInConfig(rValue, rConfig, pszPropName);\ + }\ +\ + template<>\ + inline cls GetConfigValueDef(const TConfig& rConfig, PCTSTR pszPropName, const cls& rDefault)\ + {\ + cls tValue;\ + if(!ReadFromConfig(tValue, rConfig, pszPropName))\ + tValue = rDefault;\ + return tValue;\ + }\ +\ + template<>\ + inline bool GetConfigValue(const TConfig& rConfig, PCTSTR pszPropName, cls& rValue)\ + {\ + return ReadFromConfig(rValue, rConfig, pszPropName);\ + }\ + } +} + +#endif Index: src/libchcore/TConfigArray.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfigArray.cpp (.../TConfigArray.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TConfigArray.cpp (.../TConfigArray.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,84 +1,84 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TConfigArray.h" - -namespace chcore -{ - ///////////////////////////////////////////////////////////////////////////////////////////// - // class TConfigArray - - TConfigArray::TConfigArray() - { - } - - TConfigArray::TConfigArray(const TConfigArray& rSrc) : - m_vConfigs(rSrc.m_vConfigs) - { - } - - TConfigArray::~TConfigArray() - { - } - - TConfigArray& TConfigArray::operator=(const TConfigArray& rSrc) - { - if (this != &rSrc) - { - m_vConfigs = rSrc.m_vConfigs; - } - - return *this; - } - - size_t TConfigArray::GetCount() const - { - return m_vConfigs.size(); - } - - bool TConfigArray::IsEmpty() const - { - return m_vConfigs.empty(); - } - - const TConfig& TConfigArray::GetAt(size_t stIndex) const - { - return m_vConfigs[stIndex]; - } - - TConfig& TConfigArray::GetAt(size_t stIndex) - { - return m_vConfigs[stIndex]; - } - - void TConfigArray::Add(const TConfig& rSrc) - { - m_vConfigs.push_back(rSrc); - } - - void TConfigArray::RemoveAt(size_t stIndex) - { - m_vConfigs.erase(m_vConfigs.begin() + stIndex); - } - - void TConfigArray::Clear() - { - m_vConfigs.clear(); - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TConfigArray.h" + +namespace chcore +{ + ///////////////////////////////////////////////////////////////////////////////////////////// + // class TConfigArray + + TConfigArray::TConfigArray() + { + } + + TConfigArray::TConfigArray(const TConfigArray& rSrc) : + m_vConfigs(rSrc.m_vConfigs) + { + } + + TConfigArray::~TConfigArray() + { + } + + TConfigArray& TConfigArray::operator=(const TConfigArray& rSrc) + { + if (this != &rSrc) + { + m_vConfigs = rSrc.m_vConfigs; + } + + return *this; + } + + size_t TConfigArray::GetCount() const + { + return m_vConfigs.size(); + } + + bool TConfigArray::IsEmpty() const + { + return m_vConfigs.empty(); + } + + const TConfig& TConfigArray::GetAt(size_t stIndex) const + { + return m_vConfigs[stIndex]; + } + + TConfig& TConfigArray::GetAt(size_t stIndex) + { + return m_vConfigs[stIndex]; + } + + void TConfigArray::Add(const TConfig& rSrc) + { + m_vConfigs.push_back(rSrc); + } + + void TConfigArray::RemoveAt(size_t stIndex) + { + m_vConfigs.erase(m_vConfigs.begin() + stIndex); + } + + void TConfigArray::Clear() + { + m_vConfigs.clear(); + } +} Index: src/libchcore/TConfigArray.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfigArray.h (.../TConfigArray.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TConfigArray.h (.../TConfigArray.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,55 +1,55 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TCONFIGARRAY_H__ -#define __TCONFIGARRAY_H__ - -#include "libchcore.h" -#include "TConfig.h" - -namespace chcore -{ - class LIBCHCORE_API TConfigArray - { - public: - TConfigArray(); - TConfigArray(const TConfigArray& rSrc); - ~TConfigArray(); - - TConfigArray& operator=(const TConfigArray& rSrc); - - size_t GetCount() const; - bool IsEmpty() const; - - const TConfig& GetAt(size_t stIndex) const; - TConfig& GetAt(size_t stIndex); - - void Add(const TConfig& rSrc); - - void RemoveAt(size_t stIndex); - void Clear(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vConfigs; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TCONFIGARRAY_H__ +#define __TCONFIGARRAY_H__ + +#include "libchcore.h" +#include "TConfig.h" + +namespace chcore +{ + class LIBCHCORE_API TConfigArray + { + public: + TConfigArray(); + TConfigArray(const TConfigArray& rSrc); + ~TConfigArray(); + + TConfigArray& operator=(const TConfigArray& rSrc); + + size_t GetCount() const; + bool IsEmpty() const; + + const TConfig& GetAt(size_t stIndex) const; + TConfig& GetAt(size_t stIndex); + + void Add(const TConfig& rSrc); + + void RemoveAt(size_t stIndex); + void Clear(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vConfigs; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TConfigNotifier.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfigNotifier.cpp (.../TConfigNotifier.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TConfigNotifier.cpp (.../TConfigNotifier.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,61 +1,61 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TConfigNotifier.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////////////////// - // class TConfigNotifier - - TConfigNotifier::TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) : - m_pfnCallback(pfnCallback), - m_pParam(pParam) - { - } - - TConfigNotifier::~TConfigNotifier() - { - } - - void TConfigNotifier::operator()(const TStringSet& rsetPropNames) - { - if (!m_pfnCallback) - throw TCoreException(eErr_InvalidPointer, L"m_pfnCallback", LOCATION); - - (*m_pfnCallback)(rsetPropNames, m_pParam); - } - - TConfigNotifier& TConfigNotifier::operator=(const TConfigNotifier& rNotifier) - { - if (this != &rNotifier) - { - m_pfnCallback = rNotifier.m_pfnCallback; - m_pParam = rNotifier.m_pParam; - } - return *this; - } - - bool TConfigNotifier::operator==(const TConfigNotifier& rNotifier) const - { - return m_pfnCallback == rNotifier.m_pfnCallback/* && m_pParam == rNotifier.m_pParam*/; - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TConfigNotifier.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////////// + // class TConfigNotifier + + TConfigNotifier::TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam) : + m_pfnCallback(pfnCallback), + m_pParam(pParam) + { + } + + TConfigNotifier::~TConfigNotifier() + { + } + + void TConfigNotifier::operator()(const TStringSet& rsetPropNames) + { + if (!m_pfnCallback) + throw TCoreException(eErr_InvalidPointer, L"m_pfnCallback", LOCATION); + + (*m_pfnCallback)(rsetPropNames, m_pParam); + } + + TConfigNotifier& TConfigNotifier::operator=(const TConfigNotifier& rNotifier) + { + if (this != &rNotifier) + { + m_pfnCallback = rNotifier.m_pfnCallback; + m_pParam = rNotifier.m_pParam; + } + return *this; + } + + bool TConfigNotifier::operator==(const TConfigNotifier& rNotifier) const + { + return m_pfnCallback == rNotifier.m_pfnCallback/* && m_pParam == rNotifier.m_pParam*/; + } +} Index: src/libchcore/TConfigNotifier.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfigNotifier.h (.../TConfigNotifier.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TConfigNotifier.h (.../TConfigNotifier.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,45 +1,45 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TCONFIGNOTIFIER_H__ -#define __TCONFIGNOTIFIER_H__ - -#include "TStringSet.h" - -namespace chcore -{ - // class defines configuration change notification record; not to be used outside - class TConfigNotifier - { - public: - TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); - ~TConfigNotifier(); - - void operator()(const TStringSet& rsetPropNames); - - TConfigNotifier& operator=(const TConfigNotifier& rNotifier); - - bool operator==(const TConfigNotifier& rNotifier) const; - - private: - void(*m_pfnCallback)(const TStringSet&, void*); - void* m_pParam; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TCONFIGNOTIFIER_H__ +#define __TCONFIGNOTIFIER_H__ + +#include "TStringSet.h" + +namespace chcore +{ + // class defines configuration change notification record; not to be used outside + class TConfigNotifier + { + public: + TConfigNotifier(void(*pfnCallback)(const TStringSet&, void*), void* pParam); + ~TConfigNotifier(); + + void operator()(const TStringSet& rsetPropNames); + + TConfigNotifier& operator=(const TConfigNotifier& rNotifier); + + bool operator==(const TConfigNotifier& rNotifier) const; + + private: + void(*m_pfnCallback)(const TStringSet&, void*); + void* m_pParam; + }; +} + +#endif Index: src/libchcore/TConfigSerializers.h =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TConfigSerializers.h (.../TConfigSerializers.h) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TConfigSerializers.h (.../TConfigSerializers.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,87 +1,87 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TConfigSerializers.h -/// @date 2010/10/23 -/// @brief Contains declarations/implementations of additional inline serializers. -// ============================================================================ -#ifndef __TCONFIGSERIALIZERS_H__ -#define __TCONFIGSERIALIZERS_H__ - -#include "TConfig.h" -#include "TStringArray.h" - -namespace chcore -{ -#ifdef _MFC_VER - - // CString config serializer - static void StoreInConfig(const CString& strValue, TConfig& rConfig, PCTSTR pszPropName) - { - rConfig.SetValue(pszPropName, TString((PCTSTR)strValue)); - } - - static bool ReadFromConfig(CString& strValue, const TConfig& rConfig, PCTSTR pszPropName) - { - TString wstrData; - bool bRes = rConfig.GetValue(pszPropName, wstrData); - if (bRes) - strValue = wstrData.c_str(); - else - strValue.Empty(); - return bRes; - } - - // vector config serializer - static void StoreInConfig(const std::vector& vValues, TConfig& rConfig, PCTSTR pszPropName) - { - // convert to vector of wstrings (ineffective; there should be a better way to do this) - TStringArray vToStore; - for(const CString& strVal : vValues) - { - vToStore.Add((PCTSTR)strVal); - } - - rConfig.SetValue(pszPropName, vToStore); - } - - static bool ReadFromConfig(std::vector& vValues, const TConfig& rConfig, PCTSTR pszPropName) - { - vValues.clear(); - - TStringArray vToConvert; - - bool bRes = rConfig.GetValue(pszPropName, vToConvert); - if (bRes) - { - for (size_t stIndex = 0; stIndex < vToConvert.GetCount(); ++stIndex) - { - vValues.push_back(vToConvert.GetAt(stIndex).c_str()); - } - } - - return bRes; - } - -#endif -} - -CONFIG_STANDALONE_SERIALIZATION(CString) -CONFIG_STANDALONE_SERIALIZATION(std::vector) - -#endif // __TCONFIGSERIALIZERS_H__ +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TConfigSerializers.h +/// @date 2010/10/23 +/// @brief Contains declarations/implementations of additional inline serializers. +// ============================================================================ +#ifndef __TCONFIGSERIALIZERS_H__ +#define __TCONFIGSERIALIZERS_H__ + +#include "TConfig.h" +#include "TStringArray.h" + +namespace chcore +{ +#ifdef _MFC_VER + + // CString config serializer + static void StoreInConfig(const CString& strValue, TConfig& rConfig, PCTSTR pszPropName) + { + rConfig.SetValue(pszPropName, TString((PCTSTR)strValue)); + } + + static bool ReadFromConfig(CString& strValue, const TConfig& rConfig, PCTSTR pszPropName) + { + TString wstrData; + bool bRes = rConfig.GetValue(pszPropName, wstrData); + if (bRes) + strValue = wstrData.c_str(); + else + strValue.Empty(); + return bRes; + } + + // vector config serializer + static void StoreInConfig(const std::vector& vValues, TConfig& rConfig, PCTSTR pszPropName) + { + // convert to vector of wstrings (ineffective; there should be a better way to do this) + TStringArray vToStore; + for(const CString& strVal : vValues) + { + vToStore.Add((PCTSTR)strVal); + } + + rConfig.SetValue(pszPropName, vToStore); + } + + static bool ReadFromConfig(std::vector& vValues, const TConfig& rConfig, PCTSTR pszPropName) + { + vValues.clear(); + + TStringArray vToConvert; + + bool bRes = rConfig.GetValue(pszPropName, vToConvert); + if (bRes) + { + for (size_t stIndex = 0; stIndex < vToConvert.GetCount(); ++stIndex) + { + vValues.push_back(vToConvert.GetAt(stIndex).c_str()); + } + } + + return bRes; + } + +#endif +} + +CONFIG_STANDALONE_SERIALIZATION(CString) +CONFIG_STANDALONE_SERIALIZATION(std::vector) + +#endif // __TCONFIGSERIALIZERS_H__ Index: src/libchcore/TCoreException.cpp =================================================================== diff -u -rbfc7a8378a96c5b58def559b343918fca32f05a6 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreException.cpp (.../TCoreException.cpp) (revision bfc7a8378a96c5b58def559b343918fca32f05a6) +++ src/libchcore/TCoreException.cpp (.../TCoreException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,33 +1,33 @@ -/*************************************************************************** -* Copyright (C) 2001-2008 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#include "stdafx.h" -#include "TCoreException.h" - -namespace chcore -{ - TCoreException::TCoreException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } - - TCoreException::TCoreException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } -} +/*************************************************************************** +* Copyright (C) 2001-2008 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#include "stdafx.h" +#include "TCoreException.h" + +namespace chcore +{ + TCoreException::TCoreException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } + + TCoreException::TCoreException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } +} Index: src/libchcore/TCoreException.h =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreException.h (.../TCoreException.h) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TCoreException.h (.../TCoreException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,36 +1,36 @@ -/*************************************************************************** -* Copyright (C) 2001-2008 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __TEXCEPTION_H__ -#define __TEXCEPTION_H__ - -#include "libchcore.h" -#include "ErrorCodes.h" -#include "TBaseException.h" - -namespace chcore -{ - class LIBCHCORE_API TCoreException : public TBaseException - { - public: - TCoreException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TCoreException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - }; -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2008 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __TEXCEPTION_H__ +#define __TEXCEPTION_H__ + +#include "libchcore.h" +#include "ErrorCodes.h" +#include "TBaseException.h" + +namespace chcore +{ + class LIBCHCORE_API TCoreException : public TBaseException + { + public: + TCoreException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TCoreException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + }; +} + +#endif Index: src/libchcore/TCoreStdException.cpp =================================================================== diff -u -ra27d1acf1bda3c25b6dcce0d0eb0278009ce63ae -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreStdException.cpp (.../TCoreStdException.cpp) (revision a27d1acf1bda3c25b6dcce0d0eb0278009ce63ae) +++ src/libchcore/TCoreStdException.cpp (.../TCoreStdException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TCoreStdException.h" - -namespace chcore -{ - // ============================================================================ - /// TCoreException::TCoreException - /// @date 2009/11/30 - /// - /// @brief Constructs core exception object with additional data. - /// @param[in] eErrorCode - error code - /// @param[in] stdException - standard exception info - /// @param[in] pszFile - source file name - /// @param[in] stLineNumber - source line number - /// @param[in] pszFunction - function name in which the problem occurred. - // ============================================================================ - TCoreStdException::TCoreStdException(EGeneralErrors eErrorCode, std::exception& stdException, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TCoreException(eErrorCode, stdException.what(), pszFile, stLineNumber, pszFunction) - { - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TCoreStdException.h" + +namespace chcore +{ + // ============================================================================ + /// TCoreException::TCoreException + /// @date 2009/11/30 + /// + /// @brief Constructs core exception object with additional data. + /// @param[in] eErrorCode - error code + /// @param[in] stdException - standard exception info + /// @param[in] pszFile - source file name + /// @param[in] stLineNumber - source line number + /// @param[in] pszFunction - function name in which the problem occurred. + // ============================================================================ + TCoreStdException::TCoreStdException(EGeneralErrors eErrorCode, std::exception& stdException, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TCoreException(eErrorCode, stdException.what(), pszFile, stLineNumber, pszFunction) + { + } +} Index: src/libchcore/TCoreStdException.h =================================================================== diff -u -rd18db617f4727a237c94b59af9b4328f829eda16 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreStdException.h (.../TCoreStdException.h) (revision d18db617f4727a237c94b59af9b4328f829eda16) +++ src/libchcore/TCoreStdException.h (.../TCoreStdException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,37 +1,37 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TCORESTDEXCEPTION_H__ -#define __TCORESTDEXCEPTION_H__ - -#include "libchcore.h" -#include "TCoreException.h" - -#define THROW_CORE_EXCEPTION_STD(error_code, std_exception)\ - throw TCoreStdException(error_code, std_exception, __FILEW__, __LINE__, __FUNCTIONW__) - -namespace chcore -{ - class LIBCHCORE_API TCoreStdException : public TCoreException - { - public: - TCoreStdException(EGeneralErrors eErrorCode, std::exception& stdException, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TCORESTDEXCEPTION_H__ +#define __TCORESTDEXCEPTION_H__ + +#include "libchcore.h" +#include "TCoreException.h" + +#define THROW_CORE_EXCEPTION_STD(error_code, std_exception)\ + throw TCoreStdException(error_code, std_exception, __FILEW__, __LINE__, __FUNCTIONW__) + +namespace chcore +{ + class LIBCHCORE_API TCoreStdException : public TCoreException + { + public: + TCoreStdException(EGeneralErrors eErrorCode, std::exception& stdException, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + }; +} + +#endif Index: src/libchcore/TCoreWin32Exception.cpp =================================================================== diff -u -r71c49ab6ac2e657dee997cb9129c7d0d4dde21b6 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreWin32Exception.cpp (.../TCoreWin32Exception.cpp) (revision 71c49ab6ac2e657dee997cb9129c7d0d4dde21b6) +++ src/libchcore/TCoreWin32Exception.cpp (.../TCoreWin32Exception.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,60 +1,60 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TCoreWin32Exception.h" - -namespace chcore -{ - // ============================================================================ - /// TCoreWin32Exception::TCoreWin32Exception - /// @date 2011/07/18 - /// - /// @brief Constructs core win32 exception. - /// @param[in] eErrorCode - core error code - /// @param[in] dwWin32Exception - win32 error code - /// @param[in] pszFile -source file where the exception was thrown - /// @param[in] stLineNumber - source code line number where the exception was thrown - /// @param[in] pszFunction - function throwing the exception - // ============================================================================ - TCoreWin32Exception::TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TCoreException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_dwWin32ErrorCode(dwWin32Exception) - { - } - - // ============================================================================ - /// TCoreWin32Exception::GetErrorInfo - /// @date 2011/07/18 - /// - /// @brief Retrieves formatted exception information. - /// @param[in] pszBuffer - buffer for formatted string - /// @param[in] stMaxBuffer - max size of buffer - // ============================================================================ - void TCoreWin32Exception::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d, win32 error code: %lu)"), m_pszMsg, m_eErrorCode, m_dwWin32ErrorCode); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } - - void TCoreWin32Exception::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nWin32 error code: %lu\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), m_pszMsg, m_eErrorCode, m_dwWin32ErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TCoreWin32Exception.h" + +namespace chcore +{ + // ============================================================================ + /// TCoreWin32Exception::TCoreWin32Exception + /// @date 2011/07/18 + /// + /// @brief Constructs core win32 exception. + /// @param[in] eErrorCode - core error code + /// @param[in] dwWin32Exception - win32 error code + /// @param[in] pszFile -source file where the exception was thrown + /// @param[in] stLineNumber - source code line number where the exception was thrown + /// @param[in] pszFunction - function throwing the exception + // ============================================================================ + TCoreWin32Exception::TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TCoreException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_dwWin32ErrorCode(dwWin32Exception) + { + } + + // ============================================================================ + /// TCoreWin32Exception::GetErrorInfo + /// @date 2011/07/18 + /// + /// @brief Retrieves formatted exception information. + /// @param[in] pszBuffer - buffer for formatted string + /// @param[in] stMaxBuffer - max size of buffer + // ============================================================================ + void TCoreWin32Exception::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d, win32 error code: %lu)"), m_pszMsg, m_eErrorCode, m_dwWin32ErrorCode); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } + + void TCoreWin32Exception::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nWin32 error code: %lu\r\nFile: %s\r\nFunction: %s\r\nLine no: %lu"), m_pszMsg, m_eErrorCode, m_dwWin32ErrorCode, m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } +} Index: src/libchcore/TCoreWin32Exception.h =================================================================== diff -u -rad4fe0f8085b15527158073aa76eb2d9ef80b0e5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TCoreWin32Exception.h (.../TCoreWin32Exception.h) (revision ad4fe0f8085b15527158073aa76eb2d9ef80b0e5) +++ src/libchcore/TCoreWin32Exception.h (.../TCoreWin32Exception.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,41 +1,41 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TCOREWIN32EXCEPTION_H__ -#define __TCOREWIN32EXCEPTION_H__ - -#include "TCoreException.h" - -namespace chcore -{ - class LIBCHCORE_API TCoreWin32Exception : public TCoreException - { - public: - TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - - DWORD GetWin32ErrorCode() const { return m_dwWin32ErrorCode; } - - virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - - protected: - DWORD m_dwWin32ErrorCode; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TCOREWIN32EXCEPTION_H__ +#define __TCOREWIN32EXCEPTION_H__ + +#include "TCoreException.h" + +namespace chcore +{ + class LIBCHCORE_API TCoreWin32Exception : public TCoreException + { + public: + TCoreWin32Exception(EGeneralErrors eErrorCode, DWORD dwWin32Exception, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + + DWORD GetWin32ErrorCode() const { return m_dwWin32ErrorCode; } + + virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + + protected: + DWORD m_dwWin32ErrorCode; + }; +} + +#endif Index: src/libchcore/TDateTime.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TDateTime.cpp (.../TDateTime.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/TDateTime.cpp (.../TDateTime.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,231 +1,231 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TDateTime.cpp -/// @date 2011/10/26 -/// @brief Contains implementation of date&time handling class. -// ============================================================================ -#include "stdafx.h" -#include "TDateTime.h" -#include "TCoreWin32Exception.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TDateTime::TDateTime() : - m_tTime(0) - { - } - - TDateTime::TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond) - { - if (iYear < 1900) - throw TCoreException(eErr_InvalidArgument, L"iYear", LOCATION); - - tm tTime; - - tTime.tm_sec = iSecond; - tTime.tm_min = iMinute; - tTime.tm_hour = iHour; - tTime.tm_mday = iDay; - tTime.tm_mon = iMonth - 1; - tTime.tm_year = iYear - 1900; - tTime.tm_isdst = -1; - - m_tTime = _mktime64(&tTime); - if (m_tTime == -1) - throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot make time", LOCATION); - } - - TDateTime::TDateTime(FILETIME ftDateTime) - { - operator=(ftDateTime); - } - - TDateTime::TDateTime(SYSTEMTIME sysDateTime) - { - operator=(sysDateTime); - } - - TDateTime::TDateTime(time_t tDateTime) : - m_tTime(tDateTime) - { - } - - TDateTime& TDateTime::operator=(FILETIME ftDateTime) - { - // convert and process as system time - FILETIME tLocalFileTime; - if (!FileTimeToLocalFileTime(&ftDateTime, &tLocalFileTime)) - throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot convert file time to local file time", LOCATION); - - SYSTEMTIME sysTime; - if (!FileTimeToSystemTime(&tLocalFileTime, &sysTime)) - throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot convert file time to system time", LOCATION); - - return operator=(sysTime); - } - - TDateTime& TDateTime::operator=(SYSTEMTIME sysDateTime) - { - if (sysDateTime.wYear < 1900) - throw TCoreException(eErr_InvalidArgument, L"sysDateTime.wYear", LOCATION); - - tm tTime; - - tTime.tm_sec = sysDateTime.wSecond; - tTime.tm_min = sysDateTime.wMinute; - tTime.tm_hour = sysDateTime.wHour; - tTime.tm_mday = sysDateTime.wDay; - tTime.tm_mon = sysDateTime.wMonth - 1; - tTime.tm_year = sysDateTime.wYear - 1900; - tTime.tm_isdst = -1; - - m_tTime = _mktime64(&tTime); - if (m_tTime == -1) - throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot make time", LOCATION); - - return *this; - } - - TDateTime& TDateTime::operator=(time_t tDateTime) - { - m_tTime = tDateTime; - return *this; - } - - void TDateTime::Clear() - { - m_tTime = 0; - } - - void TDateTime::SetCurrentDateTime() - { - m_tTime = _time64(nullptr); - } - - void TDateTime::GetAsSystemTime(SYSTEMTIME& tSystemTime) const - { - tm tThisTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if (err != 0) - throw TCoreException(eErr_InvalidData, L"Reading localtime failed", LOCATION); - - tSystemTime.wYear = (WORD)(tThisTimeInfo.tm_year + 1900); - tSystemTime.wMonth = (WORD)(tThisTimeInfo.tm_mon + 1); - tSystemTime.wDayOfWeek = (WORD)tThisTimeInfo.tm_wday; - tSystemTime.wDay = (WORD)tThisTimeInfo.tm_mday; - tSystemTime.wHour = (WORD)tThisTimeInfo.tm_hour; - tSystemTime.wMinute = (WORD)tThisTimeInfo.tm_min; - tSystemTime.wSecond = (WORD)tThisTimeInfo.tm_sec; - tSystemTime.wMilliseconds = 0; - } - - TString TDateTime::Format(bool bUseDate, bool bUseTime) const - { - if (!bUseDate && !bUseTime) - return TString(); - - TString strTmp; - const size_t stMaxBufSize = 1024; - wchar_t* pszBuffer = strTmp.GetBuffer(stMaxBufSize); - - PCTSTR pszFmt = nullptr; - if (bUseDate && bUseTime) - pszFmt = _T("%x %X"); - else if (bUseDate) - pszFmt = _T("%x"); - else if (bUseTime) - pszFmt = _T("%X"); - - tm tThisTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if (err != 0) - throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); - - if (!_tcsftime(pszBuffer, stMaxBufSize, pszFmt, &tThisTimeInfo)) - throw TCoreException(eErr_InvalidData, L"Time formatting failed", LOCATION); - - strTmp.ReleaseBuffer(); - return strTmp; - } - - time_t TDateTime::Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const - { - if (!bCompareDate && !bCompareTime) - return 0; - - tm tThisTimeInfo; - tm tOtherTimeInfo; - errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); - if (err != 0) - throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); - err = _localtime64_s(&tOtherTimeInfo, &rOtherDateTime.m_tTime); - if (err != 0) - throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); - - time_t tDiffDateTime = 0; - if (bCompareDate) - { - time_t tThisCompoundDate = (tThisTimeInfo.tm_year - 1900) * 32140800 + tThisTimeInfo.tm_mon * 2678400 + tThisTimeInfo.tm_mday * 86400; - time_t tOtherCompoundDate = (tOtherTimeInfo.tm_year - 1900) * 32140800 + tOtherTimeInfo.tm_mon * 2678400 + tOtherTimeInfo.tm_mday * 86400; - - // <0 means that this date is less than other date, 0 means they are equal, >0 means that other date is less than this date - tDiffDateTime = tOtherCompoundDate - tThisCompoundDate; - - // at this point we can return only if this date differs from other date; if they are equal, process time comparison if needed - if (tDiffDateTime != 0) - return tDiffDateTime; - } - - if (bCompareTime) - { - time_t tThisCompoundTime = tThisTimeInfo.tm_hour * 3600 + tThisTimeInfo.tm_min * 60 + tThisTimeInfo.tm_sec; - time_t tOtherCompoundTime = tOtherTimeInfo.tm_hour * 3600 + tOtherTimeInfo.tm_min * 60 + tOtherTimeInfo.tm_sec; - - tDiffDateTime = tOtherCompoundTime - tThisCompoundTime; - } - - return tDiffDateTime; - } - - void TDateTime::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const - { - rConfig.SetValue(pszNodeName, m_tTime); - } - - bool TDateTime::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) - { - return rConfig.GetValue(pszNodeName, m_tTime); - } - - time_t TDateTime::GetAsTimeT() const - { - return m_tTime; - } - - bool TDateTime::operator==(const TDateTime& rSrc) const - { - return m_tTime == rSrc.m_tTime; - } - - bool TDateTime::operator!=(const TDateTime& rSrc) const - { - return m_tTime != rSrc.m_tTime; - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TDateTime.cpp +/// @date 2011/10/26 +/// @brief Contains implementation of date&time handling class. +// ============================================================================ +#include "stdafx.h" +#include "TDateTime.h" +#include "TCoreWin32Exception.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TDateTime::TDateTime() : + m_tTime(0) + { + } + + TDateTime::TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond) + { + if (iYear < 1900) + throw TCoreException(eErr_InvalidArgument, L"iYear", LOCATION); + + tm tTime; + + tTime.tm_sec = iSecond; + tTime.tm_min = iMinute; + tTime.tm_hour = iHour; + tTime.tm_mday = iDay; + tTime.tm_mon = iMonth - 1; + tTime.tm_year = iYear - 1900; + tTime.tm_isdst = -1; + + m_tTime = _mktime64(&tTime); + if (m_tTime == -1) + throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot make time", LOCATION); + } + + TDateTime::TDateTime(FILETIME ftDateTime) + { + operator=(ftDateTime); + } + + TDateTime::TDateTime(SYSTEMTIME sysDateTime) + { + operator=(sysDateTime); + } + + TDateTime::TDateTime(time_t tDateTime) : + m_tTime(tDateTime) + { + } + + TDateTime& TDateTime::operator=(FILETIME ftDateTime) + { + // convert and process as system time + FILETIME tLocalFileTime; + if (!FileTimeToLocalFileTime(&ftDateTime, &tLocalFileTime)) + throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot convert file time to local file time", LOCATION); + + SYSTEMTIME sysTime; + if (!FileTimeToSystemTime(&tLocalFileTime, &sysTime)) + throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot convert file time to system time", LOCATION); + + return operator=(sysTime); + } + + TDateTime& TDateTime::operator=(SYSTEMTIME sysDateTime) + { + if (sysDateTime.wYear < 1900) + throw TCoreException(eErr_InvalidArgument, L"sysDateTime.wYear", LOCATION); + + tm tTime; + + tTime.tm_sec = sysDateTime.wSecond; + tTime.tm_min = sysDateTime.wMinute; + tTime.tm_hour = sysDateTime.wHour; + tTime.tm_mday = sysDateTime.wDay; + tTime.tm_mon = sysDateTime.wMonth - 1; + tTime.tm_year = sysDateTime.wYear - 1900; + tTime.tm_isdst = -1; + + m_tTime = _mktime64(&tTime); + if (m_tTime == -1) + throw TCoreWin32Exception(eErr_InvalidArgument, GetLastError(), L"Cannot make time", LOCATION); + + return *this; + } + + TDateTime& TDateTime::operator=(time_t tDateTime) + { + m_tTime = tDateTime; + return *this; + } + + void TDateTime::Clear() + { + m_tTime = 0; + } + + void TDateTime::SetCurrentDateTime() + { + m_tTime = _time64(nullptr); + } + + void TDateTime::GetAsSystemTime(SYSTEMTIME& tSystemTime) const + { + tm tThisTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + throw TCoreException(eErr_InvalidData, L"Reading localtime failed", LOCATION); + + tSystemTime.wYear = (WORD)(tThisTimeInfo.tm_year + 1900); + tSystemTime.wMonth = (WORD)(tThisTimeInfo.tm_mon + 1); + tSystemTime.wDayOfWeek = (WORD)tThisTimeInfo.tm_wday; + tSystemTime.wDay = (WORD)tThisTimeInfo.tm_mday; + tSystemTime.wHour = (WORD)tThisTimeInfo.tm_hour; + tSystemTime.wMinute = (WORD)tThisTimeInfo.tm_min; + tSystemTime.wSecond = (WORD)tThisTimeInfo.tm_sec; + tSystemTime.wMilliseconds = 0; + } + + TString TDateTime::Format(bool bUseDate, bool bUseTime) const + { + if (!bUseDate && !bUseTime) + return TString(); + + TString strTmp; + const size_t stMaxBufSize = 1024; + wchar_t* pszBuffer = strTmp.GetBuffer(stMaxBufSize); + + PCTSTR pszFmt = nullptr; + if (bUseDate && bUseTime) + pszFmt = _T("%x %X"); + else if (bUseDate) + pszFmt = _T("%x"); + else if (bUseTime) + pszFmt = _T("%X"); + + tm tThisTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); + + if (!_tcsftime(pszBuffer, stMaxBufSize, pszFmt, &tThisTimeInfo)) + throw TCoreException(eErr_InvalidData, L"Time formatting failed", LOCATION); + + strTmp.ReleaseBuffer(); + return strTmp; + } + + time_t TDateTime::Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const + { + if (!bCompareDate && !bCompareTime) + return 0; + + tm tThisTimeInfo; + tm tOtherTimeInfo; + errno_t err = _localtime64_s(&tThisTimeInfo, &m_tTime); + if (err != 0) + throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); + err = _localtime64_s(&tOtherTimeInfo, &rOtherDateTime.m_tTime); + if (err != 0) + throw TCoreException(eErr_InvalidData, L"Reading local time failed", LOCATION); + + time_t tDiffDateTime = 0; + if (bCompareDate) + { + time_t tThisCompoundDate = (tThisTimeInfo.tm_year - 1900) * 32140800 + tThisTimeInfo.tm_mon * 2678400 + tThisTimeInfo.tm_mday * 86400; + time_t tOtherCompoundDate = (tOtherTimeInfo.tm_year - 1900) * 32140800 + tOtherTimeInfo.tm_mon * 2678400 + tOtherTimeInfo.tm_mday * 86400; + + // <0 means that this date is less than other date, 0 means they are equal, >0 means that other date is less than this date + tDiffDateTime = tOtherCompoundDate - tThisCompoundDate; + + // at this point we can return only if this date differs from other date; if they are equal, process time comparison if needed + if (tDiffDateTime != 0) + return tDiffDateTime; + } + + if (bCompareTime) + { + time_t tThisCompoundTime = tThisTimeInfo.tm_hour * 3600 + tThisTimeInfo.tm_min * 60 + tThisTimeInfo.tm_sec; + time_t tOtherCompoundTime = tOtherTimeInfo.tm_hour * 3600 + tOtherTimeInfo.tm_min * 60 + tOtherTimeInfo.tm_sec; + + tDiffDateTime = tOtherCompoundTime - tThisCompoundTime; + } + + return tDiffDateTime; + } + + void TDateTime::StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const + { + rConfig.SetValue(pszNodeName, m_tTime); + } + + bool TDateTime::ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName) + { + return rConfig.GetValue(pszNodeName, m_tTime); + } + + time_t TDateTime::GetAsTimeT() const + { + return m_tTime; + } + + bool TDateTime::operator==(const TDateTime& rSrc) const + { + return m_tTime == rSrc.m_tTime; + } + + bool TDateTime::operator!=(const TDateTime& rSrc) const + { + return m_tTime != rSrc.m_tTime; + } +} Index: src/libchcore/TDateTime.h =================================================================== diff -u -r5446395d3925e49d3e4cba82044bdfd4dffb6ee9 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TDateTime.h (.../TDateTime.h) (revision 5446395d3925e49d3e4cba82044bdfd4dffb6ee9) +++ src/libchcore/TDateTime.h (.../TDateTime.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,75 +1,75 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TDateTime.h -/// @date 2011/10/26 -/// @brief Contains declaration of date&time handling class. -// ============================================================================ -#ifndef __TDATETIME_H__ -#define __TDATETIME_H__ - -#include "libchcore.h" -#include "TConfig.h" - -namespace chcore -{ - class TConfig; - - class LIBCHCORE_API TDateTime - { - public: - TDateTime(); - TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond); - // cppcheck-suppress noExplicitConstructor - TDateTime(FILETIME ftDateTime); - // cppcheck-suppress noExplicitConstructor - TDateTime(SYSTEMTIME sysDateTime); - // cppcheck-suppress noExplicitConstructor - TDateTime(time_t tDateTime); - - TDateTime& operator=(FILETIME ftDateTime); - TDateTime& operator=(SYSTEMTIME sysDateTime); - TDateTime& operator=(time_t tDateTime); - - bool operator==(const TDateTime& rSrc) const; - bool operator!=(const TDateTime& rSrc) const; - - // content modification - void Clear(); - void SetCurrentDateTime(); - - // content extraction - void GetAsSystemTime(SYSTEMTIME& tSystemTime) const; - time_t GetAsTimeT() const; - TString Format(bool bUseDate, bool bUseTime) const; - - // comparison - time_t Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const; - - // serialization - void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; - bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); - - private: - time_t m_tTime; - }; -} - -CONFIG_MEMBER_SERIALIZATION(TDateTime) - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TDateTime.h +/// @date 2011/10/26 +/// @brief Contains declaration of date&time handling class. +// ============================================================================ +#ifndef __TDATETIME_H__ +#define __TDATETIME_H__ + +#include "libchcore.h" +#include "TConfig.h" + +namespace chcore +{ + class TConfig; + + class LIBCHCORE_API TDateTime + { + public: + TDateTime(); + TDateTime(int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond); + // cppcheck-suppress noExplicitConstructor + TDateTime(FILETIME ftDateTime); + // cppcheck-suppress noExplicitConstructor + TDateTime(SYSTEMTIME sysDateTime); + // cppcheck-suppress noExplicitConstructor + TDateTime(time_t tDateTime); + + TDateTime& operator=(FILETIME ftDateTime); + TDateTime& operator=(SYSTEMTIME sysDateTime); + TDateTime& operator=(time_t tDateTime); + + bool operator==(const TDateTime& rSrc) const; + bool operator!=(const TDateTime& rSrc) const; + + // content modification + void Clear(); + void SetCurrentDateTime(); + + // content extraction + void GetAsSystemTime(SYSTEMTIME& tSystemTime) const; + time_t GetAsTimeT() const; + TString Format(bool bUseDate, bool bUseTime) const; + + // comparison + time_t Compare(const TDateTime& rOtherDateTime, bool bCompareDate, bool bCompareTime) const; + + // serialization + void StoreInConfig(TConfig& rConfig, PCTSTR pszNodeName) const; + bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszNodeName); + + private: + time_t m_tTime; + }; +} + +CONFIG_MEMBER_SERIALIZATION(TDateTime) + +#endif Index: src/libchcore/TEvent.cpp =================================================================== diff -u -r3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TEvent.cpp (.../TEvent.cpp) (revision 3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4) +++ src/libchcore/TEvent.cpp (.../TEvent.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,65 +1,65 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TEvent.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TEvent::TEvent(bool bManualReset, bool bInitialState) - { - m_hEvent = CreateEvent(nullptr, bManualReset, bInitialState, nullptr); - if (m_hEvent == nullptr) - throw TCoreException(eErr_CannotCreateEvent, L"Failed to create event", LOCATION); -#ifdef _DEBUG - m_bSignaled = bInitialState; -#endif - } - - TEvent::~TEvent() - { - CloseHandle(m_hEvent); - } - - void TEvent::SetEvent(bool bSet) - { - if(bSet) - SetEvent(); - else - ResetEvent(); - } - - void TEvent::SetEvent() - { - ::SetEvent(m_hEvent); -#ifdef _DEBUG - m_bSignaled = true; -#endif - } - - void TEvent::ResetEvent() - { - ::ResetEvent(m_hEvent); -#ifdef _DEBUG - m_bSignaled = false; -#endif - } - -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TEvent.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TEvent::TEvent(bool bManualReset, bool bInitialState) + { + m_hEvent = CreateEvent(nullptr, bManualReset, bInitialState, nullptr); + if (m_hEvent == nullptr) + throw TCoreException(eErr_CannotCreateEvent, L"Failed to create event", LOCATION); +#ifdef _DEBUG + m_bSignaled = bInitialState; +#endif + } + + TEvent::~TEvent() + { + CloseHandle(m_hEvent); + } + + void TEvent::SetEvent(bool bSet) + { + if(bSet) + SetEvent(); + else + ResetEvent(); + } + + void TEvent::SetEvent() + { + ::SetEvent(m_hEvent); +#ifdef _DEBUG + m_bSignaled = true; +#endif + } + + void TEvent::ResetEvent() + { + ::ResetEvent(m_hEvent); +#ifdef _DEBUG + m_bSignaled = false; +#endif + } + +} Index: src/libchcore/TEvent.h =================================================================== diff -u -r3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TEvent.h (.../TEvent.h) (revision 3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4) +++ src/libchcore/TEvent.h (.../TEvent.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,48 +1,48 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TEVENT_H__ -#define __TEVENT_H__ - -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API TEvent - { - public: - TEvent(bool bManualReset, bool bInitialState); - virtual ~TEvent(); - - HANDLE Get() const { return m_hEvent; } - - void SetEvent(bool bSet); - void SetEvent(); - void ResetEvent(); - - HANDLE Handle() const { return m_hEvent; } - - private: -#ifdef _DEBUG - bool m_bSignaled = false; -#endif - HANDLE m_hEvent; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TEVENT_H__ +#define __TEVENT_H__ + +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API TEvent + { + public: + TEvent(bool bManualReset, bool bInitialState); + virtual ~TEvent(); + + HANDLE Get() const { return m_hEvent; } + + void SetEvent(bool bSet); + void SetEvent(); + void ResetEvent(); + + HANDLE Handle() const { return m_hEvent; } + + private: +#ifdef _DEBUG + bool m_bSignaled = false; +#endif + HANDLE m_hEvent; + }; +} + +#endif Index: src/libchcore/TFakeFileSerializer.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFakeFileSerializer.cpp (.../TFakeFileSerializer.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TFakeFileSerializer.cpp (.../TFakeFileSerializer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,49 +1,49 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFakeFileSerializer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TFakeFileSerializer::TFakeFileSerializer(const TSmartPath& rPath) : - m_pathFileSerializer(rPath) - { - } - - TFakeFileSerializer::~TFakeFileSerializer() - { - } - - TSmartPath TFakeFileSerializer::GetLocation() const - { - return m_pathFileSerializer; - } - - ISerializerContainerPtr TFakeFileSerializer::GetContainer(const TString& /*strContainerName*/) - { - throw TCoreException(eErr_InvalidSerializer, L"GetContainer is unsupported on fake serializer", m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); - } - - void TFakeFileSerializer::Flush() - { - throw TCoreException(eErr_InvalidSerializer, L"Flush is unsupported on fake serializer", m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFakeFileSerializer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TFakeFileSerializer::TFakeFileSerializer(const TSmartPath& rPath) : + m_pathFileSerializer(rPath) + { + } + + TFakeFileSerializer::~TFakeFileSerializer() + { + } + + TSmartPath TFakeFileSerializer::GetLocation() const + { + return m_pathFileSerializer; + } + + ISerializerContainerPtr TFakeFileSerializer::GetContainer(const TString& /*strContainerName*/) + { + throw TCoreException(eErr_InvalidSerializer, L"GetContainer is unsupported on fake serializer", m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); + } + + void TFakeFileSerializer::Flush() + { + throw TCoreException(eErr_InvalidSerializer, L"Flush is unsupported on fake serializer", m_pathFileSerializer.ToString(), __LINE__, __FUNCTIONW__); + } +} Index: src/libchcore/TFakeFileSerializer.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFakeFileSerializer.h (.../TFakeFileSerializer.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TFakeFileSerializer.h (.../TFakeFileSerializer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,47 +1,47 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFAKEFILESERIALIZER_H__ -#define __TFAKEFILESERIALIZER_H__ - -#include "libchcore.h" -#include "ISerializer.h" - -namespace chcore -{ - class LIBCHCORE_API TFakeFileSerializer : public ISerializer - { - public: - explicit TFakeFileSerializer(const TSmartPath& rPath); - virtual ~TFakeFileSerializer(); - - TFakeFileSerializer(const TFakeFileSerializer& rSrc) = delete; - TFakeFileSerializer& operator=(const TFakeFileSerializer& rSrc) = delete; - - virtual TSmartPath GetLocation() const override; - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) override; - virtual void Flush() override; - - private: - TSmartPath m_pathFileSerializer; - }; - - typedef std::shared_ptr TFakeFileSerializerPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFAKEFILESERIALIZER_H__ +#define __TFAKEFILESERIALIZER_H__ + +#include "libchcore.h" +#include "ISerializer.h" + +namespace chcore +{ + class LIBCHCORE_API TFakeFileSerializer : public ISerializer + { + public: + explicit TFakeFileSerializer(const TSmartPath& rPath); + virtual ~TFakeFileSerializer(); + + TFakeFileSerializer(const TFakeFileSerializer& rSrc) = delete; + TFakeFileSerializer& operator=(const TFakeFileSerializer& rSrc) = delete; + + virtual TSmartPath GetLocation() const override; + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName) override; + virtual void Flush() override; + + private: + TSmartPath m_pathFileSerializer; + }; + + typedef std::shared_ptr TFakeFileSerializerPtr; +} + +#endif Index: src/libchcore/TFeedbackHandlerBase.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackHandlerBase.cpp (.../TFeedbackHandlerBase.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TFeedbackHandlerBase.cpp (.../TFeedbackHandlerBase.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,183 +1,183 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFeedbackHandlerBase.h" -#include "SerializerDataTypes.h" -#include "ISerializerContainer.h" -#include - -namespace chcore -{ - TFeedbackHandlerBase::TFeedbackHandlerBase() : - m_eFileError(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eFileAlreadyExists(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eNotEnoughSpace(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eOperationFinished(m_setModifications, EFeedbackResult::eResult_Unknown), - m_eOperationError(m_setModifications, EFeedbackResult::eResult_Unknown) - { - m_setModifications[eMod_Added] = true; - } - - TFeedbackHandlerBase::~TFeedbackHandlerBase() - { - } - - void TFeedbackHandlerBase::SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult) - { - boost::unique_lock lock(m_lock); - m_eFileError = ePermanentResult; - } - - EFeedbackResult TFeedbackHandlerBase::GetFileErrorPermanentResponse() const - { - boost::shared_lock lock(m_lock); - return m_eFileError; - } - - bool TFeedbackHandlerBase::HasFileErrorPermanentResponse(EFeedbackResult& rePermanentResult) const - { - boost::shared_lock lock(m_lock); - rePermanentResult = m_eFileError; - return rePermanentResult != EFeedbackResult::eResult_Unknown; - } - - void TFeedbackHandlerBase::SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult) - { - boost::unique_lock lock(m_lock); - m_eFileAlreadyExists = ePermanentResult; - } - - EFeedbackResult TFeedbackHandlerBase::GetFileAlreadyExistsPermanentResponse() const - { - boost::shared_lock lock(m_lock); - return m_eFileAlreadyExists; - } - - bool TFeedbackHandlerBase::HasFileAlreadyExistsPermanentResponse(EFeedbackResult& rePermanentResult) const - { - boost::shared_lock lock(m_lock); - rePermanentResult = m_eFileAlreadyExists; - return rePermanentResult != EFeedbackResult::eResult_Unknown; - } - - void TFeedbackHandlerBase::SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult) - { - boost::unique_lock lock(m_lock); - m_eNotEnoughSpace = ePermanentResult; - } - - EFeedbackResult TFeedbackHandlerBase::GetNotEnoughSpacePermanentResponse() const - { - boost::shared_lock lock(m_lock); - return m_eNotEnoughSpace; - } - - bool TFeedbackHandlerBase::HasNotEnoughSpacePermanentResponse(EFeedbackResult& rePermanentResult) const - { - boost::shared_lock lock(m_lock); - rePermanentResult = m_eNotEnoughSpace; - return rePermanentResult != EFeedbackResult::eResult_Unknown; - } - - void TFeedbackHandlerBase::Store(const ISerializerContainerPtr& spContainer) const - { - boost::shared_lock lock(m_lock); - - if (m_setModifications.any()) - { - InitColumns(spContainer); - - bool bAdded = m_setModifications[eMod_Added]; - ISerializerRowData& rRowData = spContainer->GetRow(0, bAdded); - - if (bAdded || m_eFileError.IsModified()) - rRowData.SetValue(_T("file_error"), m_eFileError); - - if (bAdded || m_eFileAlreadyExists.IsModified()) - rRowData.SetValue(_T("file_already_exists"), m_eFileAlreadyExists); - - if (bAdded || m_eNotEnoughSpace.IsModified()) - rRowData.SetValue(_T("not_enough_space"), m_eNotEnoughSpace); - - if (bAdded || m_eOperationFinished.IsModified()) - rRowData.SetValue(_T("operation_finished"), m_eOperationFinished); - - if (bAdded || m_eOperationError.IsModified()) - rRowData.SetValue(_T("operation_error"), m_eOperationError); - - m_setModifications.reset(); - } - } - - void TFeedbackHandlerBase::InitColumns(const ISerializerContainerPtr& spContainer) - { - IColumnsDefinition& rColumnDefs = spContainer->GetColumnsDefinition(); - if (rColumnDefs.IsEmpty()) - { - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("file_error"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("file_already_exists"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("not_enough_space"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("operation_finished"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("operation_error"), IColumnsDefinition::eType_int); - } - } - - void TFeedbackHandlerBase::Load(const ISerializerContainerPtr& spContainer) - { - boost::unique_lock lock(m_lock); - - InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) - { - int iFeedbackResult = eResult_Unknown; - - spRowReader->GetValue(_T("file_error"), iFeedbackResult); - m_eFileError = (EFeedbackResult)iFeedbackResult; - - spRowReader->GetValue(_T("file_already_exists"), iFeedbackResult); - m_eFileAlreadyExists = (EFeedbackResult)iFeedbackResult; - spRowReader->GetValue(_T("not_enough_space"), iFeedbackResult); - m_eNotEnoughSpace = (EFeedbackResult)iFeedbackResult; - spRowReader->GetValue(_T("operation_finished"), iFeedbackResult); - m_eOperationFinished = (EFeedbackResult)iFeedbackResult; - spRowReader->GetValue(_T("operation_error"), iFeedbackResult); - m_eOperationError = (EFeedbackResult)iFeedbackResult; - - m_setModifications.reset(); - } - } - - DWORD TFeedbackHandlerBase::GetRetryInterval() const - { - return 100; - } - - void TFeedbackHandlerBase::RestoreDefaults() - { - boost::unique_lock lock(m_lock); - - m_eFileError = EFeedbackResult::eResult_Unknown; - m_eFileAlreadyExists = EFeedbackResult::eResult_Unknown; - m_eNotEnoughSpace = EFeedbackResult::eResult_Unknown; - m_eOperationFinished = EFeedbackResult::eResult_Unknown; - m_eOperationError = EFeedbackResult::eResult_Unknown; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFeedbackHandlerBase.h" +#include "SerializerDataTypes.h" +#include "ISerializerContainer.h" +#include + +namespace chcore +{ + TFeedbackHandlerBase::TFeedbackHandlerBase() : + m_eFileError(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eFileAlreadyExists(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eNotEnoughSpace(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eOperationFinished(m_setModifications, EFeedbackResult::eResult_Unknown), + m_eOperationError(m_setModifications, EFeedbackResult::eResult_Unknown) + { + m_setModifications[eMod_Added] = true; + } + + TFeedbackHandlerBase::~TFeedbackHandlerBase() + { + } + + void TFeedbackHandlerBase::SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult) + { + boost::unique_lock lock(m_lock); + m_eFileError = ePermanentResult; + } + + EFeedbackResult TFeedbackHandlerBase::GetFileErrorPermanentResponse() const + { + boost::shared_lock lock(m_lock); + return m_eFileError; + } + + bool TFeedbackHandlerBase::HasFileErrorPermanentResponse(EFeedbackResult& rePermanentResult) const + { + boost::shared_lock lock(m_lock); + rePermanentResult = m_eFileError; + return rePermanentResult != EFeedbackResult::eResult_Unknown; + } + + void TFeedbackHandlerBase::SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult) + { + boost::unique_lock lock(m_lock); + m_eFileAlreadyExists = ePermanentResult; + } + + EFeedbackResult TFeedbackHandlerBase::GetFileAlreadyExistsPermanentResponse() const + { + boost::shared_lock lock(m_lock); + return m_eFileAlreadyExists; + } + + bool TFeedbackHandlerBase::HasFileAlreadyExistsPermanentResponse(EFeedbackResult& rePermanentResult) const + { + boost::shared_lock lock(m_lock); + rePermanentResult = m_eFileAlreadyExists; + return rePermanentResult != EFeedbackResult::eResult_Unknown; + } + + void TFeedbackHandlerBase::SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult) + { + boost::unique_lock lock(m_lock); + m_eNotEnoughSpace = ePermanentResult; + } + + EFeedbackResult TFeedbackHandlerBase::GetNotEnoughSpacePermanentResponse() const + { + boost::shared_lock lock(m_lock); + return m_eNotEnoughSpace; + } + + bool TFeedbackHandlerBase::HasNotEnoughSpacePermanentResponse(EFeedbackResult& rePermanentResult) const + { + boost::shared_lock lock(m_lock); + rePermanentResult = m_eNotEnoughSpace; + return rePermanentResult != EFeedbackResult::eResult_Unknown; + } + + void TFeedbackHandlerBase::Store(const ISerializerContainerPtr& spContainer) const + { + boost::shared_lock lock(m_lock); + + if (m_setModifications.any()) + { + InitColumns(spContainer); + + bool bAdded = m_setModifications[eMod_Added]; + ISerializerRowData& rRowData = spContainer->GetRow(0, bAdded); + + if (bAdded || m_eFileError.IsModified()) + rRowData.SetValue(_T("file_error"), m_eFileError); + + if (bAdded || m_eFileAlreadyExists.IsModified()) + rRowData.SetValue(_T("file_already_exists"), m_eFileAlreadyExists); + + if (bAdded || m_eNotEnoughSpace.IsModified()) + rRowData.SetValue(_T("not_enough_space"), m_eNotEnoughSpace); + + if (bAdded || m_eOperationFinished.IsModified()) + rRowData.SetValue(_T("operation_finished"), m_eOperationFinished); + + if (bAdded || m_eOperationError.IsModified()) + rRowData.SetValue(_T("operation_error"), m_eOperationError); + + m_setModifications.reset(); + } + } + + void TFeedbackHandlerBase::InitColumns(const ISerializerContainerPtr& spContainer) + { + IColumnsDefinition& rColumnDefs = spContainer->GetColumnsDefinition(); + if (rColumnDefs.IsEmpty()) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("file_error"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("file_already_exists"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("not_enough_space"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("operation_finished"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("operation_error"), IColumnsDefinition::eType_int); + } + } + + void TFeedbackHandlerBase::Load(const ISerializerContainerPtr& spContainer) + { + boost::unique_lock lock(m_lock); + + InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + { + int iFeedbackResult = eResult_Unknown; + + spRowReader->GetValue(_T("file_error"), iFeedbackResult); + m_eFileError = (EFeedbackResult)iFeedbackResult; + + spRowReader->GetValue(_T("file_already_exists"), iFeedbackResult); + m_eFileAlreadyExists = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("not_enough_space"), iFeedbackResult); + m_eNotEnoughSpace = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("operation_finished"), iFeedbackResult); + m_eOperationFinished = (EFeedbackResult)iFeedbackResult; + spRowReader->GetValue(_T("operation_error"), iFeedbackResult); + m_eOperationError = (EFeedbackResult)iFeedbackResult; + + m_setModifications.reset(); + } + } + + DWORD TFeedbackHandlerBase::GetRetryInterval() const + { + return 100; + } + + void TFeedbackHandlerBase::RestoreDefaults() + { + boost::unique_lock lock(m_lock); + + m_eFileError = EFeedbackResult::eResult_Unknown; + m_eFileAlreadyExists = EFeedbackResult::eResult_Unknown; + m_eNotEnoughSpace = EFeedbackResult::eResult_Unknown; + m_eOperationFinished = EFeedbackResult::eResult_Unknown; + m_eOperationError = EFeedbackResult::eResult_Unknown; + } +} Index: src/libchcore/TFeedbackHandlerBase.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackHandlerBase.h (.../TFeedbackHandlerBase.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TFeedbackHandlerBase.h (.../TFeedbackHandlerBase.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,91 +1,91 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFEEDBACKHANDLERBASE_H__ -#define __TFEEDBACKHANDLERBASE_H__ - -#include "libchcore.h" -#include "IFeedbackHandler.h" -#include "ISerializerRowData.h" -#include -#include "TSharedModificationTracker.h" - -namespace chcore -{ - class LIBCHCORE_API TFeedbackHandlerBase : public IFeedbackHandler - { - public: - TFeedbackHandlerBase(); - virtual ~TFeedbackHandlerBase(); - - // marking responses as permanent - void SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult); - EFeedbackResult GetFileErrorPermanentResponse() const; - bool HasFileErrorPermanentResponse(EFeedbackResult& rePermanentResult) const; - - void SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult); - EFeedbackResult GetFileAlreadyExistsPermanentResponse() const; - bool HasFileAlreadyExistsPermanentResponse(EFeedbackResult& rePermanentResult) const; - - void SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult); - EFeedbackResult GetNotEnoughSpacePermanentResponse() const; - bool HasNotEnoughSpacePermanentResponse(EFeedbackResult& rePermanentResult) const; - - // resets the permanent status from all responses - virtual void RestoreDefaults() override; - - // serialization - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(const ISerializerContainerPtr& spContainer); - void Load(const ISerializerContainerPtr& spContainer); - - virtual DWORD GetRetryInterval() const override; - - private: - enum EModifications - { - eMod_Added = 0, - eMod_FileError, - eMod_FileAlreadyExists, - eMod_NotEnoughSpace, - eMod_OperationFinished, - eMod_OperationError, - - // last item - eMod_Last - }; - -#pragma warning(push) -#pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; - - using Bitset = std::bitset; - mutable Bitset m_setModifications; - - TSharedModificationTracker m_eFileError; - TSharedModificationTracker m_eFileAlreadyExists; - TSharedModificationTracker m_eNotEnoughSpace; - TSharedModificationTracker m_eOperationFinished; - TSharedModificationTracker m_eOperationError; -#pragma warning(pop) - }; - - typedef std::shared_ptr TFeedbackHandlerBasePtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFEEDBACKHANDLERBASE_H__ +#define __TFEEDBACKHANDLERBASE_H__ + +#include "libchcore.h" +#include "IFeedbackHandler.h" +#include "ISerializerRowData.h" +#include +#include "TSharedModificationTracker.h" + +namespace chcore +{ + class LIBCHCORE_API TFeedbackHandlerBase : public IFeedbackHandler + { + public: + TFeedbackHandlerBase(); + virtual ~TFeedbackHandlerBase(); + + // marking responses as permanent + void SetFileErrorPermanentResponse(EFeedbackResult ePermanentResult); + EFeedbackResult GetFileErrorPermanentResponse() const; + bool HasFileErrorPermanentResponse(EFeedbackResult& rePermanentResult) const; + + void SetFileAlreadyExistsPermanentResponse(EFeedbackResult ePermanentResult); + EFeedbackResult GetFileAlreadyExistsPermanentResponse() const; + bool HasFileAlreadyExistsPermanentResponse(EFeedbackResult& rePermanentResult) const; + + void SetNotEnoughSpacePermanentResponse(EFeedbackResult ePermanentResult); + EFeedbackResult GetNotEnoughSpacePermanentResponse() const; + bool HasNotEnoughSpacePermanentResponse(EFeedbackResult& rePermanentResult) const; + + // resets the permanent status from all responses + virtual void RestoreDefaults() override; + + // serialization + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(const ISerializerContainerPtr& spContainer); + void Load(const ISerializerContainerPtr& spContainer); + + virtual DWORD GetRetryInterval() const override; + + private: + enum EModifications + { + eMod_Added = 0, + eMod_FileError, + eMod_FileAlreadyExists, + eMod_NotEnoughSpace, + eMod_OperationFinished, + eMod_OperationError, + + // last item + eMod_Last + }; + +#pragma warning(push) +#pragma warning(disable: 4251) + mutable boost::shared_mutex m_lock; + + using Bitset = std::bitset; + mutable Bitset m_setModifications; + + TSharedModificationTracker m_eFileError; + TSharedModificationTracker m_eFileAlreadyExists; + TSharedModificationTracker m_eNotEnoughSpace; + TSharedModificationTracker m_eOperationFinished; + TSharedModificationTracker m_eOperationError; +#pragma warning(pop) + }; + + typedef std::shared_ptr TFeedbackHandlerBasePtr; +} + +#endif Index: src/libchcore/TFeedbackHandlerWrapper.cpp =================================================================== diff -u -r89f857792bba8752de98ddd477949e45cef5ba5a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackHandlerWrapper.cpp (.../TFeedbackHandlerWrapper.cpp) (revision 89f857792bba8752de98ddd477949e45cef5ba5a) +++ src/libchcore/TFeedbackHandlerWrapper.cpp (.../TFeedbackHandlerWrapper.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,90 +1,90 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFeedbackHandlerWrapper.h" -#include "TScopedRunningTimeTrackerPause.h" - -namespace chcore -{ - TFeedbackHandlerWrapper::TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard) : - m_spFeedbackHandler(spFeedbackHandler), - m_rTimeGuard(rTimeGuard) - { - } - - TFeedbackHandlerWrapper::~TFeedbackHandlerWrapper() - { - } - - TFeedbackResult TFeedbackHandlerWrapper::FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) - { - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - - return m_spFeedbackHandler->FileError(strSrcPath, strDstPath, eFileError, ulError); - } - - TFeedbackResult TFeedbackHandlerWrapper::FileAlreadyExists(const TFileInfo& spSrcFileInfo, const TFileInfo& spDstFileInfo) - { - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - - return m_spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); - } - - TFeedbackResult TFeedbackHandlerWrapper::NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) - { - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - - return m_spFeedbackHandler->NotEnoughSpace(strSrcPath, strDstPath, ullRequiredSize); - } - - TFeedbackResult TFeedbackHandlerWrapper::OperationFinished() - { - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - - return m_spFeedbackHandler->OperationFinished(); - } - - TFeedbackResult TFeedbackHandlerWrapper::OperationError() - { - TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); - - return m_spFeedbackHandler->OperationError(); - } - - void TFeedbackHandlerWrapper::RestoreDefaults() - { - return m_spFeedbackHandler->RestoreDefaults(); - } - - void TFeedbackHandlerWrapper::Store(const ISerializerContainerPtr& spContainer) const - { - return m_spFeedbackHandler->Store(spContainer); - } - - void TFeedbackHandlerWrapper::Load(const ISerializerContainerPtr& spContainer) - { - return m_spFeedbackHandler->Load(spContainer); - } - - DWORD TFeedbackHandlerWrapper::GetRetryInterval() const - { - return m_spFeedbackHandler->GetRetryInterval(); - } - -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFeedbackHandlerWrapper.h" +#include "TScopedRunningTimeTrackerPause.h" + +namespace chcore +{ + TFeedbackHandlerWrapper::TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard) : + m_spFeedbackHandler(spFeedbackHandler), + m_rTimeGuard(rTimeGuard) + { + } + + TFeedbackHandlerWrapper::~TFeedbackHandlerWrapper() + { + } + + TFeedbackResult TFeedbackHandlerWrapper::FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + + return m_spFeedbackHandler->FileError(strSrcPath, strDstPath, eFileError, ulError); + } + + TFeedbackResult TFeedbackHandlerWrapper::FileAlreadyExists(const TFileInfo& spSrcFileInfo, const TFileInfo& spDstFileInfo) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + + return m_spFeedbackHandler->FileAlreadyExists(spSrcFileInfo, spDstFileInfo); + } + + TFeedbackResult TFeedbackHandlerWrapper::NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + + return m_spFeedbackHandler->NotEnoughSpace(strSrcPath, strDstPath, ullRequiredSize); + } + + TFeedbackResult TFeedbackHandlerWrapper::OperationFinished() + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + + return m_spFeedbackHandler->OperationFinished(); + } + + TFeedbackResult TFeedbackHandlerWrapper::OperationError() + { + TScopedRunningTimeTrackerPause scopedTimePause(m_rTimeGuard); + + return m_spFeedbackHandler->OperationError(); + } + + void TFeedbackHandlerWrapper::RestoreDefaults() + { + return m_spFeedbackHandler->RestoreDefaults(); + } + + void TFeedbackHandlerWrapper::Store(const ISerializerContainerPtr& spContainer) const + { + return m_spFeedbackHandler->Store(spContainer); + } + + void TFeedbackHandlerWrapper::Load(const ISerializerContainerPtr& spContainer) + { + return m_spFeedbackHandler->Load(spContainer); + } + + DWORD TFeedbackHandlerWrapper::GetRetryInterval() const + { + return m_spFeedbackHandler->GetRetryInterval(); + } + +} Index: src/libchcore/TFeedbackHandlerWrapper.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackHandlerWrapper.h (.../TFeedbackHandlerWrapper.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TFeedbackHandlerWrapper.h (.../TFeedbackHandlerWrapper.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,59 +1,59 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFEEDBACKHANDLERWRAPPER_H__ -#define __TFEEDBACKHANDLERWRAPPER_H__ - -#include "libchcore.h" -#include "IFeedbackHandler.h" - -namespace chcore -{ - class TScopedRunningTimeTracker; - - class TFeedbackHandlerWrapper : public IFeedbackHandler - { - public: - TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard); - virtual ~TFeedbackHandlerWrapper(); - - TFeedbackHandlerWrapper(const TFeedbackHandlerWrapper&) = delete; - TFeedbackHandlerWrapper& operator=(const TFeedbackHandlerWrapper&) = delete; - - virtual TFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; - virtual TFeedbackResult FileAlreadyExists(const TFileInfo& spSrcFileInfo, const TFileInfo& spDstFileInfo) override; - virtual TFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; - virtual TFeedbackResult OperationFinished() override; - virtual TFeedbackResult OperationError() override; - - virtual void RestoreDefaults() override; - - virtual void Store(const ISerializerContainerPtr& spContainer) const override; - virtual void Load(const ISerializerContainerPtr& spContainer) override; - - virtual DWORD GetRetryInterval() const override; - - private: - IFeedbackHandlerPtr m_spFeedbackHandler; - TScopedRunningTimeTracker& m_rTimeGuard; - }; - - typedef std::shared_ptr TFeedbackHandlerWrapperPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFEEDBACKHANDLERWRAPPER_H__ +#define __TFEEDBACKHANDLERWRAPPER_H__ + +#include "libchcore.h" +#include "IFeedbackHandler.h" + +namespace chcore +{ + class TScopedRunningTimeTracker; + + class TFeedbackHandlerWrapper : public IFeedbackHandler + { + public: + TFeedbackHandlerWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, TScopedRunningTimeTracker& rTimeGuard); + virtual ~TFeedbackHandlerWrapper(); + + TFeedbackHandlerWrapper(const TFeedbackHandlerWrapper&) = delete; + TFeedbackHandlerWrapper& operator=(const TFeedbackHandlerWrapper&) = delete; + + virtual TFeedbackResult FileError(const TString& strSrcPath, const TString& strDstPath, EFileError eFileError, unsigned long ulError) override; + virtual TFeedbackResult FileAlreadyExists(const TFileInfo& spSrcFileInfo, const TFileInfo& spDstFileInfo) override; + virtual TFeedbackResult NotEnoughSpace(const TString& strSrcPath, const TString& strDstPath, unsigned long long ullRequiredSize) override; + virtual TFeedbackResult OperationFinished() override; + virtual TFeedbackResult OperationError() override; + + virtual void RestoreDefaults() override; + + virtual void Store(const ISerializerContainerPtr& spContainer) const override; + virtual void Load(const ISerializerContainerPtr& spContainer) override; + + virtual DWORD GetRetryInterval() const override; + + private: + IFeedbackHandlerPtr m_spFeedbackHandler; + TScopedRunningTimeTracker& m_rTimeGuard; + }; + + typedef std::shared_ptr TFeedbackHandlerWrapperPtr; +} + +#endif Index: src/libchcore/TFeedbackResult.cpp =================================================================== diff -u -r4d1f8110906889d56552771fb58a6de86bc54a29 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackResult.cpp (.../TFeedbackResult.cpp) (revision 4d1f8110906889d56552771fb58a6de86bc54a29) +++ src/libchcore/TFeedbackResult.cpp (.../TFeedbackResult.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFeedbackResult.h" - -namespace chcore -{ - TFeedbackResult::TFeedbackResult(EFeedbackResult eFeedbackResult, bool bAutomatedReply) : - m_eFeedbackResult(eFeedbackResult), - m_bAutomatedReply(bAutomatedReply) - { - } - - EFeedbackResult TFeedbackResult::GetResult() const - { - return m_eFeedbackResult; - } - - bool TFeedbackResult::IsAutomatedReply() const - { - return m_bAutomatedReply; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFeedbackResult.h" + +namespace chcore +{ + TFeedbackResult::TFeedbackResult(EFeedbackResult eFeedbackResult, bool bAutomatedReply) : + m_eFeedbackResult(eFeedbackResult), + m_bAutomatedReply(bAutomatedReply) + { + } + + EFeedbackResult TFeedbackResult::GetResult() const + { + return m_eFeedbackResult; + } + + bool TFeedbackResult::IsAutomatedReply() const + { + return m_bAutomatedReply; + } +} Index: src/libchcore/TFeedbackResult.h =================================================================== diff -u -r4d1f8110906889d56552771fb58a6de86bc54a29 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFeedbackResult.h (.../TFeedbackResult.h) (revision 4d1f8110906889d56552771fb58a6de86bc54a29) +++ src/libchcore/TFeedbackResult.h (.../TFeedbackResult.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,41 +1,41 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFEEDBACKRESULT_H__ -#define __TFEEDBACKRESULT_H__ - -#include "libchcore.h" -#include "EFeedbackResult.h" - -namespace chcore -{ - class LIBCHCORE_API TFeedbackResult - { - public: - TFeedbackResult(EFeedbackResult eFeedbackResult, bool bAutomatedReply); - - EFeedbackResult GetResult() const; - bool IsAutomatedReply() const; - - private: - EFeedbackResult m_eFeedbackResult; - bool m_bAutomatedReply; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFEEDBACKRESULT_H__ +#define __TFEEDBACKRESULT_H__ + +#include "libchcore.h" +#include "EFeedbackResult.h" + +namespace chcore +{ + class LIBCHCORE_API TFeedbackResult + { + public: + TFeedbackResult(EFeedbackResult eFeedbackResult, bool bAutomatedReply); + + EFeedbackResult GetResult() const; + bool IsAutomatedReply() const; + + private: + EFeedbackResult m_eFeedbackResult; + bool m_bAutomatedReply; + }; +} + +#endif Index: src/libchcore/TFileException.cpp =================================================================== diff -u -r71c49ab6ac2e657dee997cb9129c7d0d4dde21b6 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFileException.cpp (.../TFileException.cpp) (revision 71c49ab6ac2e657dee997cb9129c7d0d4dde21b6) +++ src/libchcore/TFileException.cpp (.../TFileException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,43 +1,43 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFileException.h" - -namespace chcore -{ - TFileException::TFileException(EGeneralErrors eErrorCode, DWORD dwNativeErrorCode, const TSmartPath& path, wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TCoreException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_path(path), - m_dwNativeErrorCode(dwNativeErrorCode) - { - } - - void TFileException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d, win32 error code: %lu, path: %s)"), m_pszMsg, m_eErrorCode, m_dwNativeErrorCode, m_path.ToString()); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } - - void TFileException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const - { - _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nWin32 error code: %lu\r\nFile: %s\r\nSource file: %s\r\nFunction: %s\r\nLine no: %lu"), - m_pszMsg, m_eErrorCode, m_dwNativeErrorCode, m_path.ToString(), m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); - pszBuffer[stMaxBuffer - 1] = _T('\0'); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFileException.h" + +namespace chcore +{ + TFileException::TFileException(EGeneralErrors eErrorCode, DWORD dwNativeErrorCode, const TSmartPath& path, wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TCoreException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_path(path), + m_dwNativeErrorCode(dwNativeErrorCode) + { + } + + void TFileException::GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s (error code: %d, win32 error code: %lu, path: %s)"), m_pszMsg, m_eErrorCode, m_dwNativeErrorCode, m_path.ToString()); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } + + void TFileException::GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const + { + _snwprintf_s(pszBuffer, stMaxBuffer, _TRUNCATE, _T("%s\r\nError code: %d\r\nWin32 error code: %lu\r\nFile: %s\r\nSource file: %s\r\nFunction: %s\r\nLine no: %lu"), + m_pszMsg, m_eErrorCode, m_dwNativeErrorCode, m_path.ToString(), m_pszFile, m_pszFunction, (unsigned long)m_stLineNumber); + pszBuffer[stMaxBuffer - 1] = _T('\0'); + } +} Index: src/libchcore/TFileException.h =================================================================== diff -u -rad4fe0f8085b15527158073aa76eb2d9ef80b0e5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFileException.h (.../TFileException.h) (revision ad4fe0f8085b15527158073aa76eb2d9ef80b0e5) +++ src/libchcore/TFileException.h (.../TFileException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,47 +1,47 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFILEWIN32EXCEPTION_H__ -#define __TFILEWIN32EXCEPTION_H__ - -#include "libchcore.h" -#include "ErrorCodes.h" -#include "TPath.h" -#include "TCoreException.h" - -namespace chcore -{ - class LIBCHCORE_API TFileException : public TCoreException - { - public: - TFileException(EGeneralErrors eErrorCode, DWORD dwNativeErrorCode, const TSmartPath& path, wchar_t* pszMsg, - const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - - virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; - - const TSmartPath& GetPath() const { return m_path; } - DWORD GetNativeError() const { return m_dwNativeErrorCode; } - - private: - DWORD m_dwNativeErrorCode; - TSmartPath m_path; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFILEWIN32EXCEPTION_H__ +#define __TFILEWIN32EXCEPTION_H__ + +#include "libchcore.h" +#include "ErrorCodes.h" +#include "TPath.h" +#include "TCoreException.h" + +namespace chcore +{ + class LIBCHCORE_API TFileException : public TCoreException + { + public: + TFileException(EGeneralErrors eErrorCode, DWORD dwNativeErrorCode, const TSmartPath& path, wchar_t* pszMsg, + const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + + virtual void GetErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + virtual void GetDetailedErrorInfo(wchar_t* pszBuffer, size_t stMaxBuffer) const; + + const TSmartPath& GetPath() const { return m_path; } + DWORD GetNativeError() const { return m_dwNativeErrorCode; } + + private: + DWORD m_dwNativeErrorCode; + TSmartPath m_path; + }; +} + +#endif Index: src/libchcore/TFileInfoFwd.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFileInfoFwd.h (.../TFileInfoFwd.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TFileInfoFwd.h (.../TFileInfoFwd.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,28 +1,28 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFILEINFOFWD_H__ -#define __TFILEINFOFWD_H__ - -namespace chcore -{ - class TFileInfo; - typedef std::shared_ptr TFileInfoPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFILEINFOFWD_H__ +#define __TFILEINFOFWD_H__ + +namespace chcore +{ + class TFileInfo; + typedef std::shared_ptr TFileInfoPtr; +} + +#endif Index: src/libchcore/TFileTime.cpp =================================================================== diff -u -rf866db90e4b058a4f2e13cc6cf076d1e0bf2d956 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFileTime.cpp (.../TFileTime.cpp) (revision f866db90e4b058a4f2e13cc6cf076d1e0bf2d956) +++ src/libchcore/TFileTime.cpp (.../TFileTime.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,98 +1,98 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFileTime.h" - -namespace chcore -{ - TFileTime::TFileTime() - { - m_ftTime.dwHighDateTime = 0; - m_ftTime.dwLowDateTime = 0; - } - - TFileTime::TFileTime(const TFileTime& rSrc) : - m_ftTime(rSrc.m_ftTime) - { - } - - TFileTime::TFileTime(const FILETIME& rftTime) : - m_ftTime(rftTime) - { - } - - TFileTime::~TFileTime() - { - } - - TFileTime& TFileTime::operator=(const TFileTime& rSrc) - { - if (this != &rSrc) - { - m_ftTime = rSrc.m_ftTime; - } - - return *this; - } - - TFileTime& TFileTime::operator=(const FILETIME& rSrc) - { - m_ftTime = rSrc; - - return *this; - } - - - bool TFileTime::operator==(const TFileTime& rSrc) const - { - return m_ftTime.dwHighDateTime == rSrc.m_ftTime.dwHighDateTime && m_ftTime.dwLowDateTime == rSrc.m_ftTime.dwLowDateTime; - } - - bool TFileTime::operator!=(const TFileTime& rSrc) const - { - return m_ftTime.dwHighDateTime != rSrc.m_ftTime.dwHighDateTime || m_ftTime.dwLowDateTime != rSrc.m_ftTime.dwLowDateTime; - } - - void TFileTime::FromUInt64(unsigned long long ullTime) - { - ULARGE_INTEGER uli; - uli.QuadPart = ullTime; - m_ftTime.dwLowDateTime = uli.LowPart; - m_ftTime.dwHighDateTime = uli.HighPart; - } - - unsigned long long TFileTime::ToUInt64() const - { - ULARGE_INTEGER uli; - uli.HighPart = m_ftTime.dwHighDateTime; - uli.LowPart = m_ftTime.dwLowDateTime; - - return uli.QuadPart; - } - - void TFileTime::SetCurrentTime() - { - GetSystemTimeAsFileTime(&m_ftTime); - } - - const FILETIME& TFileTime::GetAsFiletime() const - { - return m_ftTime; - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFileTime.h" + +namespace chcore +{ + TFileTime::TFileTime() + { + m_ftTime.dwHighDateTime = 0; + m_ftTime.dwLowDateTime = 0; + } + + TFileTime::TFileTime(const TFileTime& rSrc) : + m_ftTime(rSrc.m_ftTime) + { + } + + TFileTime::TFileTime(const FILETIME& rftTime) : + m_ftTime(rftTime) + { + } + + TFileTime::~TFileTime() + { + } + + TFileTime& TFileTime::operator=(const TFileTime& rSrc) + { + if (this != &rSrc) + { + m_ftTime = rSrc.m_ftTime; + } + + return *this; + } + + TFileTime& TFileTime::operator=(const FILETIME& rSrc) + { + m_ftTime = rSrc; + + return *this; + } + + + bool TFileTime::operator==(const TFileTime& rSrc) const + { + return m_ftTime.dwHighDateTime == rSrc.m_ftTime.dwHighDateTime && m_ftTime.dwLowDateTime == rSrc.m_ftTime.dwLowDateTime; + } + + bool TFileTime::operator!=(const TFileTime& rSrc) const + { + return m_ftTime.dwHighDateTime != rSrc.m_ftTime.dwHighDateTime || m_ftTime.dwLowDateTime != rSrc.m_ftTime.dwLowDateTime; + } + + void TFileTime::FromUInt64(unsigned long long ullTime) + { + ULARGE_INTEGER uli; + uli.QuadPart = ullTime; + m_ftTime.dwLowDateTime = uli.LowPart; + m_ftTime.dwHighDateTime = uli.HighPart; + } + + unsigned long long TFileTime::ToUInt64() const + { + ULARGE_INTEGER uli; + uli.HighPart = m_ftTime.dwHighDateTime; + uli.LowPart = m_ftTime.dwLowDateTime; + + return uli.QuadPart; + } + + void TFileTime::SetCurrentTime() + { + GetSystemTimeAsFileTime(&m_ftTime); + } + + const FILETIME& TFileTime::GetAsFiletime() const + { + return m_ftTime; + } +} Index: src/libchcore/TFileTime.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFileTime.h (.../TFileTime.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TFileTime.h (.../TFileTime.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,54 +1,54 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFILETIME_H__ -#define __TFILETIME_H__ - -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API TFileTime - { - public: - TFileTime(); - // cppcheck-suppress noExplicitConstructor - TFileTime(const FILETIME& rftTime); - TFileTime(const TFileTime& rSrc); - ~TFileTime(); - - TFileTime& operator=(const TFileTime& rSrc); - TFileTime& operator=(const FILETIME& rSrc); - - bool operator==(const TFileTime& rSrc) const; - bool operator!=(const TFileTime& rSrc) const; - - void SetCurrentTime(); - const FILETIME& GetAsFiletime() const; - - void FromUInt64(unsigned long long ullTime); - unsigned long long ToUInt64() const; - - private: - FILETIME m_ftTime; - }; - - typedef std::shared_ptr TFileTimePtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFILETIME_H__ +#define __TFILETIME_H__ + +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API TFileTime + { + public: + TFileTime(); + // cppcheck-suppress noExplicitConstructor + TFileTime(const FILETIME& rftTime); + TFileTime(const TFileTime& rSrc); + ~TFileTime(); + + TFileTime& operator=(const TFileTime& rSrc); + TFileTime& operator=(const FILETIME& rSrc); + + bool operator==(const TFileTime& rSrc) const; + bool operator!=(const TFileTime& rSrc) const; + + void SetCurrentTime(); + const FILETIME& GetAsFiletime() const; + + void FromUInt64(unsigned long long ullTime); + unsigned long long ToUInt64() const; + + private: + FILETIME m_ftTime; + }; + + typedef std::shared_ptr TFileTimePtr; +} + +#endif Index: src/libchcore/TFilesystemFeedbackWrapper.cpp =================================================================== diff -u -rfc42a6399299d4b90268695740a9e6e35ab25b05 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFilesystemFeedbackWrapper.cpp (.../TFilesystemFeedbackWrapper.cpp) (revision fc42a6399299d4b90268695740a9e6e35ab25b05) +++ src/libchcore/TFilesystemFeedbackWrapper.cpp (.../TFilesystemFeedbackWrapper.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,426 +1,426 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFilesystemFeedbackWrapper.h" -#include -#include "TFileException.h" -#include "TFileInfo.h" -#include "TWorkerThreadController.h" - -namespace chcore -{ - TFilesystemFeedbackWrapper::TFilesystemFeedbackWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemPtr& spFilesystem, const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController) : - m_spFeedbackHandler(spFeedbackHandler), - m_spFilesystem(spFilesystem), - m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem")), - m_rThreadController(rThreadController) - { - if (!spFilesystem) - throw TCoreException(eErr_InvalidArgument, L"Filesystem not provided", LOCATION); - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::CreateDirectoryFB(const TSmartPath& pathDirectory) - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - try - { - m_spFilesystem->CreateDirectory(pathDirectory, false); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - if (dwLastError == ERROR_ALREADY_EXISTS) - return TSubTaskBase::eSubResult_Continue; - - // log - TString strFormat; - strFormat = _T("Error %errno while calling CreateDirectory %path (ProcessFiles)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), pathDirectory.ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathDirectory.ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_Continue; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while (bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - bool TFilesystemFeedbackWrapper::WasKillRequested(const TFeedbackResult& rFeedbackResult) const - { - if(m_rThreadController.KillRequested(rFeedbackResult.IsAutomatedReply() ? m_spFeedbackHandler->GetRetryInterval() : 0)) - return true; - return false; - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::CheckForFreeSpaceFB(const TSmartPath& pathFirstSrc, const TSmartPath& pathDestination, unsigned long long ullNeededSize) - { - unsigned long long ullAvailableSize = 0, ullTotal = 0; - TFeedbackResult frResult(eResult_Unknown, false); - bool bRetry = false; - - do - { - bRetry = false; - - LOG_INFO(m_spLog) << _T("Checking for free space on destination disk..."); - - // get free space - DWORD dwLastError = ERROR_SUCCESS; - bool bCheckFailed = false; - try - { - m_spFilesystem->GetDynamicFreeSpace(pathDestination, ullAvailableSize, ullTotal); - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - bCheckFailed = true; - } - - if (bCheckFailed) - { - TString strFormat; - strFormat = _T("Error %errno while checking free space at %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), pathDestination.ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - frResult = m_spFeedbackHandler->FileError(pathDestination.ToWString(), TString(), EFileError::eCheckForFreeSpace, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_Continue; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - } - - if (!bRetry && ullNeededSize > ullAvailableSize) - { - TString strFormat = _T("Not enough free space on disk - needed %needsize bytes for data, available: %availablesize bytes."); - strFormat.Replace(_T("%needsize"), boost::lexical_cast(ullNeededSize).c_str()); - strFormat.Replace(_T("%availablesize"), boost::lexical_cast(ullAvailableSize).c_str()); - LOG_WARNING(m_spLog) << strFormat.c_str(); - - frResult = m_spFeedbackHandler->NotEnoughSpace(pathFirstSrc.ToWString(), pathDestination.ToWString(), ullNeededSize); - switch (frResult.GetResult()) - { - case eResult_Cancel: - LOG_INFO(m_spLog) << _T("Cancel request while checking for free space on disk."); - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - LOG_INFO(m_spLog) << _T("Retrying to read drive's free space..."); - bRetry = true; - break; - - case eResult_Ignore: - LOG_INFO(m_spLog) << _T("Ignored warning about not enough place on disk to copy data."); - return TSubTaskBase::eSubResult_Continue; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - } - - if(bRetry && WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while (bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::RemoveDirectoryFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles) - { - bool bRetry = false; - do - { - bRetry = false; - DWORD dwLastError = ERROR_SUCCESS; - - try - { - DWORD dwAttributes = spFileInfo->GetAttributes(); - if((dwAttributes & FILE_ATTRIBUTE_READONLY) && !bProtectReadOnlyFiles) - m_spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), dwAttributes & ~FILE_ATTRIBUTE_READONLY); - - m_spFilesystem->RemoveDirectory(spFileInfo->GetFullFilePath()); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - if(dwLastError == ERROR_PATH_NOT_FOUND || dwLastError == ERROR_FILE_NOT_FOUND) - return TSubTaskBase::eSubResult_Continue; - - // log - TString strFormat = _T("Error #%errno while deleting folder %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - LOG_INFO(m_spLog) << _T("Cancel request while deleting file."); - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; // no fcIndex bump, since we are trying again - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_Continue; // just do nothing - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while (bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::DeleteFileFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles) - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - try - { - DWORD dwAttributes = spFileInfo->GetAttributes(); - if((dwAttributes & FILE_ATTRIBUTE_READONLY) && !bProtectReadOnlyFiles) - m_spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), dwAttributes & ~FILE_ATTRIBUTE_READONLY); - - m_spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - if (dwLastError == ERROR_PATH_NOT_FOUND || dwLastError == ERROR_FILE_NOT_FOUND) - return TSubTaskBase::eSubResult_Continue; - - // log - TString strFormat = _T("Error #%errno while deleting file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - LOG_INFO(m_spLog) << _T("Cancel request while deleting file."); - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_Continue; // just do nothing - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::FastMoveFB(const TFileInfoPtr& spFileInfo, const TSmartPath& pathDestination, const TBasePathDataPtr& spBasePath) - { - bool bRetry = false; - do - { - bRetry = false; - - TSmartPath pathSrc = spBasePath->GetSrcPath(); - - DWORD dwLastError = ERROR_SUCCESS; - try - { - m_spFilesystem->FastMove(pathSrc, pathDestination); - spBasePath->SetSkipFurtherProcessing(true); // mark that this path should not be processed any further - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - // check if this is one of the errors, that will just cause fast move to skip - if (dwLastError == ERROR_ACCESS_DENIED || dwLastError == ERROR_ALREADY_EXISTS || dwLastError == ERROR_NOT_SAME_DEVICE) - { - return TSubTaskBase::eSubResult_Continue; - } - - //log - TString strFormat = _T("Error %errno while calling fast move %srcpath -> %dstpath (TSubTaskFastMove)"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%srcpath"), spFileInfo->GetFullFilePath().ToString()); - strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathSrc.ToWString(), pathDestination.ToWString(), EFileError::eFastMoveError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while (bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::GetFileInfoFB(const TSmartPath& pathCurrent, TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePath) - { - bool bRetry = false; - do - { - bRetry = false; - - // read attributes of src file/folder - DWORD dwLastError = ERROR_SUCCESS; - try - { - m_spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eRetrieveFileInfo, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFilesystemFeedbackWrapper.h" +#include +#include "TFileException.h" +#include "TFileInfo.h" +#include "TWorkerThreadController.h" + +namespace chcore +{ + TFilesystemFeedbackWrapper::TFilesystemFeedbackWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemPtr& spFilesystem, const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController) : + m_spFeedbackHandler(spFeedbackHandler), + m_spFilesystem(spFilesystem), + m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem")), + m_rThreadController(rThreadController) + { + if (!spFilesystem) + throw TCoreException(eErr_InvalidArgument, L"Filesystem not provided", LOCATION); + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::CreateDirectoryFB(const TSmartPath& pathDirectory) + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + try + { + m_spFilesystem->CreateDirectory(pathDirectory, false); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + if (dwLastError == ERROR_ALREADY_EXISTS) + return TSubTaskBase::eSubResult_Continue; + + // log + TString strFormat; + strFormat = _T("Error %errno while calling CreateDirectory %path (ProcessFiles)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), pathDirectory.ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathDirectory.ToWString(), TString(), EFileError::eCreateError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_Continue; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while (bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + bool TFilesystemFeedbackWrapper::WasKillRequested(const TFeedbackResult& rFeedbackResult) const + { + if(m_rThreadController.KillRequested(rFeedbackResult.IsAutomatedReply() ? m_spFeedbackHandler->GetRetryInterval() : 0)) + return true; + return false; + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::CheckForFreeSpaceFB(const TSmartPath& pathFirstSrc, const TSmartPath& pathDestination, unsigned long long ullNeededSize) + { + unsigned long long ullAvailableSize = 0, ullTotal = 0; + TFeedbackResult frResult(eResult_Unknown, false); + bool bRetry = false; + + do + { + bRetry = false; + + LOG_INFO(m_spLog) << _T("Checking for free space on destination disk..."); + + // get free space + DWORD dwLastError = ERROR_SUCCESS; + bool bCheckFailed = false; + try + { + m_spFilesystem->GetDynamicFreeSpace(pathDestination, ullAvailableSize, ullTotal); + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + bCheckFailed = true; + } + + if (bCheckFailed) + { + TString strFormat; + strFormat = _T("Error %errno while checking free space at %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), pathDestination.ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + frResult = m_spFeedbackHandler->FileError(pathDestination.ToWString(), TString(), EFileError::eCheckForFreeSpace, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_Continue; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + } + + if (!bRetry && ullNeededSize > ullAvailableSize) + { + TString strFormat = _T("Not enough free space on disk - needed %needsize bytes for data, available: %availablesize bytes."); + strFormat.Replace(_T("%needsize"), boost::lexical_cast(ullNeededSize).c_str()); + strFormat.Replace(_T("%availablesize"), boost::lexical_cast(ullAvailableSize).c_str()); + LOG_WARNING(m_spLog) << strFormat.c_str(); + + frResult = m_spFeedbackHandler->NotEnoughSpace(pathFirstSrc.ToWString(), pathDestination.ToWString(), ullNeededSize); + switch (frResult.GetResult()) + { + case eResult_Cancel: + LOG_INFO(m_spLog) << _T("Cancel request while checking for free space on disk."); + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + LOG_INFO(m_spLog) << _T("Retrying to read drive's free space..."); + bRetry = true; + break; + + case eResult_Ignore: + LOG_INFO(m_spLog) << _T("Ignored warning about not enough place on disk to copy data."); + return TSubTaskBase::eSubResult_Continue; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + } + + if(bRetry && WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while (bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::RemoveDirectoryFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles) + { + bool bRetry = false; + do + { + bRetry = false; + DWORD dwLastError = ERROR_SUCCESS; + + try + { + DWORD dwAttributes = spFileInfo->GetAttributes(); + if((dwAttributes & FILE_ATTRIBUTE_READONLY) && !bProtectReadOnlyFiles) + m_spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), dwAttributes & ~FILE_ATTRIBUTE_READONLY); + + m_spFilesystem->RemoveDirectory(spFileInfo->GetFullFilePath()); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + if(dwLastError == ERROR_PATH_NOT_FOUND || dwLastError == ERROR_FILE_NOT_FOUND) + return TSubTaskBase::eSubResult_Continue; + + // log + TString strFormat = _T("Error #%errno while deleting folder %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + LOG_INFO(m_spLog) << _T("Cancel request while deleting file."); + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; // no fcIndex bump, since we are trying again + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_Continue; // just do nothing + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while (bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::DeleteFileFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles) + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + try + { + DWORD dwAttributes = spFileInfo->GetAttributes(); + if((dwAttributes & FILE_ATTRIBUTE_READONLY) && !bProtectReadOnlyFiles) + m_spFilesystem->SetAttributes(spFileInfo->GetFullFilePath(), dwAttributes & ~FILE_ATTRIBUTE_READONLY); + + m_spFilesystem->DeleteFile(spFileInfo->GetFullFilePath()); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + if (dwLastError == ERROR_PATH_NOT_FOUND || dwLastError == ERROR_FILE_NOT_FOUND) + return TSubTaskBase::eSubResult_Continue; + + // log + TString strFormat = _T("Error #%errno while deleting file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(spFileInfo->GetFullFilePath().ToWString(), TString(), EFileError::eDeleteError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + LOG_INFO(m_spLog) << _T("Cancel request while deleting file."); + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_Continue; // just do nothing + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::FastMoveFB(const TFileInfoPtr& spFileInfo, const TSmartPath& pathDestination, const TBasePathDataPtr& spBasePath) + { + bool bRetry = false; + do + { + bRetry = false; + + TSmartPath pathSrc = spBasePath->GetSrcPath(); + + DWORD dwLastError = ERROR_SUCCESS; + try + { + m_spFilesystem->FastMove(pathSrc, pathDestination); + spBasePath->SetSkipFurtherProcessing(true); // mark that this path should not be processed any further + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + // check if this is one of the errors, that will just cause fast move to skip + if (dwLastError == ERROR_ACCESS_DENIED || dwLastError == ERROR_ALREADY_EXISTS || dwLastError == ERROR_NOT_SAME_DEVICE) + { + return TSubTaskBase::eSubResult_Continue; + } + + //log + TString strFormat = _T("Error %errno while calling fast move %srcpath -> %dstpath (TSubTaskFastMove)"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%srcpath"), spFileInfo->GetFullFilePath().ToString()); + strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathSrc.ToWString(), pathDestination.ToWString(), EFileError::eFastMoveError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while (bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFeedbackWrapper::GetFileInfoFB(const TSmartPath& pathCurrent, TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePath) + { + bool bRetry = false; + do + { + bRetry = false; + + // read attributes of src file/folder + DWORD dwLastError = ERROR_SUCCESS; + try + { + m_spFilesystem->GetFileInfo(pathCurrent, spFileInfo, spBasePath); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(pathCurrent.ToWString(), TString(), EFileError::eRetrieveFileInfo, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } +} Index: src/libchcore/TFilesystemFeedbackWrapper.h =================================================================== diff -u -rc0d9a798f9fbbeda239b84721ed864f9727e1ddc -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFilesystemFeedbackWrapper.h (.../TFilesystemFeedbackWrapper.h) (revision c0d9a798f9fbbeda239b84721ed864f9727e1ddc) +++ src/libchcore/TFilesystemFeedbackWrapper.h (.../TFilesystemFeedbackWrapper.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,59 +1,59 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFILESYSTEMFEEDBACKWRAPPER_H__ -#define __TFILESYSTEMFEEDBACKWRAPPER_H__ - -#include "IFilesystem.h" -#include "TSubTaskBase.h" -#include "../liblogger/TLogger.h" - -namespace chcore -{ - class TWorkerThreadController; - - class TFilesystemFeedbackWrapper - { - public: - TFilesystemFeedbackWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemPtr& spFilesystem, const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController); - TFilesystemFeedbackWrapper& operator=(const TFilesystemFeedbackWrapper&) = delete; - - TSubTaskBase::ESubOperationResult CreateDirectoryFB(const TSmartPath& pathDirectory); - TSubTaskBase::ESubOperationResult CheckForFreeSpaceFB(const TSmartPath& pathFirstSrc, const TSmartPath& pathDestination, unsigned long long ullNeededSize); - - TSubTaskBase::ESubOperationResult RemoveDirectoryFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles); - TSubTaskBase::ESubOperationResult DeleteFileFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles); - - TSubTaskBase::ESubOperationResult FastMoveFB(const TFileInfoPtr& spFileInfo, const TSmartPath& pathDestination, - const TBasePathDataPtr& spBasePath); - - TSubTaskBase::ESubOperationResult GetFileInfoFB(const TSmartPath& pathCurrent, - TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePath); - - private: - bool WasKillRequested(const TFeedbackResult& rFeedbackResult) const; - - private: - IFeedbackHandlerPtr m_spFeedbackHandler; - IFilesystemPtr m_spFilesystem; - logger::TLoggerPtr m_spLog; - TWorkerThreadController& m_rThreadController; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFILESYSTEMFEEDBACKWRAPPER_H__ +#define __TFILESYSTEMFEEDBACKWRAPPER_H__ + +#include "IFilesystem.h" +#include "TSubTaskBase.h" +#include "../liblogger/TLogger.h" + +namespace chcore +{ + class TWorkerThreadController; + + class TFilesystemFeedbackWrapper + { + public: + TFilesystemFeedbackWrapper(const IFeedbackHandlerPtr& spFeedbackHandler, const IFilesystemPtr& spFilesystem, const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController); + TFilesystemFeedbackWrapper& operator=(const TFilesystemFeedbackWrapper&) = delete; + + TSubTaskBase::ESubOperationResult CreateDirectoryFB(const TSmartPath& pathDirectory); + TSubTaskBase::ESubOperationResult CheckForFreeSpaceFB(const TSmartPath& pathFirstSrc, const TSmartPath& pathDestination, unsigned long long ullNeededSize); + + TSubTaskBase::ESubOperationResult RemoveDirectoryFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles); + TSubTaskBase::ESubOperationResult DeleteFileFB(const TFileInfoPtr& spFileInfo, bool bProtectReadOnlyFiles); + + TSubTaskBase::ESubOperationResult FastMoveFB(const TFileInfoPtr& spFileInfo, const TSmartPath& pathDestination, + const TBasePathDataPtr& spBasePath); + + TSubTaskBase::ESubOperationResult GetFileInfoFB(const TSmartPath& pathCurrent, + TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePath); + + private: + bool WasKillRequested(const TFeedbackResult& rFeedbackResult) const; + + private: + IFeedbackHandlerPtr m_spFeedbackHandler; + IFilesystemPtr m_spFilesystem; + logger::TLoggerPtr m_spLog; + TWorkerThreadController& m_rThreadController; + }; +} + +#endif Index: src/libchcore/TFilesystemFileFeedbackWrapper.cpp =================================================================== diff -u -rfc42a6399299d4b90268695740a9e6e35ab25b05 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFilesystemFileFeedbackWrapper.cpp (.../TFilesystemFileFeedbackWrapper.cpp) (revision fc42a6399299d4b90268695740a9e6e35ab25b05) +++ src/libchcore/TFilesystemFileFeedbackWrapper.cpp (.../TFilesystemFileFeedbackWrapper.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,485 +1,485 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TFilesystemFileFeedbackWrapper.h" -#include "TFileException.h" -#include -#include "TFileInfo.h" -#include "TWorkerThreadController.h" -#include "TOverlappedDataBuffer.h" - -namespace chcore -{ - TFilesystemFileFeedbackWrapper::TFilesystemFileFeedbackWrapper(const IFilesystemFilePtr& spFile, - const IFeedbackHandlerPtr& spFeedbackHandler, const logger::TLogFileDataPtr& spLogFileData, - TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : - m_spFile(spFile), - m_spFeedbackHandler(spFeedbackHandler), - m_spLog(std::make_unique(spLogFileData, L"Filesystem-File")), - m_rThreadController(rThreadController), - m_spFilesystem(spFilesystem) - { - if (!spFeedbackHandler) - throw TCoreException(eErr_InvalidArgument, L"spFeedbackHandler is NULL", LOCATION); - if (!spFile) - throw TCoreException(eErr_InvalidArgument, L"spFile is NULL", LOCATION); - if (!spFilesystem) - throw TCoreException(eErr_InvalidArgument, L"spFilesystem is NULL", LOCATION); - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleFileAlreadyExistsFB(const TFileInfoPtr& spSrcFileInfo, bool& bShouldAppend) - { - bShouldAppend = false; - - // read info about the existing destination file, - TFileInfo tDstFileInfo; - m_spFile->GetFileInfo(tDstFileInfo); - - // src and dst files are the same - TFeedbackResult frResult = m_spFeedbackHandler->FileAlreadyExists(*spSrcFileInfo, tDstFileInfo); - switch(frResult.GetResult()) - { - case eResult_Overwrite: - bShouldAppend = false; - return TSubTaskBase::eSubResult_Continue; - - case eResult_CopyRest: - bShouldAppend = true; - return TSubTaskBase::eSubResult_Continue; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - case eResult_Cancel: - { - // log - TString strFormat = _T("Cancel request when handling already existing file %path"); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_INFO(m_spLog) << strFormat.c_str(); - - return TSubTaskBase::eSubResult_CancelRequest; - } - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::TruncateFileFB(file_size_t fsNewSize) - { - bool bRetry = false; - do - { - DWORD dwLastError = ERROR_SUCCESS; - - try - { - m_spFile->Truncate(fsNewSize); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while truncating file %path to 0"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eResizeError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::ReadFileFB(TOverlappedDataBuffer& rBuffer) - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - - try - { - m_spFile->ReadFile(rBuffer); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eReadError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::WriteFileFB(TOverlappedDataBuffer& rBuffer) - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - - try - { - m_spFile->WriteFile(rBuffer); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eWriteError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::FinalizeFileFB(TOverlappedDataBuffer& rBuffer) - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - - try - { - m_spFile->FinalizeFile(rBuffer); - return TSubTaskBase::eSubResult_Continue; - } - catch (const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while trying to finalize file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eFinalizeError, dwLastError); - switch (frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleReadError(TOverlappedDataBuffer& rBuffer) - { - DWORD dwLastError = rBuffer.GetErrorCode(); - - // log - TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eReadError, dwLastError); - switch(frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - return TSubTaskBase::eSubResult_Retry; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Unknown feedback result", LOCATION); - } - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleWriteError(TOverlappedDataBuffer& rBuffer) - { - DWORD dwLastError = rBuffer.GetErrorCode(); - - // log - TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(rBuffer.GetErrorCode()).c_str()); - strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eWriteError, dwLastError); - switch(frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - return TSubTaskBase::eSubResult_Retry; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Unknown feedback result", LOCATION); - } - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::IsFreshlyCreated(bool& bIsFreshlyCreated) const - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - - try - { - bIsFreshlyCreated = m_spFile->IsFreshlyCreated(); - return TSubTaskBase::eSubResult_Continue; - } - catch(const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while trying to retrieve freshly-created flag for file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); - switch(frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - TSmartPath TFilesystemFileFeedbackWrapper::GetFilePath() const - { - return m_spFile->GetFilePath(); - } - - TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::GetFileSize(file_size_t& fsSize) const - { - bool bRetry = false; - do - { - bRetry = false; - - DWORD dwLastError = ERROR_SUCCESS; - - try - { - fsSize = m_spFile->GetFileSize(); - return TSubTaskBase::eSubResult_Continue; - } - catch(const TFileException& e) - { - dwLastError = e.GetNativeError(); - } - - TString strFormat = _T("Error %errno while trying to retrieve file size of file %path"); - strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); - strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); - LOG_ERROR(m_spLog) << strFormat.c_str(); - - TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eRetrieveFileInfo, dwLastError); - switch(frResult.GetResult()) - { - case eResult_Cancel: - return TSubTaskBase::eSubResult_CancelRequest; - - case eResult_Retry: - bRetry = true; - break; - - case eResult_Pause: - return TSubTaskBase::eSubResult_PauseRequest; - - case eResult_Skip: - return TSubTaskBase::eSubResult_SkipFile; - - default: - BOOST_ASSERT(FALSE); // unknown result - throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); - } - - if(WasKillRequested(frResult)) - return TSubTaskBase::eSubResult_KillRequest; - } - while(bRetry); - - return TSubTaskBase::eSubResult_Continue; - } - - file_size_t TFilesystemFileFeedbackWrapper::GetSeekPositionForResume(file_size_t fsLastAvailablePosition) - { - return m_spFile->GetSeekPositionForResume(fsLastAvailablePosition); - } - - bool TFilesystemFileFeedbackWrapper::WasKillRequested(const TFeedbackResult& rFeedbackResult) const - { - if(m_rThreadController.KillRequested(rFeedbackResult.IsAutomatedReply() ? m_spFeedbackHandler->GetRetryInterval() : 0)) - return true; - return false; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TFilesystemFileFeedbackWrapper.h" +#include "TFileException.h" +#include +#include "TFileInfo.h" +#include "TWorkerThreadController.h" +#include "TOverlappedDataBuffer.h" + +namespace chcore +{ + TFilesystemFileFeedbackWrapper::TFilesystemFileFeedbackWrapper(const IFilesystemFilePtr& spFile, + const IFeedbackHandlerPtr& spFeedbackHandler, const logger::TLogFileDataPtr& spLogFileData, + TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : + m_spFile(spFile), + m_spFeedbackHandler(spFeedbackHandler), + m_spLog(std::make_unique(spLogFileData, L"Filesystem-File")), + m_rThreadController(rThreadController), + m_spFilesystem(spFilesystem) + { + if (!spFeedbackHandler) + throw TCoreException(eErr_InvalidArgument, L"spFeedbackHandler is NULL", LOCATION); + if (!spFile) + throw TCoreException(eErr_InvalidArgument, L"spFile is NULL", LOCATION); + if (!spFilesystem) + throw TCoreException(eErr_InvalidArgument, L"spFilesystem is NULL", LOCATION); + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleFileAlreadyExistsFB(const TFileInfoPtr& spSrcFileInfo, bool& bShouldAppend) + { + bShouldAppend = false; + + // read info about the existing destination file, + TFileInfo tDstFileInfo; + m_spFile->GetFileInfo(tDstFileInfo); + + // src and dst files are the same + TFeedbackResult frResult = m_spFeedbackHandler->FileAlreadyExists(*spSrcFileInfo, tDstFileInfo); + switch(frResult.GetResult()) + { + case eResult_Overwrite: + bShouldAppend = false; + return TSubTaskBase::eSubResult_Continue; + + case eResult_CopyRest: + bShouldAppend = true; + return TSubTaskBase::eSubResult_Continue; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + case eResult_Cancel: + { + // log + TString strFormat = _T("Cancel request when handling already existing file %path"); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_INFO(m_spLog) << strFormat.c_str(); + + return TSubTaskBase::eSubResult_CancelRequest; + } + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::TruncateFileFB(file_size_t fsNewSize) + { + bool bRetry = false; + do + { + DWORD dwLastError = ERROR_SUCCESS; + + try + { + m_spFile->Truncate(fsNewSize); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while truncating file %path to 0"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eResizeError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::ReadFileFB(TOverlappedDataBuffer& rBuffer) + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + + try + { + m_spFile->ReadFile(rBuffer); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eReadError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::WriteFileFB(TOverlappedDataBuffer& rBuffer) + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + + try + { + m_spFile->WriteFile(rBuffer); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eWriteError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::FinalizeFileFB(TOverlappedDataBuffer& rBuffer) + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + + try + { + m_spFile->FinalizeFile(rBuffer); + return TSubTaskBase::eSubResult_Continue; + } + catch (const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while trying to finalize file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eFinalizeError, dwLastError); + switch (frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleReadError(TOverlappedDataBuffer& rBuffer) + { + DWORD dwLastError = rBuffer.GetErrorCode(); + + // log + TString strFormat = _T("Error %errno while requesting read of %count bytes from source file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetRequestedDataSize()).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eReadError, dwLastError); + switch(frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + return TSubTaskBase::eSubResult_Retry; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Unknown feedback result", LOCATION); + } + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::HandleWriteError(TOverlappedDataBuffer& rBuffer) + { + DWORD dwLastError = rBuffer.GetErrorCode(); + + // log + TString strFormat = _T("Error %errno while trying to write %count bytes to destination file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(rBuffer.GetErrorCode()).c_str()); + strFormat.Replace(_T("%count"), boost::lexical_cast(rBuffer.GetBytesTransferred()).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eWriteError, dwLastError); + switch(frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + return TSubTaskBase::eSubResult_Retry; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Unknown feedback result", LOCATION); + } + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::IsFreshlyCreated(bool& bIsFreshlyCreated) const + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + + try + { + bIsFreshlyCreated = m_spFile->IsFreshlyCreated(); + return TSubTaskBase::eSubResult_Continue; + } + catch(const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while trying to retrieve freshly-created flag for file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eCreateError, dwLastError); + switch(frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + TSmartPath TFilesystemFileFeedbackWrapper::GetFilePath() const + { + return m_spFile->GetFilePath(); + } + + TSubTaskBase::ESubOperationResult TFilesystemFileFeedbackWrapper::GetFileSize(file_size_t& fsSize) const + { + bool bRetry = false; + do + { + bRetry = false; + + DWORD dwLastError = ERROR_SUCCESS; + + try + { + fsSize = m_spFile->GetFileSize(); + return TSubTaskBase::eSubResult_Continue; + } + catch(const TFileException& e) + { + dwLastError = e.GetNativeError(); + } + + TString strFormat = _T("Error %errno while trying to retrieve file size of file %path"); + strFormat.Replace(_T("%errno"), boost::lexical_cast(dwLastError).c_str()); + strFormat.Replace(_T("%path"), m_spFile->GetFilePath().ToString()); + LOG_ERROR(m_spLog) << strFormat.c_str(); + + TFeedbackResult frResult = m_spFeedbackHandler->FileError(m_spFile->GetFilePath().ToWString(), TString(), EFileError::eRetrieveFileInfo, dwLastError); + switch(frResult.GetResult()) + { + case eResult_Cancel: + return TSubTaskBase::eSubResult_CancelRequest; + + case eResult_Retry: + bRetry = true; + break; + + case eResult_Pause: + return TSubTaskBase::eSubResult_PauseRequest; + + case eResult_Skip: + return TSubTaskBase::eSubResult_SkipFile; + + default: + BOOST_ASSERT(FALSE); // unknown result + throw TCoreException(eErr_UnhandledCase, L"Feedback result unknown", LOCATION); + } + + if(WasKillRequested(frResult)) + return TSubTaskBase::eSubResult_KillRequest; + } + while(bRetry); + + return TSubTaskBase::eSubResult_Continue; + } + + file_size_t TFilesystemFileFeedbackWrapper::GetSeekPositionForResume(file_size_t fsLastAvailablePosition) + { + return m_spFile->GetSeekPositionForResume(fsLastAvailablePosition); + } + + bool TFilesystemFileFeedbackWrapper::WasKillRequested(const TFeedbackResult& rFeedbackResult) const + { + if(m_rThreadController.KillRequested(rFeedbackResult.IsAutomatedReply() ? m_spFeedbackHandler->GetRetryInterval() : 0)) + return true; + return false; + } +} Index: src/libchcore/TFilesystemFileFeedbackWrapper.h =================================================================== diff -u -rfc42a6399299d4b90268695740a9e6e35ab25b05 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TFilesystemFileFeedbackWrapper.h (.../TFilesystemFileFeedbackWrapper.h) (revision fc42a6399299d4b90268695740a9e6e35ab25b05) +++ src/libchcore/TFilesystemFileFeedbackWrapper.h (.../TFilesystemFileFeedbackWrapper.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,75 +1,75 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TFILESYSTEMFILEFEEDBACKWRAPPER_H__ -#define __TFILESYSTEMFILEFEEDBACKWRAPPER_H__ - -#include "IFilesystemFile.h" -#include "TSubTaskBase.h" -#include "IFeedbackHandler.h" -#include "IFilesystem.h" -#include "../liblogger/TLogger.h" - -namespace chcore -{ - class TWorkerThreadController; - - class TFilesystemFileFeedbackWrapper - { - public: - TFilesystemFileFeedbackWrapper(const IFilesystemFilePtr& spFile, const IFeedbackHandlerPtr& spFeedbackHandler, - const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController, - const IFilesystemPtr& spFilesystem); - TFilesystemFileFeedbackWrapper& operator=(const TFilesystemFileFeedbackWrapper&) = delete; - - TSubTaskBase::ESubOperationResult HandleFileAlreadyExistsFB(const TFileInfoPtr& spSrcFileInfo, bool& bShouldAppend); - - TSubTaskBase::ESubOperationResult TruncateFileFB(file_size_t fsNewSize); - - TSubTaskBase::ESubOperationResult ReadFileFB(TOverlappedDataBuffer& rBuffer); - TSubTaskBase::ESubOperationResult WriteFileFB(TOverlappedDataBuffer& rBuffer); - - TSubTaskBase::ESubOperationResult FinalizeFileFB(TOverlappedDataBuffer& rBuffer); - - TSubTaskBase::ESubOperationResult HandleReadError(TOverlappedDataBuffer& rBuffer); - TSubTaskBase::ESubOperationResult HandleWriteError(TOverlappedDataBuffer& rBuffer); - - TSubTaskBase::ESubOperationResult IsFreshlyCreated(bool& bIsFreshlyCreated) const; - - TSmartPath GetFilePath() const; - TSubTaskBase::ESubOperationResult GetFileSize(file_size_t& fsSize) const; - file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition); - - bool IsOpen() const { return m_spFile->IsOpen(); } - void Close() { m_spFile->Close(); } - - private: - bool WasKillRequested(const TFeedbackResult& rFeedbackResult) const; - - private: - IFilesystemFilePtr m_spFile; - IFeedbackHandlerPtr m_spFeedbackHandler; - IFilesystemPtr m_spFilesystem; - logger::TLoggerPtr m_spLog; - TWorkerThreadController& m_rThreadController; - }; - - using TFilesystemFileFeedbackWrapperPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TFILESYSTEMFILEFEEDBACKWRAPPER_H__ +#define __TFILESYSTEMFILEFEEDBACKWRAPPER_H__ + +#include "IFilesystemFile.h" +#include "TSubTaskBase.h" +#include "IFeedbackHandler.h" +#include "IFilesystem.h" +#include "../liblogger/TLogger.h" + +namespace chcore +{ + class TWorkerThreadController; + + class TFilesystemFileFeedbackWrapper + { + public: + TFilesystemFileFeedbackWrapper(const IFilesystemFilePtr& spFile, const IFeedbackHandlerPtr& spFeedbackHandler, + const logger::TLogFileDataPtr& spLogFileData, TWorkerThreadController& rThreadController, + const IFilesystemPtr& spFilesystem); + TFilesystemFileFeedbackWrapper& operator=(const TFilesystemFileFeedbackWrapper&) = delete; + + TSubTaskBase::ESubOperationResult HandleFileAlreadyExistsFB(const TFileInfoPtr& spSrcFileInfo, bool& bShouldAppend); + + TSubTaskBase::ESubOperationResult TruncateFileFB(file_size_t fsNewSize); + + TSubTaskBase::ESubOperationResult ReadFileFB(TOverlappedDataBuffer& rBuffer); + TSubTaskBase::ESubOperationResult WriteFileFB(TOverlappedDataBuffer& rBuffer); + + TSubTaskBase::ESubOperationResult FinalizeFileFB(TOverlappedDataBuffer& rBuffer); + + TSubTaskBase::ESubOperationResult HandleReadError(TOverlappedDataBuffer& rBuffer); + TSubTaskBase::ESubOperationResult HandleWriteError(TOverlappedDataBuffer& rBuffer); + + TSubTaskBase::ESubOperationResult IsFreshlyCreated(bool& bIsFreshlyCreated) const; + + TSmartPath GetFilePath() const; + TSubTaskBase::ESubOperationResult GetFileSize(file_size_t& fsSize) const; + file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition); + + bool IsOpen() const { return m_spFile->IsOpen(); } + void Close() { m_spFile->Close(); } + + private: + bool WasKillRequested(const TFeedbackResult& rFeedbackResult) const; + + private: + IFilesystemFilePtr m_spFile; + IFeedbackHandlerPtr m_spFeedbackHandler; + IFilesystemPtr m_spFilesystem; + logger::TLoggerPtr m_spLog; + TWorkerThreadController& m_rThreadController; + }; + + using TFilesystemFileFeedbackWrapperPtr = std::shared_ptr; +} + +#endif Index: src/libchcore/TLocalFilesystem.cpp =================================================================== diff -u -r789d0908abf8db57e27cfeac7045d9962f4b522a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystem.cpp (.../TLocalFilesystem.cpp) (revision 789d0908abf8db57e27cfeac7045d9962f4b522a) +++ src/libchcore/TLocalFilesystem.cpp (.../TLocalFilesystem.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,485 +1,485 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TLocalFilesystem.cpp -/// @date 2011/03/24 -/// @brief -// ============================================================================ -#include "stdafx.h" -#include "TLocalFilesystem.h" -#include -#include -#include "TAutoHandles.h" -#include "TFileInfo.h" -#include -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TPathContainer.h" -#include "TFileTime.h" -#include "TLocalFilesystemFile.h" -#include -#include "TLocalFilesystemFind.h" -#include "TFileException.h" -#include -#include "StreamingHelpers.h" - -namespace chcore -{ - TLocalFilesystem::TLocalFilesystem(const logger::TLogFileDataPtr& spLogFileData) : - m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem")) - { - } - - TLocalFilesystem::~TLocalFilesystem() - { - } - - UINT TLocalFilesystem::GetDriveData(const TSmartPath& spPath) - { - UINT uiDrvType = DRIVE_UNKNOWN; - if (!spPath.IsNetworkPath()) - { - if (!spPath.IsEmpty()) - { - TSmartPath pathDrive = spPath.GetDrive(); - pathDrive.AppendSeparatorIfDoesNotExist(); - - uiDrvType = GetDriveType(pathDrive.ToString()); - if (uiDrvType == DRIVE_NO_ROOT_DIR) - uiDrvType = DRIVE_UNKNOWN; - } - } - else - uiDrvType = DRIVE_REMOTE; - - return uiDrvType; - } - - bool TLocalFilesystem::PathExist(const TSmartPath& pathToCheck) - { - WIN32_FIND_DATA fd; - - TSmartPath findPath = pathToCheck; - bool bIsDrive = pathToCheck.IsDrive() || (pathToCheck.IsDriveWithRootDir()); - - if(bIsDrive) - { - // add '\\' if needed and '*' for marking that we look for e.g. c:\* - // instead of c:\, which would never be found the other way - findPath.AppendIfNotExists(_T("*"), false); - } - - findPath = PrependPathExtensionIfNeeded(findPath); - - LOG_DEBUG(m_spLog) << L"Checking for path existence: " << pathToCheck << L" (using search pattern: " << findPath << L")"; - - HANDLE hFind = FindFirstFile(findPath.ToString(), &fd); - if (hFind != INVALID_HANDLE_VALUE) - { - ::FindClose(hFind); - LOG_DEBUG(m_spLog) << L"Path: " << pathToCheck << L" exists"; - return true; - } - - LOG_DEBUG(m_spLog) << L"Path: " << pathToCheck << L" does not exist"; - return false; - } - - void TLocalFilesystem::SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) - { - TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFileDir); - - LOG_TRACE(m_spLog) << L"Setting file/directory times for " << fullPath << - L", creation-time: " << ftCreationTime.GetAsFiletime() << - L", last-access-time: " << ftLastAccessTime.GetAsFiletime() << - L", last-write-time: " << ftLastWriteTime.GetAsFiletime(); - - TAutoFileHandle hFile = TAutoFileHandle(CreateFile(fullPath.ToString(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, nullptr)); - if (hFile == INVALID_HANDLE_VALUE) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Open file failed with error: " << dwLastError << L". Cannot set file/directory times."; - - throw TFileException(eErr_CannotOpenFile, dwLastError, pathFileDir, L"Cannot open file for setting file/directory times", LOCATION); - } - - if (!SetFileTime(hFile, &ftCreationTime.GetAsFiletime(), &ftLastAccessTime.GetAsFiletime(), &ftLastWriteTime.GetAsFiletime())) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to set file/directory times. Error: " << dwLastError; - throw TFileException(eErr_CannotSetFileTimes, dwLastError, pathFileDir, L"Cannot set file/directory times", LOCATION); - } - LOG_TRACE(m_spLog) << L"File/directory times set successfully"; - } - - void TLocalFilesystem::SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) - { - TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFileDir); - - LOG_TRACE(m_spLog) << L"Setting file/directory attributes for " << fullPath << - L", attributes: " << dwAttributes; - - if (!::SetFileAttributes(fullPath.ToString(), dwAttributes)) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to set file/directory attributes. Error: " << dwLastError; - throw TFileException(eErr_CannotSetFileAttributes, dwLastError, pathFileDir, L"Cannot set file/directory attributes", LOCATION); - } - LOG_TRACE(m_spLog) << L"File/directory attributes set successfully"; - } - - void TLocalFilesystem::CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) - { - LOG_DEBUG(m_spLog) << L"Creating directory " << pathDirectory << - L", create-full-path: " << bCreateFullPath; - - if (!bCreateFullPath) - { - if (!::CreateDirectory(PrependPathExtensionIfNeeded(pathDirectory).ToString(), nullptr)) - { - DWORD dwLastError = GetLastError(); - if(dwLastError != ERROR_ALREADY_EXISTS) - { - LOG_ERROR(m_spLog) << L"Creating directory " << pathDirectory << L" failed with error " << dwLastError; - throw TFileException(eErr_CannotCreateDirectory, dwLastError, pathDirectory, L"Cannot create directory", LOCATION); - } - - LOG_DEBUG(m_spLog) << L"Directory " << pathDirectory << L" already exists, nothing to do"; - return; - } - } - else - { - TPathContainer vComponents; - pathDirectory.SplitPath(vComponents); - - TSmartPath pathToTest; - for (size_t stIndex = 0; stIndex < vComponents.GetCount(); ++stIndex) - { - const TSmartPath& pathComponent = vComponents.GetAt(stIndex); - pathToTest += pathComponent; - - LOG_DEBUG(m_spLog) << L"Creating " << pathDirectory << L" - partial path: " << pathToTest; - - // try to create subsequent paths - if(!pathToTest.IsDrive() && !pathToTest.IsServerName()) - { - // try to create the specified path - BOOL bRes = ::CreateDirectory(PrependPathExtensionIfNeeded(pathToTest).ToString(), nullptr); - if(!bRes) - { - DWORD dwLastError = GetLastError(); - if(dwLastError != ERROR_ALREADY_EXISTS) - { - LOG_ERROR(m_spLog) << L"Creating directory " << pathToTest << L" failed with error " << dwLastError; - throw TFileException(eErr_CannotCreateDirectory, dwLastError, pathToTest, L"Cannot create directory", LOCATION); - } - } - } - else - LOG_DEBUG(m_spLog) << L"Skipping drive/server part of a path when creating directory " << pathToTest; - } - } - - LOG_DEBUG(m_spLog) << L"Directory " << pathDirectory << L" created successfully"; - } - - void TLocalFilesystem::RemoveDirectory(const TSmartPath& pathDirectory) - { - TSmartPath fullPath = PrependPathExtensionIfNeeded(pathDirectory); - LOG_DEBUG(m_spLog) << L"Removing directory " << fullPath; - - if (!::RemoveDirectory(fullPath.ToString())) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to remove directory " << fullPath << L". Error: " << dwLastError; - throw TFileException(eErr_CannotRemoveDirectory, dwLastError, pathDirectory, L"Cannot delete directory", LOCATION); - } - - LOG_DEBUG(m_spLog) << L"Directory " << fullPath << L" removed successfully"; - } - - void TLocalFilesystem::DeleteFile(const TSmartPath& pathFile) - { - TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFile); - LOG_DEBUG(m_spLog) << L"Removing file " << fullPath; - - if (!::DeleteFile(fullPath.ToString())) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to remove file " << fullPath << L". Error: " << dwLastError; - throw TFileException(eErr_CannotDeleteFile, dwLastError, pathFile, L"Cannot delete file", LOCATION); - } - - LOG_DEBUG(m_spLog) << L"File " << fullPath << L" removed successfully"; - } - - void TLocalFilesystem::GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePathData) - { - if (!spFileInfo) - throw TCoreException(eErr_InvalidArgument, L"spFileInfo", LOCATION); - - LOG_DEBUG(m_spLog) << L"Retrieving file information for " << pathFile << - L" with base path data: " << TSmartPath(spBasePathData ? spBasePathData->GetSrcPath() : TSmartPath()); - - WIN32_FIND_DATA wfd; - - TSmartPath findPath = pathFile; - bool bIsDrive = pathFile.IsDrive() || (pathFile.IsDriveWithRootDir()); - if(bIsDrive) - { - // add '\\' if needed and '*' for marking that we look for e.g. c:\* - // instead of c:\, which would never be found the other way - findPath.AppendIfNotExists(_T("*"), false); - } - - LOG_DEBUG(m_spLog) << L"Retrieving file information for " << pathFile << L". Using search pattern: " << findPath; - - HANDLE hFind = FindFirstFileEx(PrependPathExtensionIfNeeded(findPath).ToString(), FindExInfoStandard, &wfd, FindExSearchNameMatch, nullptr, 0); - if (hFind != INVALID_HANDLE_VALUE) - { - FindClose(hFind); - - if(bIsDrive) - { - TFileTime ftTime; - ftTime.SetCurrentTime(); - - spFileInfo->Init(spBasePathData, pathFile, FILE_ATTRIBUTE_DIRECTORY, 0, ftTime, ftTime, ftTime, 0); - LOG_DEBUG(m_spLog) << L"Retrieved information for drive - using current timestamp file information for " << pathFile; - } - else - { - // new instance of path to accommodate the corrected path (i.e. input path might have lower case names, but we'd like to - // preserve the original case contained in the file system) - TSmartPath pathNew(pathFile); - pathNew.DeleteFileName(); - pathNew += PathFromString(wfd.cFileName); - - unsigned long long ullFullSize = (((unsigned long long)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow; - - // copy data from W32_F_D - spFileInfo->Init(spBasePathData, pathNew, - wfd.dwFileAttributes, ullFullSize, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - - LOG_DEBUG(m_spLog) << L"Retrieved information for file/directory " << pathFile << - L", full-path: " << pathNew << - L", attributes: " << wfd.dwFileAttributes << - L", size: " << ullFullSize << - L", creation-time: " << wfd.ftCreationTime << - L", last-access-time: " << wfd.ftLastAccessTime << - L", last-write-time: " << wfd.ftLastWriteTime; - } - } - else - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to retrieve file information for " << pathFile << L". Error: " << dwLastError; - throw TFileException(eErr_CannotGetFileInfo, dwLastError, pathFile, L"Cannot retrieve file information", LOCATION); - } - } - - void TLocalFilesystem::FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) - { - TSmartPath pathMoveFrom = PrependPathExtensionIfNeeded(pathSource); - TSmartPath pathMoveTo = PrependPathExtensionIfNeeded(pathDestination); - - LOG_DEBUG(m_spLog) << L"Trying to fast-move file " << pathMoveFrom << L" to " << pathMoveTo; - - if (!::MoveFileEx(pathMoveFrom.ToString(), pathMoveTo.ToString(), 0)) - { - DWORD dwLastError = GetLastError(); - - LOG_ERROR(m_spLog) << L"Failed to fast-move file " << pathMoveFrom << L" to " << pathMoveTo << L". Error: " << dwLastError; - throw TFileException(eErr_CannotFastMove, dwLastError, pathSource, L"Cannot fast move file/directory", LOCATION); - } - - LOG_DEBUG(m_spLog) << L"Successfully fast-moved file " << pathMoveFrom << L" to " << pathMoveTo; - } - - IFilesystemFindPtr TLocalFilesystem::CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) - { - LOG_TRACE(m_spLog) << L"Creating file finder object for path " << pathDir << L" with mask " << pathMask; - - return std::shared_ptr(new TLocalFilesystemFind(pathDir, pathMask, m_spLog->GetLogFileData())); - } - - IFilesystemFilePtr TLocalFilesystem::CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) - { - LOG_TRACE(m_spLog) << L"Creating file object for path " << pathFile << L" with no-buffering set to " << bNoBuffering << L" and protect-read-only set to " << bProtectReadOnlyFiles; - return std::shared_ptr(new TLocalFilesystemFile(eMode, pathFile, bNoBuffering, bProtectReadOnlyFiles, m_spLog->GetLogFileData())); - } - - TSmartPath TLocalFilesystem::PrependPathExtensionIfNeeded(const TSmartPath& pathInput) - { - const TSmartPath pathPrefix = PathFromString(L"\\\\?\\"); - - if (pathInput.GetLength() >= 248 && !pathInput.StartsWith(pathPrefix)) - return pathPrefix + pathInput; - - return pathInput; - } - - TLocalFilesystem::EPathsRelation TLocalFilesystem::GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) - { - if (pathFirst.IsEmpty()) - throw TCoreException(eErr_InvalidArgument, L"pathFirst", LOCATION); - if(pathSecond.IsEmpty()) - throw TCoreException(eErr_InvalidArgument, L"pathSecond", LOCATION); - - LOG_DEBUG(m_spLog) << L"Trying to find relation between paths: " << pathFirst << L" and " << pathSecond; - - // get information about both paths - UINT uiFirstDriveType = GetDriveData(pathFirst); - UINT uiSecondDriveType = GetDriveData(pathSecond); - - LOG_TRACE(m_spLog) << L"Drive type for " << pathFirst << L" is " << uiFirstDriveType << L", drive type for " << pathSecond << L" is " << uiSecondDriveType; - - // what kind of relation... - EPathsRelation eRelation = eRelation_Other; - if (uiFirstDriveType == DRIVE_REMOTE || uiSecondDriveType == DRIVE_REMOTE) - eRelation = eRelation_Network; - else if (uiFirstDriveType == DRIVE_CDROM || uiSecondDriveType == DRIVE_CDROM) - eRelation = eRelation_CDRom; - else if (uiFirstDriveType == DRIVE_FIXED && uiSecondDriveType == DRIVE_FIXED) - { - // two hdd's - is this the same physical disk ? - wchar_t wchFirstDrive = pathFirst.GetDriveLetter(); - wchar_t wchSecondDrive = pathSecond.GetDriveLetter(); - - if (wchFirstDrive == L'\0' || wchSecondDrive == L'\0') - throw TCoreException(eErr_FixedDriveWithoutDriveLetter, L"Fixed drive does not have drive letter assigned", LOCATION); - - if (wchFirstDrive == wchSecondDrive) - eRelation = eRelation_SinglePhysicalDisk; - else - { - DWORD dwFirstPhysicalDisk = GetPhysicalDiskNumber(wchFirstDrive); - DWORD dwSecondPhysicalDisk = GetPhysicalDiskNumber(wchSecondDrive); - - LOG_TRACE(m_spLog) << L"Physical disk for " << pathFirst << L" is " << dwFirstPhysicalDisk << L", physical disk for " << pathSecond << L" is " << dwSecondPhysicalDisk; - - if (dwFirstPhysicalDisk == std::numeric_limits::max() || dwSecondPhysicalDisk == std::numeric_limits::max()) - { - // NOTE: disabled throwing an exception here - when testing, it came out that some DRIVE_FIXED - // volumes might have problems handling this detection (TrueCrypt volumes for example). - // So for now we report it as two different physical disks. - //THROW(_T("Problem with physical disk detection"), 0, 0, 0); - eRelation = eRelation_TwoPhysicalDisks; - } - else if (dwFirstPhysicalDisk == dwSecondPhysicalDisk) - eRelation = eRelation_SinglePhysicalDisk; - else - eRelation = eRelation_TwoPhysicalDisks; - } - } - - LOG_DEBUG(m_spLog) << L"Drive relation for " << pathFirst << L" and " << pathSecond << L" is " << eRelation; - - return eRelation; - } - - DWORD TLocalFilesystem::GetPhysicalDiskNumber(wchar_t wchDrive) - { - LOG_TRACE(m_spLog) << L"Checking physical disk number for drive " << wchDrive; - - { - boost::shared_lock lock(m_lockDriveLetterToPhysicalDisk); - - std::map::iterator iterMap = m_mapDriveLetterToPhysicalDisk.find(wchDrive); - if (iterMap != m_mapDriveLetterToPhysicalDisk.end()) - { - LOG_TRACE(m_spLog) << L"Physical disk number for drive " << wchDrive << L" is " << (*iterMap).second << L" (cached)"; - return (*iterMap).second; - } - } - - wchar_t szDrive[] = { L'\\', L'\\', L'.', L'\\', wchDrive, L':', L'\0' }; - - LOG_DEBUG(m_spLog) << L"Creating handle for drive " << szDrive; - - HANDLE hDevice = CreateFile(szDrive, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); - if (hDevice == INVALID_HANDLE_VALUE) - { - DWORD dwLastError = GetLastError(); - LOG_DEBUG(m_spLog) << L"Failed to create handle for drive " << szDrive << L". Error: " << dwLastError; - return std::numeric_limits::max(); - } - - // buffer for data (cannot make member nor static because this function might be called by many threads at once) - // buffer is larger than one extent to allow getting information in multi-extent volumes (raid?) - const int stSize = sizeof(VOLUME_DISK_EXTENTS) + 20 * sizeof(DISK_EXTENT); - boost::shared_array spData(new BYTE[stSize]); - - LOG_DEBUG(m_spLog) << L"Retrieving volume disk extents for drive " << szDrive; - - VOLUME_DISK_EXTENTS* pVolumeDiskExtents = (VOLUME_DISK_EXTENTS*)spData.get(); - DWORD dwBytesReturned = 0; - BOOL bResult = DeviceIoControl(hDevice, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, pVolumeDiskExtents, stSize, &dwBytesReturned, nullptr); - if (!bResult) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to retrieve volume disk extents for drive " << szDrive << L". Error: " << dwLastError; - - CloseHandle(hDevice); - - // NOTE: when ERROR_INVALID_FUNCTION is reported here, it probably means that underlying volume - // cannot support IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS properly (such case includes TrueCrypt volumes) - return std::numeric_limits::max(); - } - - CloseHandle(hDevice); - - if (pVolumeDiskExtents->NumberOfDiskExtents == 0) - { - LOG_DEBUG(m_spLog) << L"No disk extents available for drive " << szDrive; - return std::numeric_limits::max(); - } - - DISK_EXTENT* pDiskExtent = &pVolumeDiskExtents->Extents[0]; - - LOG_DEBUG(m_spLog) << L"Retrieved disk number for drive " << szDrive << L": " << pDiskExtent->DiskNumber; - - boost::unique_lock lock(m_lockDriveLetterToPhysicalDisk); - m_mapDriveLetterToPhysicalDisk.insert(std::make_pair(wchDrive, pDiskExtent->DiskNumber)); - - return pDiskExtent->DiskNumber; - } - - void TLocalFilesystem::GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) - { - LOG_DEBUG(m_spLog) << L"Retrieving free space for path " << path; - - rullFree = 0; - - ULARGE_INTEGER ui64Available, ui64Total; - if (GetDiskFreeSpaceEx(path.ToString(), &ui64Available, &ui64Total, nullptr)) - { - rullFree = ui64Available.QuadPart; - rullTotal = ui64Total.QuadPart; - LOG_DEBUG(m_spLog) << L"Free space for path " << path << L" is " << rullFree; - } - else - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Failed to retrieve free space for path " << path << L". Error: " << dwLastError; - throw TFileException(eErr_CannotGetFreeSpace, dwLastError, path, L"Failed to retrieve free space information", LOCATION); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TLocalFilesystem.cpp +/// @date 2011/03/24 +/// @brief +// ============================================================================ +#include "stdafx.h" +#include "TLocalFilesystem.h" +#include +#include +#include "TAutoHandles.h" +#include "TFileInfo.h" +#include +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TPathContainer.h" +#include "TFileTime.h" +#include "TLocalFilesystemFile.h" +#include +#include "TLocalFilesystemFind.h" +#include "TFileException.h" +#include +#include "StreamingHelpers.h" + +namespace chcore +{ + TLocalFilesystem::TLocalFilesystem(const logger::TLogFileDataPtr& spLogFileData) : + m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem")) + { + } + + TLocalFilesystem::~TLocalFilesystem() + { + } + + UINT TLocalFilesystem::GetDriveData(const TSmartPath& spPath) + { + UINT uiDrvType = DRIVE_UNKNOWN; + if (!spPath.IsNetworkPath()) + { + if (!spPath.IsEmpty()) + { + TSmartPath pathDrive = spPath.GetDrive(); + pathDrive.AppendSeparatorIfDoesNotExist(); + + uiDrvType = GetDriveType(pathDrive.ToString()); + if (uiDrvType == DRIVE_NO_ROOT_DIR) + uiDrvType = DRIVE_UNKNOWN; + } + } + else + uiDrvType = DRIVE_REMOTE; + + return uiDrvType; + } + + bool TLocalFilesystem::PathExist(const TSmartPath& pathToCheck) + { + WIN32_FIND_DATA fd; + + TSmartPath findPath = pathToCheck; + bool bIsDrive = pathToCheck.IsDrive() || (pathToCheck.IsDriveWithRootDir()); + + if(bIsDrive) + { + // add '\\' if needed and '*' for marking that we look for e.g. c:\* + // instead of c:\, which would never be found the other way + findPath.AppendIfNotExists(_T("*"), false); + } + + findPath = PrependPathExtensionIfNeeded(findPath); + + LOG_DEBUG(m_spLog) << L"Checking for path existence: " << pathToCheck << L" (using search pattern: " << findPath << L")"; + + HANDLE hFind = FindFirstFile(findPath.ToString(), &fd); + if (hFind != INVALID_HANDLE_VALUE) + { + ::FindClose(hFind); + LOG_DEBUG(m_spLog) << L"Path: " << pathToCheck << L" exists"; + return true; + } + + LOG_DEBUG(m_spLog) << L"Path: " << pathToCheck << L" does not exist"; + return false; + } + + void TLocalFilesystem::SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) + { + TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFileDir); + + LOG_TRACE(m_spLog) << L"Setting file/directory times for " << fullPath << + L", creation-time: " << ftCreationTime.GetAsFiletime() << + L", last-access-time: " << ftLastAccessTime.GetAsFiletime() << + L", last-write-time: " << ftLastWriteTime.GetAsFiletime(); + + TAutoFileHandle hFile = TAutoFileHandle(CreateFile(fullPath.ToString(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + if (hFile == INVALID_HANDLE_VALUE) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Open file failed with error: " << dwLastError << L". Cannot set file/directory times."; + + throw TFileException(eErr_CannotOpenFile, dwLastError, pathFileDir, L"Cannot open file for setting file/directory times", LOCATION); + } + + if (!SetFileTime(hFile, &ftCreationTime.GetAsFiletime(), &ftLastAccessTime.GetAsFiletime(), &ftLastWriteTime.GetAsFiletime())) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to set file/directory times. Error: " << dwLastError; + throw TFileException(eErr_CannotSetFileTimes, dwLastError, pathFileDir, L"Cannot set file/directory times", LOCATION); + } + LOG_TRACE(m_spLog) << L"File/directory times set successfully"; + } + + void TLocalFilesystem::SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) + { + TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFileDir); + + LOG_TRACE(m_spLog) << L"Setting file/directory attributes for " << fullPath << + L", attributes: " << dwAttributes; + + if (!::SetFileAttributes(fullPath.ToString(), dwAttributes)) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to set file/directory attributes. Error: " << dwLastError; + throw TFileException(eErr_CannotSetFileAttributes, dwLastError, pathFileDir, L"Cannot set file/directory attributes", LOCATION); + } + LOG_TRACE(m_spLog) << L"File/directory attributes set successfully"; + } + + void TLocalFilesystem::CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) + { + LOG_DEBUG(m_spLog) << L"Creating directory " << pathDirectory << + L", create-full-path: " << bCreateFullPath; + + if (!bCreateFullPath) + { + if (!::CreateDirectory(PrependPathExtensionIfNeeded(pathDirectory).ToString(), nullptr)) + { + DWORD dwLastError = GetLastError(); + if(dwLastError != ERROR_ALREADY_EXISTS) + { + LOG_ERROR(m_spLog) << L"Creating directory " << pathDirectory << L" failed with error " << dwLastError; + throw TFileException(eErr_CannotCreateDirectory, dwLastError, pathDirectory, L"Cannot create directory", LOCATION); + } + + LOG_DEBUG(m_spLog) << L"Directory " << pathDirectory << L" already exists, nothing to do"; + return; + } + } + else + { + TPathContainer vComponents; + pathDirectory.SplitPath(vComponents); + + TSmartPath pathToTest; + for (size_t stIndex = 0; stIndex < vComponents.GetCount(); ++stIndex) + { + const TSmartPath& pathComponent = vComponents.GetAt(stIndex); + pathToTest += pathComponent; + + LOG_DEBUG(m_spLog) << L"Creating " << pathDirectory << L" - partial path: " << pathToTest; + + // try to create subsequent paths + if(!pathToTest.IsDrive() && !pathToTest.IsServerName()) + { + // try to create the specified path + BOOL bRes = ::CreateDirectory(PrependPathExtensionIfNeeded(pathToTest).ToString(), nullptr); + if(!bRes) + { + DWORD dwLastError = GetLastError(); + if(dwLastError != ERROR_ALREADY_EXISTS) + { + LOG_ERROR(m_spLog) << L"Creating directory " << pathToTest << L" failed with error " << dwLastError; + throw TFileException(eErr_CannotCreateDirectory, dwLastError, pathToTest, L"Cannot create directory", LOCATION); + } + } + } + else + LOG_DEBUG(m_spLog) << L"Skipping drive/server part of a path when creating directory " << pathToTest; + } + } + + LOG_DEBUG(m_spLog) << L"Directory " << pathDirectory << L" created successfully"; + } + + void TLocalFilesystem::RemoveDirectory(const TSmartPath& pathDirectory) + { + TSmartPath fullPath = PrependPathExtensionIfNeeded(pathDirectory); + LOG_DEBUG(m_spLog) << L"Removing directory " << fullPath; + + if (!::RemoveDirectory(fullPath.ToString())) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to remove directory " << fullPath << L". Error: " << dwLastError; + throw TFileException(eErr_CannotRemoveDirectory, dwLastError, pathDirectory, L"Cannot delete directory", LOCATION); + } + + LOG_DEBUG(m_spLog) << L"Directory " << fullPath << L" removed successfully"; + } + + void TLocalFilesystem::DeleteFile(const TSmartPath& pathFile) + { + TSmartPath fullPath = PrependPathExtensionIfNeeded(pathFile); + LOG_DEBUG(m_spLog) << L"Removing file " << fullPath; + + if (!::DeleteFile(fullPath.ToString())) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to remove file " << fullPath << L". Error: " << dwLastError; + throw TFileException(eErr_CannotDeleteFile, dwLastError, pathFile, L"Cannot delete file", LOCATION); + } + + LOG_DEBUG(m_spLog) << L"File " << fullPath << L" removed successfully"; + } + + void TLocalFilesystem::GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& spFileInfo, const TBasePathDataPtr& spBasePathData) + { + if (!spFileInfo) + throw TCoreException(eErr_InvalidArgument, L"spFileInfo", LOCATION); + + LOG_DEBUG(m_spLog) << L"Retrieving file information for " << pathFile << + L" with base path data: " << TSmartPath(spBasePathData ? spBasePathData->GetSrcPath() : TSmartPath()); + + WIN32_FIND_DATA wfd; + + TSmartPath findPath = pathFile; + bool bIsDrive = pathFile.IsDrive() || (pathFile.IsDriveWithRootDir()); + if(bIsDrive) + { + // add '\\' if needed and '*' for marking that we look for e.g. c:\* + // instead of c:\, which would never be found the other way + findPath.AppendIfNotExists(_T("*"), false); + } + + LOG_DEBUG(m_spLog) << L"Retrieving file information for " << pathFile << L". Using search pattern: " << findPath; + + HANDLE hFind = FindFirstFileEx(PrependPathExtensionIfNeeded(findPath).ToString(), FindExInfoStandard, &wfd, FindExSearchNameMatch, nullptr, 0); + if (hFind != INVALID_HANDLE_VALUE) + { + FindClose(hFind); + + if(bIsDrive) + { + TFileTime ftTime; + ftTime.SetCurrentTime(); + + spFileInfo->Init(spBasePathData, pathFile, FILE_ATTRIBUTE_DIRECTORY, 0, ftTime, ftTime, ftTime, 0); + LOG_DEBUG(m_spLog) << L"Retrieved information for drive - using current timestamp file information for " << pathFile; + } + else + { + // new instance of path to accommodate the corrected path (i.e. input path might have lower case names, but we'd like to + // preserve the original case contained in the file system) + TSmartPath pathNew(pathFile); + pathNew.DeleteFileName(); + pathNew += PathFromString(wfd.cFileName); + + unsigned long long ullFullSize = (((unsigned long long)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow; + + // copy data from W32_F_D + spFileInfo->Init(spBasePathData, pathNew, + wfd.dwFileAttributes, ullFullSize, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + + LOG_DEBUG(m_spLog) << L"Retrieved information for file/directory " << pathFile << + L", full-path: " << pathNew << + L", attributes: " << wfd.dwFileAttributes << + L", size: " << ullFullSize << + L", creation-time: " << wfd.ftCreationTime << + L", last-access-time: " << wfd.ftLastAccessTime << + L", last-write-time: " << wfd.ftLastWriteTime; + } + } + else + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to retrieve file information for " << pathFile << L". Error: " << dwLastError; + throw TFileException(eErr_CannotGetFileInfo, dwLastError, pathFile, L"Cannot retrieve file information", LOCATION); + } + } + + void TLocalFilesystem::FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) + { + TSmartPath pathMoveFrom = PrependPathExtensionIfNeeded(pathSource); + TSmartPath pathMoveTo = PrependPathExtensionIfNeeded(pathDestination); + + LOG_DEBUG(m_spLog) << L"Trying to fast-move file " << pathMoveFrom << L" to " << pathMoveTo; + + if (!::MoveFileEx(pathMoveFrom.ToString(), pathMoveTo.ToString(), 0)) + { + DWORD dwLastError = GetLastError(); + + LOG_ERROR(m_spLog) << L"Failed to fast-move file " << pathMoveFrom << L" to " << pathMoveTo << L". Error: " << dwLastError; + throw TFileException(eErr_CannotFastMove, dwLastError, pathSource, L"Cannot fast move file/directory", LOCATION); + } + + LOG_DEBUG(m_spLog) << L"Successfully fast-moved file " << pathMoveFrom << L" to " << pathMoveTo; + } + + IFilesystemFindPtr TLocalFilesystem::CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) + { + LOG_TRACE(m_spLog) << L"Creating file finder object for path " << pathDir << L" with mask " << pathMask; + + return std::shared_ptr(new TLocalFilesystemFind(pathDir, pathMask, m_spLog->GetLogFileData())); + } + + IFilesystemFilePtr TLocalFilesystem::CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) + { + LOG_TRACE(m_spLog) << L"Creating file object for path " << pathFile << L" with no-buffering set to " << bNoBuffering << L" and protect-read-only set to " << bProtectReadOnlyFiles; + return std::shared_ptr(new TLocalFilesystemFile(eMode, pathFile, bNoBuffering, bProtectReadOnlyFiles, m_spLog->GetLogFileData())); + } + + TSmartPath TLocalFilesystem::PrependPathExtensionIfNeeded(const TSmartPath& pathInput) + { + const TSmartPath pathPrefix = PathFromString(L"\\\\?\\"); + + if (pathInput.GetLength() >= 248 && !pathInput.StartsWith(pathPrefix)) + return pathPrefix + pathInput; + + return pathInput; + } + + TLocalFilesystem::EPathsRelation TLocalFilesystem::GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) + { + if (pathFirst.IsEmpty()) + throw TCoreException(eErr_InvalidArgument, L"pathFirst", LOCATION); + if(pathSecond.IsEmpty()) + throw TCoreException(eErr_InvalidArgument, L"pathSecond", LOCATION); + + LOG_DEBUG(m_spLog) << L"Trying to find relation between paths: " << pathFirst << L" and " << pathSecond; + + // get information about both paths + UINT uiFirstDriveType = GetDriveData(pathFirst); + UINT uiSecondDriveType = GetDriveData(pathSecond); + + LOG_TRACE(m_spLog) << L"Drive type for " << pathFirst << L" is " << uiFirstDriveType << L", drive type for " << pathSecond << L" is " << uiSecondDriveType; + + // what kind of relation... + EPathsRelation eRelation = eRelation_Other; + if (uiFirstDriveType == DRIVE_REMOTE || uiSecondDriveType == DRIVE_REMOTE) + eRelation = eRelation_Network; + else if (uiFirstDriveType == DRIVE_CDROM || uiSecondDriveType == DRIVE_CDROM) + eRelation = eRelation_CDRom; + else if (uiFirstDriveType == DRIVE_FIXED && uiSecondDriveType == DRIVE_FIXED) + { + // two hdd's - is this the same physical disk ? + wchar_t wchFirstDrive = pathFirst.GetDriveLetter(); + wchar_t wchSecondDrive = pathSecond.GetDriveLetter(); + + if (wchFirstDrive == L'\0' || wchSecondDrive == L'\0') + throw TCoreException(eErr_FixedDriveWithoutDriveLetter, L"Fixed drive does not have drive letter assigned", LOCATION); + + if (wchFirstDrive == wchSecondDrive) + eRelation = eRelation_SinglePhysicalDisk; + else + { + DWORD dwFirstPhysicalDisk = GetPhysicalDiskNumber(wchFirstDrive); + DWORD dwSecondPhysicalDisk = GetPhysicalDiskNumber(wchSecondDrive); + + LOG_TRACE(m_spLog) << L"Physical disk for " << pathFirst << L" is " << dwFirstPhysicalDisk << L", physical disk for " << pathSecond << L" is " << dwSecondPhysicalDisk; + + if (dwFirstPhysicalDisk == std::numeric_limits::max() || dwSecondPhysicalDisk == std::numeric_limits::max()) + { + // NOTE: disabled throwing an exception here - when testing, it came out that some DRIVE_FIXED + // volumes might have problems handling this detection (TrueCrypt volumes for example). + // So for now we report it as two different physical disks. + //THROW(_T("Problem with physical disk detection"), 0, 0, 0); + eRelation = eRelation_TwoPhysicalDisks; + } + else if (dwFirstPhysicalDisk == dwSecondPhysicalDisk) + eRelation = eRelation_SinglePhysicalDisk; + else + eRelation = eRelation_TwoPhysicalDisks; + } + } + + LOG_DEBUG(m_spLog) << L"Drive relation for " << pathFirst << L" and " << pathSecond << L" is " << eRelation; + + return eRelation; + } + + DWORD TLocalFilesystem::GetPhysicalDiskNumber(wchar_t wchDrive) + { + LOG_TRACE(m_spLog) << L"Checking physical disk number for drive " << wchDrive; + + { + boost::shared_lock lock(m_lockDriveLetterToPhysicalDisk); + + std::map::iterator iterMap = m_mapDriveLetterToPhysicalDisk.find(wchDrive); + if (iterMap != m_mapDriveLetterToPhysicalDisk.end()) + { + LOG_TRACE(m_spLog) << L"Physical disk number for drive " << wchDrive << L" is " << (*iterMap).second << L" (cached)"; + return (*iterMap).second; + } + } + + wchar_t szDrive[] = { L'\\', L'\\', L'.', L'\\', wchDrive, L':', L'\0' }; + + LOG_DEBUG(m_spLog) << L"Creating handle for drive " << szDrive; + + HANDLE hDevice = CreateFile(szDrive, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); + if (hDevice == INVALID_HANDLE_VALUE) + { + DWORD dwLastError = GetLastError(); + LOG_DEBUG(m_spLog) << L"Failed to create handle for drive " << szDrive << L". Error: " << dwLastError; + return std::numeric_limits::max(); + } + + // buffer for data (cannot make member nor static because this function might be called by many threads at once) + // buffer is larger than one extent to allow getting information in multi-extent volumes (raid?) + const int stSize = sizeof(VOLUME_DISK_EXTENTS) + 20 * sizeof(DISK_EXTENT); + boost::shared_array spData(new BYTE[stSize]); + + LOG_DEBUG(m_spLog) << L"Retrieving volume disk extents for drive " << szDrive; + + VOLUME_DISK_EXTENTS* pVolumeDiskExtents = (VOLUME_DISK_EXTENTS*)spData.get(); + DWORD dwBytesReturned = 0; + BOOL bResult = DeviceIoControl(hDevice, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, pVolumeDiskExtents, stSize, &dwBytesReturned, nullptr); + if (!bResult) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to retrieve volume disk extents for drive " << szDrive << L". Error: " << dwLastError; + + CloseHandle(hDevice); + + // NOTE: when ERROR_INVALID_FUNCTION is reported here, it probably means that underlying volume + // cannot support IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS properly (such case includes TrueCrypt volumes) + return std::numeric_limits::max(); + } + + CloseHandle(hDevice); + + if (pVolumeDiskExtents->NumberOfDiskExtents == 0) + { + LOG_DEBUG(m_spLog) << L"No disk extents available for drive " << szDrive; + return std::numeric_limits::max(); + } + + DISK_EXTENT* pDiskExtent = &pVolumeDiskExtents->Extents[0]; + + LOG_DEBUG(m_spLog) << L"Retrieved disk number for drive " << szDrive << L": " << pDiskExtent->DiskNumber; + + boost::unique_lock lock(m_lockDriveLetterToPhysicalDisk); + m_mapDriveLetterToPhysicalDisk.insert(std::make_pair(wchDrive, pDiskExtent->DiskNumber)); + + return pDiskExtent->DiskNumber; + } + + void TLocalFilesystem::GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) + { + LOG_DEBUG(m_spLog) << L"Retrieving free space for path " << path; + + rullFree = 0; + + ULARGE_INTEGER ui64Available, ui64Total; + if (GetDiskFreeSpaceEx(path.ToString(), &ui64Available, &ui64Total, nullptr)) + { + rullFree = ui64Available.QuadPart; + rullTotal = ui64Total.QuadPart; + LOG_DEBUG(m_spLog) << L"Free space for path " << path << L" is " << rullFree; + } + else + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Failed to retrieve free space for path " << path << L". Error: " << dwLastError; + throw TFileException(eErr_CannotGetFreeSpace, dwLastError, path, L"Failed to retrieve free space information", LOCATION); + } + } +} Index: src/libchcore/TLocalFilesystem.h =================================================================== diff -u -r789d0908abf8db57e27cfeac7045d9962f4b522a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystem.h (.../TLocalFilesystem.h) (revision 789d0908abf8db57e27cfeac7045d9962f4b522a) +++ src/libchcore/TLocalFilesystem.h (.../TLocalFilesystem.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,85 +1,85 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TLocalFilesystem.h -/// @date 2011/03/24 -/// @brief Contains class responsible for accessing local filesystem. -// ============================================================================ -#ifndef __TLOCALFILESYSTEM_H__ -#define __TLOCALFILESYSTEM_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "TBasePathData.h" -#include "TFileInfoFwd.h" -#include "IFilesystem.h" -#include "..\liblogger\TLogger.h" - -namespace chcore -{ - class TAutoFileHandle; - class TLocalFilesystemFind; - class TLocalFilesystemFile; - class TSimpleDataBuffer; - class TFileTime; - class TOverlappedDataBuffer; - - class LIBCHCORE_API TLocalFilesystem : public IFilesystem - { - public: - explicit TLocalFilesystem(const logger::TLogFileDataPtr& spLogFileData); - virtual ~TLocalFilesystem(); - - virtual bool PathExist(const TSmartPath& strPath) override; // check for file or folder existence - - virtual void SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) override; - virtual void SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) override; - - virtual void CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) override; - virtual void RemoveDirectory(const TSmartPath& pathFile) override; - virtual void DeleteFile(const TSmartPath& pathFile) override; - - virtual void GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) override; - virtual void FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) override; - - virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) override; - virtual IFilesystemFilePtr CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) override; - - virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) override; - - virtual void GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) override; - - private: - static TSmartPath PrependPathExtensionIfNeeded(const TSmartPath& pathInput); - static UINT GetDriveData(const TSmartPath& spPath); - DWORD GetPhysicalDiskNumber(wchar_t wchDrive); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::map m_mapDriveLetterToPhysicalDisk; // caches drive letter -> physical disk number - boost::shared_mutex m_lockDriveLetterToPhysicalDisk; - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - - friend class TLocalFilesystemFind; - friend class TLocalFilesystemFile; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TLocalFilesystem.h +/// @date 2011/03/24 +/// @brief Contains class responsible for accessing local filesystem. +// ============================================================================ +#ifndef __TLOCALFILESYSTEM_H__ +#define __TLOCALFILESYSTEM_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "TBasePathData.h" +#include "TFileInfoFwd.h" +#include "IFilesystem.h" +#include "..\liblogger\TLogger.h" + +namespace chcore +{ + class TAutoFileHandle; + class TLocalFilesystemFind; + class TLocalFilesystemFile; + class TSimpleDataBuffer; + class TFileTime; + class TOverlappedDataBuffer; + + class LIBCHCORE_API TLocalFilesystem : public IFilesystem + { + public: + explicit TLocalFilesystem(const logger::TLogFileDataPtr& spLogFileData); + virtual ~TLocalFilesystem(); + + virtual bool PathExist(const TSmartPath& strPath) override; // check for file or folder existence + + virtual void SetFileDirectoryTime(const TSmartPath& pathFileDir, const TFileTime& ftCreationTime, const TFileTime& ftLastAccessTime, const TFileTime& ftLastWriteTime) override; + virtual void SetAttributes(const TSmartPath& pathFileDir, DWORD dwAttributes) override; + + virtual void CreateDirectory(const TSmartPath& pathDirectory, bool bCreateFullPath) override; + virtual void RemoveDirectory(const TSmartPath& pathFile) override; + virtual void DeleteFile(const TSmartPath& pathFile) override; + + virtual void GetFileInfo(const TSmartPath& pathFile, TFileInfoPtr& rFileInfo, const TBasePathDataPtr& spBasePathData = TBasePathDataPtr()) override; + virtual void FastMove(const TSmartPath& pathSource, const TSmartPath& pathDestination) override; + + virtual IFilesystemFindPtr CreateFinderObject(const TSmartPath& pathDir, const TSmartPath& pathMask) override; + virtual IFilesystemFilePtr CreateFileObject(IFilesystemFile::EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles) override; + + virtual EPathsRelation GetPathsRelation(const TSmartPath& pathFirst, const TSmartPath& pathSecond) override; + + virtual void GetDynamicFreeSpace(const TSmartPath& path, unsigned long long& rullFree, unsigned long long& rullTotal) override; + + private: + static TSmartPath PrependPathExtensionIfNeeded(const TSmartPath& pathInput); + static UINT GetDriveData(const TSmartPath& spPath); + DWORD GetPhysicalDiskNumber(wchar_t wchDrive); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::map m_mapDriveLetterToPhysicalDisk; // caches drive letter -> physical disk number + boost::shared_mutex m_lockDriveLetterToPhysicalDisk; + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + + friend class TLocalFilesystemFind; + friend class TLocalFilesystemFile; + }; +} + +#endif Index: src/libchcore/TLocalFilesystemFile.cpp =================================================================== diff -u -ra0de3c317cb73a42ed4efbdf29b3a87243b03df4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystemFile.cpp (.../TLocalFilesystemFile.cpp) (revision a0de3c317cb73a42ed4efbdf29b3a87243b03df4) +++ src/libchcore/TLocalFilesystemFile.cpp (.../TLocalFilesystemFile.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,423 +1,423 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLocalFilesystemFile.h" -#include "TBufferSizes.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include -#include "RoundingFunctions.h" -#include "TLocalFilesystem.h" -#include "TFileException.h" -#include "TFileInfo.h" -#include "StreamingHelpers.h" -#include "TOverlappedMemoryPool.h" -#include "OverlappedCallbacks.h" - -namespace chcore -{ - // compile-time check - ensure the buffer granularity used for transfers are bigger than expected sector size - static_assert(TLocalFilesystemFile::MaxSectorSize <= TBufferSizes::BufferGranularity, "Buffer granularity must be equal to or bigger than the max sector size"); - - TLocalFilesystemFile::TLocalFilesystemFile(EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles, const logger::TLogFileDataPtr& spLogFileData) : - m_pathFile(TLocalFilesystem::PrependPathExtensionIfNeeded(pathFile)), - m_hFile(INVALID_HANDLE_VALUE), - m_eMode(eMode), - m_bProtectReadOnlyFiles(bProtectReadOnlyFiles), - m_bNoBuffering(bNoBuffering), - m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem-File")) - { - if (pathFile.IsEmpty()) - throw TCoreException(eErr_InvalidArgument, L"pathFile", LOCATION); - } - - TLocalFilesystemFile::~TLocalFilesystemFile() - { - try - { - InternalClose(); - } - catch (const std::exception&) - { - } - } - - DWORD TLocalFilesystemFile::GetFlagsAndAttributes(bool bNoBuffering) const - { - return FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN | (bNoBuffering ? FILE_FLAG_NO_BUFFERING : 0); - } - - void TLocalFilesystemFile::EnsureOpen() - { - if(m_hFile != INVALID_HANDLE_VALUE) - return; - - if(m_eMode == eMode_Read) - OpenFileForReading(); - else - OpenFileForWriting(); - } - - void TLocalFilesystemFile::OpenFileForReading() - { - LOG_DEBUG(m_spLog) << L"Opening file for reading" << GetFileInfoForLog(m_bNoBuffering); - - m_hFile = ::CreateFile(m_pathFile.ToString(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, GetFlagsAndAttributes(m_bNoBuffering), nullptr); - if (m_hFile == INVALID_HANDLE_VALUE) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << "Opening file for reading failed with error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - - throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open for reading", LOCATION); - } - - LOG_DEBUG(m_spLog) << "Opening file for reading succeeded. New handle: " << m_hFile << GetFileInfoForLog(m_bNoBuffering); - } - - void TLocalFilesystemFile::OpenFileForWriting() - { - Close(); - - LOG_DEBUG(m_spLog) << L"Opening file for writing" << GetFileInfoForLog(m_bNoBuffering); - - bool bAttributesChanged = false; - - do - { - m_hFile = ::CreateFile(m_pathFile.ToString(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, GetFlagsAndAttributes(m_bNoBuffering), nullptr); - DWORD dwLastError = GetLastError(); - if(m_hFile == INVALID_HANDLE_VALUE) - { - // failed - if(dwLastError == ERROR_ACCESS_DENIED && !m_bProtectReadOnlyFiles && !bAttributesChanged) - { - // handle read-only files - DWORD dwAttributes = GetFileAttributes(m_pathFile.ToString()); - if(dwAttributes == INVALID_FILE_ATTRIBUTES) - { - LOG_ERROR(m_spLog) << "Retrieving file attributes failed while opening file for writing. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot retrieve file attributes.", LOCATION); - } - - if(dwAttributes & FILE_ATTRIBUTE_READONLY) - { - if(!SetFileAttributes(m_pathFile.ToString(), dwAttributes & ~FILE_ATTRIBUTE_READONLY)) - { - LOG_ERROR(m_spLog) << "Error while trying to reset read-only attribute. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot reset read-only attribute.", LOCATION); - } - - bAttributesChanged = true; - continue; - } - } - - // all other errors - LOG_ERROR(m_spLog) << "Encountered an error while opening file for writing. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open file.", LOCATION); - } - - // succeeded - m_bFreshlyCreated = !(dwLastError == ERROR_ALREADY_EXISTS); - break; - } - while(bAttributesChanged); - - LOG_DEBUG(m_spLog) << "Opening file for writing succeeded. New handle: " << m_hFile << GetFileInfoForLog(m_bNoBuffering); - } - - void TLocalFilesystemFile::OpenExistingForWriting(bool bNoBuffering) - { - Close(); - - LOG_DEBUG(m_spLog) << "OpenExistingForWriting" << GetFileInfoForLog(bNoBuffering); - - m_hFile = CreateFile(m_pathFile.ToString(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, GetFlagsAndAttributes(bNoBuffering), nullptr); - if (m_hFile == INVALID_HANDLE_VALUE) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << "OpenExistingForWriting failed with error: " << dwLastError << GetFileInfoForLog(bNoBuffering); - - throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open for writing.", LOCATION); - } - LOG_DEBUG(m_spLog) << "OpenExistingForWriting succeeded. New handle: " << m_hFile << GetFileInfoForLog(bNoBuffering); - } - - file_size_t TLocalFilesystemFile::GetSeekPositionForResume(file_size_t fsLastAvailablePosition) - { - file_size_t fsMove = (m_bNoBuffering ? RoundDown(fsLastAvailablePosition, MaxSectorSize) : fsLastAvailablePosition); - LOG_DEBUG(m_spLog) << "Calculated seek position for last-available-pos: " << fsLastAvailablePosition << L" = " << fsMove << GetFileInfoForLog(m_bNoBuffering); - - return fsMove; - } - - void TLocalFilesystemFile::Truncate(file_size_t fsNewSize) - { - LOG_TRACE(m_spLog) << "Truncating file to: " << fsNewSize << GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - // when no-buffering is used, there are cases where we'd need to switch to buffered ops - // to adjust file size - bool bFileSettingsChanged = false; - if (m_bNoBuffering) - { - file_size_t fsNewAlignedSize = RoundUp(fsNewSize, MaxSectorSize); - if (fsNewAlignedSize != fsNewSize) - { - LOG_TRACE(m_spLog) << "Truncating to non-aligned size. Requested: " << fsNewSize << L", aligned: " << fsNewAlignedSize << L". Will reopen file in buffering mode." << GetFileInfoForLog(m_bNoBuffering); - - Close(); - OpenExistingForWriting(false); - - bFileSettingsChanged = true; - } - } - - LARGE_INTEGER li = { 0, 0 }; - LARGE_INTEGER liNew = { 0, 0 }; - - li.QuadPart = fsNewSize; - - LOG_TRACE(m_spLog) << L"Setting file pointer to: " << li.QuadPart << GetFileInfoForLog(m_bNoBuffering); - if (!SetFilePointerEx(m_hFile, li, &liNew, FILE_BEGIN)) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Setting file pointer to: " << li.QuadPart << L" failed." << GetFileInfoForLog(m_bNoBuffering); - - throw TFileException(eErr_SeekFailed, dwLastError, m_pathFile, L"Cannot seek to appropriate position", LOCATION); - } - - LOG_TRACE(m_spLog) << L"Setting EOF" << GetFileInfoForLog(m_bNoBuffering); - if(!::SetEndOfFile(m_hFile)) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Setting EOF failed" << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotTruncate, dwLastError, m_pathFile, L"Cannot mark the end of file", LOCATION); - } - - // close the file that was open in inappropriate mode - if(bFileSettingsChanged) - { - LOG_DEBUG(m_spLog) << L"Closing file due to mode change in truncate function" << GetFileInfoForLog(m_bNoBuffering); - - Close(); - } - } - - void TLocalFilesystemFile::ReadFile(TOverlappedDataBuffer& rBuffer) - { - LOG_TRACE(m_spLog) << L"Requesting read of " << rBuffer.GetRequestedDataSize() << - L" bytes at position " << rBuffer.GetFilePosition() << - L"; buffer-order: " << rBuffer.GetFilePosition() << - GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - if (!::ReadFileEx(m_hFile, rBuffer.GetBufferPtr(), rBuffer.GetRequestedDataSize(), &rBuffer, OverlappedReadCompleted)) - { - DWORD dwLastError = GetLastError(); - switch (dwLastError) - { - case ERROR_IO_PENDING: - LOG_TRACE(m_spLog) << L"Read requested and is pending" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - return; - - case ERROR_HANDLE_EOF: - { - LOG_TRACE(m_spLog) << L"Read request marked as EOF" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - - rBuffer.SetBytesTransferred(0); - rBuffer.SetStatusCode(0); - rBuffer.SetErrorCode(ERROR_SUCCESS); - rBuffer.SetLastPart(true); - - OverlappedReadCompleted(rBuffer.GetErrorCode(), 0, &rBuffer); - - break; - } - - default: - { - LOG_ERROR(m_spLog) << L"Read request failed with error " << dwLastError << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - - throw TFileException(eErr_CannotReadFile, dwLastError, m_pathFile, L"Error reading data from file", LOCATION); - } - } - } - else - LOG_TRACE(m_spLog) << L"Read request succeeded" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - } - - void TLocalFilesystemFile::WriteFile(TOverlappedDataBuffer& rBuffer) - { - LOG_TRACE(m_spLog) << L"Requesting writing of " << rBuffer.GetRealDataSize() << - L" bytes at position " << rBuffer.GetFilePosition() << - L"; buffer-order: " << rBuffer.GetFilePosition() << - GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - DWORD dwToWrite = boost::numeric_cast(rBuffer.GetRealDataSize()); - - if (m_bNoBuffering && rBuffer.IsLastPart()) - { - dwToWrite = RoundUp(dwToWrite, MaxSectorSize); - LOG_TRACE(m_spLog) << L"Writing last part of file in no-buffering mode. Rounding up last write to " << dwToWrite << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - } - - if (!::WriteFileEx(m_hFile, rBuffer.GetBufferPtr(), dwToWrite, &rBuffer, OverlappedWriteCompleted)) - { - DWORD dwLastError = GetLastError(); - if (dwLastError != ERROR_IO_PENDING) - { - LOG_ERROR(m_spLog) << L"Write request failed with error " << dwLastError << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotWriteFile, dwLastError, m_pathFile, L"Error while writing to file", LOCATION); - } - - LOG_TRACE(m_spLog) << L"Write requested and is pending" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - } - else - LOG_TRACE(m_spLog) << L"Write request succeeded" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); - } - - void TLocalFilesystemFile::FinalizeFile(TOverlappedDataBuffer& rBuffer) - { - LOG_TRACE(m_spLog) << L"Finalizing file" << - L"; buffer-order: " << rBuffer.GetFilePosition() << - GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - if (m_bNoBuffering && rBuffer.IsLastPart()) - { - DWORD dwToWrite = boost::numeric_cast(rBuffer.GetRealDataSize()); - DWORD dwReallyWritten = RoundUp(dwToWrite, MaxSectorSize); - - if (dwToWrite != dwReallyWritten) - { - file_size_t fsNewFileSize = rBuffer.GetFilePosition() + dwToWrite; // new size - - LOG_TRACE(m_spLog) << L"File need truncating - really written " << dwReallyWritten << - L", should write " << dwToWrite << - L". Truncating file to " << fsNewFileSize << - L"; buffer-order: " << rBuffer.GetFilePosition() << - GetFileInfoForLog(m_bNoBuffering); - - Truncate(fsNewFileSize); - } - } - } - - bool TLocalFilesystemFile::IsOpen() const - { - return m_hFile != INVALID_HANDLE_VALUE; - } - - bool TLocalFilesystemFile::IsFreshlyCreated() - { - EnsureOpen(); - return m_bFreshlyCreated; - } - - void TLocalFilesystemFile::InternalClose() - { - if (m_hFile != INVALID_HANDLE_VALUE) - { - LOG_DEBUG(m_spLog) << L"Closing file" << GetFileInfoForLog(m_bNoBuffering); - ::CloseHandle(m_hFile); - } - m_hFile = INVALID_HANDLE_VALUE; - } - - std::wstring TLocalFilesystemFile::GetFileInfoForLog(bool bNoBuffering) const - { - std::wstringstream wss; - wss << L" (handle: " << m_hFile << ", path : " << m_pathFile << L", no-buffering : " << bNoBuffering << L")"; - return wss.str(); - } - - void TLocalFilesystemFile::Close() - { - InternalClose(); - } - - file_size_t TLocalFilesystemFile::GetFileSize() - { - LOG_DEBUG(m_spLog) << L"Retrieving file size" << GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - BY_HANDLE_FILE_INFORMATION bhfi; - - if (!::GetFileInformationByHandle(m_hFile, &bhfi)) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Retrieving file size failed with error " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - - return 0; - } - - ULARGE_INTEGER uli; - uli.HighPart = bhfi.nFileSizeHigh; - uli.LowPart = bhfi.nFileSizeLow; - - LOG_DEBUG(m_spLog) << L"File size retrieved -> " << uli.QuadPart << GetFileInfoForLog(m_bNoBuffering); - - return uli.QuadPart; - } - - void TLocalFilesystemFile::GetFileInfo(TFileInfo& tFileInfo) - { - LOG_DEBUG(m_spLog) << L"Retrieving file information" << GetFileInfoForLog(m_bNoBuffering); - - EnsureOpen(); - - BY_HANDLE_FILE_INFORMATION bhfi; - - if (!::GetFileInformationByHandle(m_hFile, &bhfi)) - { - DWORD dwLastError = GetLastError(); - LOG_ERROR(m_spLog) << L"Retrieving file information failed with error " << dwLastError << GetFileInfoForLog(m_bNoBuffering); - throw TFileException(eErr_CannotGetFileInfo, dwLastError, m_pathFile, L"Retrieving file info from handle failed.", LOCATION); - } - - ULARGE_INTEGER uli; - uli.HighPart = bhfi.nFileSizeHigh; - uli.LowPart = bhfi.nFileSizeLow; - - tFileInfo.SetFilePath(m_pathFile); - tFileInfo.SetAttributes(bhfi.dwFileAttributes); - tFileInfo.SetFileTimes(TFileTime(bhfi.ftCreationTime), TFileTime(bhfi.ftLastAccessTime), TFileTime(bhfi.ftLastWriteTime)); - tFileInfo.SetLength64(uli.QuadPart); - - LOG_DEBUG(m_spLog) << L"Retrieving file information succeeded. Attributes: " << - bhfi.dwFileAttributes << - L", creation-time: " << bhfi.ftCreationTime << - L", last-access-time: " << bhfi.ftLastAccessTime<< - L", last-write-time: " << bhfi.ftLastWriteTime << - L", size: " << uli.QuadPart << - GetFileInfoForLog(m_bNoBuffering); - } - - TSmartPath TLocalFilesystemFile::GetFilePath() const - { - return m_pathFile; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLocalFilesystemFile.h" +#include "TBufferSizes.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include +#include "RoundingFunctions.h" +#include "TLocalFilesystem.h" +#include "TFileException.h" +#include "TFileInfo.h" +#include "StreamingHelpers.h" +#include "TOverlappedMemoryPool.h" +#include "OverlappedCallbacks.h" + +namespace chcore +{ + // compile-time check - ensure the buffer granularity used for transfers are bigger than expected sector size + static_assert(TLocalFilesystemFile::MaxSectorSize <= TBufferSizes::BufferGranularity, "Buffer granularity must be equal to or bigger than the max sector size"); + + TLocalFilesystemFile::TLocalFilesystemFile(EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles, const logger::TLogFileDataPtr& spLogFileData) : + m_pathFile(TLocalFilesystem::PrependPathExtensionIfNeeded(pathFile)), + m_hFile(INVALID_HANDLE_VALUE), + m_eMode(eMode), + m_bProtectReadOnlyFiles(bProtectReadOnlyFiles), + m_bNoBuffering(bNoBuffering), + m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem-File")) + { + if (pathFile.IsEmpty()) + throw TCoreException(eErr_InvalidArgument, L"pathFile", LOCATION); + } + + TLocalFilesystemFile::~TLocalFilesystemFile() + { + try + { + InternalClose(); + } + catch (const std::exception&) + { + } + } + + DWORD TLocalFilesystemFile::GetFlagsAndAttributes(bool bNoBuffering) const + { + return FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN | (bNoBuffering ? FILE_FLAG_NO_BUFFERING : 0); + } + + void TLocalFilesystemFile::EnsureOpen() + { + if(m_hFile != INVALID_HANDLE_VALUE) + return; + + if(m_eMode == eMode_Read) + OpenFileForReading(); + else + OpenFileForWriting(); + } + + void TLocalFilesystemFile::OpenFileForReading() + { + LOG_DEBUG(m_spLog) << L"Opening file for reading" << GetFileInfoForLog(m_bNoBuffering); + + m_hFile = ::CreateFile(m_pathFile.ToString(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, GetFlagsAndAttributes(m_bNoBuffering), nullptr); + if (m_hFile == INVALID_HANDLE_VALUE) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << "Opening file for reading failed with error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + + throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open for reading", LOCATION); + } + + LOG_DEBUG(m_spLog) << "Opening file for reading succeeded. New handle: " << m_hFile << GetFileInfoForLog(m_bNoBuffering); + } + + void TLocalFilesystemFile::OpenFileForWriting() + { + Close(); + + LOG_DEBUG(m_spLog) << L"Opening file for writing" << GetFileInfoForLog(m_bNoBuffering); + + bool bAttributesChanged = false; + + do + { + m_hFile = ::CreateFile(m_pathFile.ToString(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, GetFlagsAndAttributes(m_bNoBuffering), nullptr); + DWORD dwLastError = GetLastError(); + if(m_hFile == INVALID_HANDLE_VALUE) + { + // failed + if(dwLastError == ERROR_ACCESS_DENIED && !m_bProtectReadOnlyFiles && !bAttributesChanged) + { + // handle read-only files + DWORD dwAttributes = GetFileAttributes(m_pathFile.ToString()); + if(dwAttributes == INVALID_FILE_ATTRIBUTES) + { + LOG_ERROR(m_spLog) << "Retrieving file attributes failed while opening file for writing. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot retrieve file attributes.", LOCATION); + } + + if(dwAttributes & FILE_ATTRIBUTE_READONLY) + { + if(!SetFileAttributes(m_pathFile.ToString(), dwAttributes & ~FILE_ATTRIBUTE_READONLY)) + { + LOG_ERROR(m_spLog) << "Error while trying to reset read-only attribute. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot reset read-only attribute.", LOCATION); + } + + bAttributesChanged = true; + continue; + } + } + + // all other errors + LOG_ERROR(m_spLog) << "Encountered an error while opening file for writing. Error: " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open file.", LOCATION); + } + + // succeeded + m_bFreshlyCreated = !(dwLastError == ERROR_ALREADY_EXISTS); + break; + } + while(bAttributesChanged); + + LOG_DEBUG(m_spLog) << "Opening file for writing succeeded. New handle: " << m_hFile << GetFileInfoForLog(m_bNoBuffering); + } + + void TLocalFilesystemFile::OpenExistingForWriting(bool bNoBuffering) + { + Close(); + + LOG_DEBUG(m_spLog) << "OpenExistingForWriting" << GetFileInfoForLog(bNoBuffering); + + m_hFile = CreateFile(m_pathFile.ToString(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, GetFlagsAndAttributes(bNoBuffering), nullptr); + if (m_hFile == INVALID_HANDLE_VALUE) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << "OpenExistingForWriting failed with error: " << dwLastError << GetFileInfoForLog(bNoBuffering); + + throw TFileException(eErr_CannotOpenFile, dwLastError, m_pathFile, L"Cannot open for writing.", LOCATION); + } + LOG_DEBUG(m_spLog) << "OpenExistingForWriting succeeded. New handle: " << m_hFile << GetFileInfoForLog(bNoBuffering); + } + + file_size_t TLocalFilesystemFile::GetSeekPositionForResume(file_size_t fsLastAvailablePosition) + { + file_size_t fsMove = (m_bNoBuffering ? RoundDown(fsLastAvailablePosition, MaxSectorSize) : fsLastAvailablePosition); + LOG_DEBUG(m_spLog) << "Calculated seek position for last-available-pos: " << fsLastAvailablePosition << L" = " << fsMove << GetFileInfoForLog(m_bNoBuffering); + + return fsMove; + } + + void TLocalFilesystemFile::Truncate(file_size_t fsNewSize) + { + LOG_TRACE(m_spLog) << "Truncating file to: " << fsNewSize << GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + // when no-buffering is used, there are cases where we'd need to switch to buffered ops + // to adjust file size + bool bFileSettingsChanged = false; + if (m_bNoBuffering) + { + file_size_t fsNewAlignedSize = RoundUp(fsNewSize, MaxSectorSize); + if (fsNewAlignedSize != fsNewSize) + { + LOG_TRACE(m_spLog) << "Truncating to non-aligned size. Requested: " << fsNewSize << L", aligned: " << fsNewAlignedSize << L". Will reopen file in buffering mode." << GetFileInfoForLog(m_bNoBuffering); + + Close(); + OpenExistingForWriting(false); + + bFileSettingsChanged = true; + } + } + + LARGE_INTEGER li = { 0, 0 }; + LARGE_INTEGER liNew = { 0, 0 }; + + li.QuadPart = fsNewSize; + + LOG_TRACE(m_spLog) << L"Setting file pointer to: " << li.QuadPart << GetFileInfoForLog(m_bNoBuffering); + if (!SetFilePointerEx(m_hFile, li, &liNew, FILE_BEGIN)) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Setting file pointer to: " << li.QuadPart << L" failed." << GetFileInfoForLog(m_bNoBuffering); + + throw TFileException(eErr_SeekFailed, dwLastError, m_pathFile, L"Cannot seek to appropriate position", LOCATION); + } + + LOG_TRACE(m_spLog) << L"Setting EOF" << GetFileInfoForLog(m_bNoBuffering); + if(!::SetEndOfFile(m_hFile)) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Setting EOF failed" << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotTruncate, dwLastError, m_pathFile, L"Cannot mark the end of file", LOCATION); + } + + // close the file that was open in inappropriate mode + if(bFileSettingsChanged) + { + LOG_DEBUG(m_spLog) << L"Closing file due to mode change in truncate function" << GetFileInfoForLog(m_bNoBuffering); + + Close(); + } + } + + void TLocalFilesystemFile::ReadFile(TOverlappedDataBuffer& rBuffer) + { + LOG_TRACE(m_spLog) << L"Requesting read of " << rBuffer.GetRequestedDataSize() << + L" bytes at position " << rBuffer.GetFilePosition() << + L"; buffer-order: " << rBuffer.GetFilePosition() << + GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + if (!::ReadFileEx(m_hFile, rBuffer.GetBufferPtr(), rBuffer.GetRequestedDataSize(), &rBuffer, OverlappedReadCompleted)) + { + DWORD dwLastError = GetLastError(); + switch (dwLastError) + { + case ERROR_IO_PENDING: + LOG_TRACE(m_spLog) << L"Read requested and is pending" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + return; + + case ERROR_HANDLE_EOF: + { + LOG_TRACE(m_spLog) << L"Read request marked as EOF" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + + rBuffer.SetBytesTransferred(0); + rBuffer.SetStatusCode(0); + rBuffer.SetErrorCode(ERROR_SUCCESS); + rBuffer.SetLastPart(true); + + OverlappedReadCompleted(rBuffer.GetErrorCode(), 0, &rBuffer); + + break; + } + + default: + { + LOG_ERROR(m_spLog) << L"Read request failed with error " << dwLastError << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + + throw TFileException(eErr_CannotReadFile, dwLastError, m_pathFile, L"Error reading data from file", LOCATION); + } + } + } + else + LOG_TRACE(m_spLog) << L"Read request succeeded" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + } + + void TLocalFilesystemFile::WriteFile(TOverlappedDataBuffer& rBuffer) + { + LOG_TRACE(m_spLog) << L"Requesting writing of " << rBuffer.GetRealDataSize() << + L" bytes at position " << rBuffer.GetFilePosition() << + L"; buffer-order: " << rBuffer.GetFilePosition() << + GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + DWORD dwToWrite = boost::numeric_cast(rBuffer.GetRealDataSize()); + + if (m_bNoBuffering && rBuffer.IsLastPart()) + { + dwToWrite = RoundUp(dwToWrite, MaxSectorSize); + LOG_TRACE(m_spLog) << L"Writing last part of file in no-buffering mode. Rounding up last write to " << dwToWrite << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + } + + if (!::WriteFileEx(m_hFile, rBuffer.GetBufferPtr(), dwToWrite, &rBuffer, OverlappedWriteCompleted)) + { + DWORD dwLastError = GetLastError(); + if (dwLastError != ERROR_IO_PENDING) + { + LOG_ERROR(m_spLog) << L"Write request failed with error " << dwLastError << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotWriteFile, dwLastError, m_pathFile, L"Error while writing to file", LOCATION); + } + + LOG_TRACE(m_spLog) << L"Write requested and is pending" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + } + else + LOG_TRACE(m_spLog) << L"Write request succeeded" << L"; buffer-order: " << rBuffer.GetFilePosition() << GetFileInfoForLog(m_bNoBuffering); + } + + void TLocalFilesystemFile::FinalizeFile(TOverlappedDataBuffer& rBuffer) + { + LOG_TRACE(m_spLog) << L"Finalizing file" << + L"; buffer-order: " << rBuffer.GetFilePosition() << + GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + if (m_bNoBuffering && rBuffer.IsLastPart()) + { + DWORD dwToWrite = boost::numeric_cast(rBuffer.GetRealDataSize()); + DWORD dwReallyWritten = RoundUp(dwToWrite, MaxSectorSize); + + if (dwToWrite != dwReallyWritten) + { + file_size_t fsNewFileSize = rBuffer.GetFilePosition() + dwToWrite; // new size + + LOG_TRACE(m_spLog) << L"File need truncating - really written " << dwReallyWritten << + L", should write " << dwToWrite << + L". Truncating file to " << fsNewFileSize << + L"; buffer-order: " << rBuffer.GetFilePosition() << + GetFileInfoForLog(m_bNoBuffering); + + Truncate(fsNewFileSize); + } + } + } + + bool TLocalFilesystemFile::IsOpen() const + { + return m_hFile != INVALID_HANDLE_VALUE; + } + + bool TLocalFilesystemFile::IsFreshlyCreated() + { + EnsureOpen(); + return m_bFreshlyCreated; + } + + void TLocalFilesystemFile::InternalClose() + { + if (m_hFile != INVALID_HANDLE_VALUE) + { + LOG_DEBUG(m_spLog) << L"Closing file" << GetFileInfoForLog(m_bNoBuffering); + ::CloseHandle(m_hFile); + } + m_hFile = INVALID_HANDLE_VALUE; + } + + std::wstring TLocalFilesystemFile::GetFileInfoForLog(bool bNoBuffering) const + { + std::wstringstream wss; + wss << L" (handle: " << m_hFile << ", path : " << m_pathFile << L", no-buffering : " << bNoBuffering << L")"; + return wss.str(); + } + + void TLocalFilesystemFile::Close() + { + InternalClose(); + } + + file_size_t TLocalFilesystemFile::GetFileSize() + { + LOG_DEBUG(m_spLog) << L"Retrieving file size" << GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + BY_HANDLE_FILE_INFORMATION bhfi; + + if (!::GetFileInformationByHandle(m_hFile, &bhfi)) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Retrieving file size failed with error " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + + return 0; + } + + ULARGE_INTEGER uli; + uli.HighPart = bhfi.nFileSizeHigh; + uli.LowPart = bhfi.nFileSizeLow; + + LOG_DEBUG(m_spLog) << L"File size retrieved -> " << uli.QuadPart << GetFileInfoForLog(m_bNoBuffering); + + return uli.QuadPart; + } + + void TLocalFilesystemFile::GetFileInfo(TFileInfo& tFileInfo) + { + LOG_DEBUG(m_spLog) << L"Retrieving file information" << GetFileInfoForLog(m_bNoBuffering); + + EnsureOpen(); + + BY_HANDLE_FILE_INFORMATION bhfi; + + if (!::GetFileInformationByHandle(m_hFile, &bhfi)) + { + DWORD dwLastError = GetLastError(); + LOG_ERROR(m_spLog) << L"Retrieving file information failed with error " << dwLastError << GetFileInfoForLog(m_bNoBuffering); + throw TFileException(eErr_CannotGetFileInfo, dwLastError, m_pathFile, L"Retrieving file info from handle failed.", LOCATION); + } + + ULARGE_INTEGER uli; + uli.HighPart = bhfi.nFileSizeHigh; + uli.LowPart = bhfi.nFileSizeLow; + + tFileInfo.SetFilePath(m_pathFile); + tFileInfo.SetAttributes(bhfi.dwFileAttributes); + tFileInfo.SetFileTimes(TFileTime(bhfi.ftCreationTime), TFileTime(bhfi.ftLastAccessTime), TFileTime(bhfi.ftLastWriteTime)); + tFileInfo.SetLength64(uli.QuadPart); + + LOG_DEBUG(m_spLog) << L"Retrieving file information succeeded. Attributes: " << + bhfi.dwFileAttributes << + L", creation-time: " << bhfi.ftCreationTime << + L", last-access-time: " << bhfi.ftLastAccessTime<< + L", last-write-time: " << bhfi.ftLastWriteTime << + L", size: " << uli.QuadPart << + GetFileInfoForLog(m_bNoBuffering); + } + + TSmartPath TLocalFilesystemFile::GetFilePath() const + { + return m_pathFile; + } +} Index: src/libchcore/TLocalFilesystemFile.h =================================================================== diff -u -r789d0908abf8db57e27cfeac7045d9962f4b522a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystemFile.h (.../TLocalFilesystemFile.h) (revision 789d0908abf8db57e27cfeac7045d9962f4b522a) +++ src/libchcore/TLocalFilesystemFile.h (.../TLocalFilesystemFile.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,88 +1,88 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOCALFILESYSTEMFILE_H__ -#define __TLOCALFILESYSTEMFILE_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "TOverlappedDataBuffer.h" -#include "IFilesystemFile.h" -#include "..\liblogger\TLogger.h" - -namespace chcore -{ - class TFileInfo; - - class LIBCHCORE_API TLocalFilesystemFile : public IFilesystemFile - { - public: - virtual ~TLocalFilesystemFile(); - - virtual void Truncate(file_size_t fsNewSize) override; - - virtual void ReadFile(TOverlappedDataBuffer& rBuffer) override; - virtual void WriteFile(TOverlappedDataBuffer& rBuffer) override; - virtual void FinalizeFile(TOverlappedDataBuffer& rBuffer) override; - - virtual bool IsOpen() const override; - virtual bool IsFreshlyCreated() override; - - virtual file_size_t GetFileSize() override; - virtual void GetFileInfo(TFileInfo& tFileInfo) override; - - virtual TSmartPath GetFilePath() const override; - - virtual void Close() override; - virtual file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition) override; - - private: - TLocalFilesystemFile(EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles, const logger::TLogFileDataPtr& spLogFileData); - - void EnsureOpen(); - - void OpenFileForReading(); - void OpenFileForWriting(); - - void OpenExistingForWriting(bool bNoBuffering); - - DWORD GetFlagsAndAttributes(bool bNoBuffering) const; - - void InternalClose(); - - std::wstring TLocalFilesystemFile::GetFileInfoForLog(bool bNoBuffering) const; - - private: - TSmartPath m_pathFile; - HANDLE m_hFile = INVALID_HANDLE_VALUE; - EOpenMode m_eMode = eMode_Read; - bool m_bProtectReadOnlyFiles = false; - bool m_bNoBuffering = false; - - bool m_bFreshlyCreated = false; - -#pragma warning(push) -#pragma warning(disable: 4251) - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - - friend class TLocalFilesystem; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOCALFILESYSTEMFILE_H__ +#define __TLOCALFILESYSTEMFILE_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "TOverlappedDataBuffer.h" +#include "IFilesystemFile.h" +#include "..\liblogger\TLogger.h" + +namespace chcore +{ + class TFileInfo; + + class LIBCHCORE_API TLocalFilesystemFile : public IFilesystemFile + { + public: + virtual ~TLocalFilesystemFile(); + + virtual void Truncate(file_size_t fsNewSize) override; + + virtual void ReadFile(TOverlappedDataBuffer& rBuffer) override; + virtual void WriteFile(TOverlappedDataBuffer& rBuffer) override; + virtual void FinalizeFile(TOverlappedDataBuffer& rBuffer) override; + + virtual bool IsOpen() const override; + virtual bool IsFreshlyCreated() override; + + virtual file_size_t GetFileSize() override; + virtual void GetFileInfo(TFileInfo& tFileInfo) override; + + virtual TSmartPath GetFilePath() const override; + + virtual void Close() override; + virtual file_size_t GetSeekPositionForResume(file_size_t fsLastAvailablePosition) override; + + private: + TLocalFilesystemFile(EOpenMode eMode, const TSmartPath& pathFile, bool bNoBuffering, bool bProtectReadOnlyFiles, const logger::TLogFileDataPtr& spLogFileData); + + void EnsureOpen(); + + void OpenFileForReading(); + void OpenFileForWriting(); + + void OpenExistingForWriting(bool bNoBuffering); + + DWORD GetFlagsAndAttributes(bool bNoBuffering) const; + + void InternalClose(); + + std::wstring TLocalFilesystemFile::GetFileInfoForLog(bool bNoBuffering) const; + + private: + TSmartPath m_pathFile; + HANDLE m_hFile = INVALID_HANDLE_VALUE; + EOpenMode m_eMode = eMode_Read; + bool m_bProtectReadOnlyFiles = false; + bool m_bNoBuffering = false; + + bool m_bFreshlyCreated = false; + +#pragma warning(push) +#pragma warning(disable: 4251) + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + + friend class TLocalFilesystem; + }; +} + +#endif Index: src/libchcore/TLocalFilesystemFind.cpp =================================================================== diff -u -rf8fcbbd1d2321cf0c8be79526c449384af654e49 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystemFind.cpp (.../TLocalFilesystemFind.cpp) (revision f8fcbbd1d2321cf0c8be79526c449384af654e49) +++ src/libchcore/TLocalFilesystemFind.cpp (.../TLocalFilesystemFind.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,124 +1,124 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLocalFilesystemFind.h" -#include "TLocalFilesystem.h" -#include "TFileInfo.h" -#include "StreamingHelpers.h" - -namespace chcore -{ - TLocalFilesystemFind::TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask, const logger::TLogFileDataPtr& spLogFileData) : - m_pathDir(pathDir), - m_pathMask(pathMask), - m_hFind(INVALID_HANDLE_VALUE), - m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem-Find")) - { - } - - TLocalFilesystemFind::~TLocalFilesystemFind() - { - InternalClose(); - } - - bool TLocalFilesystemFind::FindNext(TFileInfoPtr& rspFileInfo) - { - WIN32_FIND_DATA wfd; - - TSmartPath pathCurrent = TLocalFilesystem::PrependPathExtensionIfNeeded(m_pathDir + m_pathMask); - // Iterate through dirs & files - bool bContinue = true; - if (m_hFind != INVALID_HANDLE_VALUE) - { - LOG_TRACE(m_spLog) << "Find next" << GetFindLogData(); - bContinue = (FindNextFile(m_hFind, &wfd) != FALSE); - } - else - { - LOG_TRACE(m_spLog) << "Find first" << GetFindLogData(); - - m_hFind = FindFirstFileEx(pathCurrent.ToString(), FindExInfoStandard, &wfd, FindExSearchNameMatch, nullptr, 0); - bContinue = (m_hFind != INVALID_HANDLE_VALUE); - } - if (bContinue) - { - do - { - unsigned long long ullObjectSize = (((unsigned long long)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow; - - if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - LOG_TRACE(m_spLog) << "Found directory: " << wfd.cFileName << - L", attrs: " << wfd.dwFileAttributes << - L", size: " << ullObjectSize << - L", created: " << wfd.ftCreationTime << - L", last-access: " << wfd.ftLastAccessTime << - L", last-write: " << wfd.ftLastWriteTime << - GetFindLogData(); - - rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), wfd.dwFileAttributes, ullObjectSize, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - return true; - } - else if (wfd.cFileName[0] != _T('.') || (wfd.cFileName[1] != _T('\0') && (wfd.cFileName[1] != _T('.') || wfd.cFileName[2] != _T('\0')))) - { - LOG_TRACE(m_spLog) << "Found file: " << wfd.cFileName << - L", attrs: " << wfd.dwFileAttributes << - L", size: " << ullObjectSize << - L", created: " << wfd.ftCreationTime << - L", last-access: " << wfd.ftLastAccessTime << - L", last-write: " << wfd.ftLastWriteTime << - GetFindLogData(); - - // Add directory itself - rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), - wfd.dwFileAttributes, ullObjectSize, wfd.ftCreationTime, - wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); - return true; - } - } while (m_hFind != INVALID_HANDLE_VALUE && ::FindNextFile(m_hFind, &wfd)); // checking m_hFind in case other thread changed it (it shouldn't happen though) - - Close(); - } - - return false; - } - - void TLocalFilesystemFind::InternalClose() - { - if(m_hFind != INVALID_HANDLE_VALUE) - { - LOG_TRACE(m_spLog) << "Closing finder" << GetFindLogData(); - FindClose(m_hFind); - } - m_hFind = INVALID_HANDLE_VALUE; - } - - std::wstring TLocalFilesystemFind::GetFindLogData() const - { - std::wstringstream wss; - wss << L" (directory: " << m_pathDir << L", mask: " << m_pathMask << L", handle: " << m_hFind << L")"; - return wss.str(); - } - - void TLocalFilesystemFind::Close() - { - InternalClose(); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLocalFilesystemFind.h" +#include "TLocalFilesystem.h" +#include "TFileInfo.h" +#include "StreamingHelpers.h" + +namespace chcore +{ + TLocalFilesystemFind::TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask, const logger::TLogFileDataPtr& spLogFileData) : + m_pathDir(pathDir), + m_pathMask(pathMask), + m_hFind(INVALID_HANDLE_VALUE), + m_spLog(logger::MakeLogger(spLogFileData, L"Filesystem-Find")) + { + } + + TLocalFilesystemFind::~TLocalFilesystemFind() + { + InternalClose(); + } + + bool TLocalFilesystemFind::FindNext(TFileInfoPtr& rspFileInfo) + { + WIN32_FIND_DATA wfd; + + TSmartPath pathCurrent = TLocalFilesystem::PrependPathExtensionIfNeeded(m_pathDir + m_pathMask); + // Iterate through dirs & files + bool bContinue = true; + if (m_hFind != INVALID_HANDLE_VALUE) + { + LOG_TRACE(m_spLog) << "Find next" << GetFindLogData(); + bContinue = (FindNextFile(m_hFind, &wfd) != FALSE); + } + else + { + LOG_TRACE(m_spLog) << "Find first" << GetFindLogData(); + + m_hFind = FindFirstFileEx(pathCurrent.ToString(), FindExInfoStandard, &wfd, FindExSearchNameMatch, nullptr, 0); + bContinue = (m_hFind != INVALID_HANDLE_VALUE); + } + if (bContinue) + { + do + { + unsigned long long ullObjectSize = (((unsigned long long)wfd.nFileSizeHigh) << 32) + wfd.nFileSizeLow; + + if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { + LOG_TRACE(m_spLog) << "Found directory: " << wfd.cFileName << + L", attrs: " << wfd.dwFileAttributes << + L", size: " << ullObjectSize << + L", created: " << wfd.ftCreationTime << + L", last-access: " << wfd.ftLastAccessTime << + L", last-write: " << wfd.ftLastWriteTime << + GetFindLogData(); + + rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), wfd.dwFileAttributes, ullObjectSize, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + return true; + } + else if (wfd.cFileName[0] != _T('.') || (wfd.cFileName[1] != _T('\0') && (wfd.cFileName[1] != _T('.') || wfd.cFileName[2] != _T('\0')))) + { + LOG_TRACE(m_spLog) << "Found file: " << wfd.cFileName << + L", attrs: " << wfd.dwFileAttributes << + L", size: " << ullObjectSize << + L", created: " << wfd.ftCreationTime << + L", last-access: " << wfd.ftLastAccessTime << + L", last-write: " << wfd.ftLastWriteTime << + GetFindLogData(); + + // Add directory itself + rspFileInfo->Init(m_pathDir + PathFromString(wfd.cFileName), + wfd.dwFileAttributes, ullObjectSize, wfd.ftCreationTime, + wfd.ftLastAccessTime, wfd.ftLastWriteTime, 0); + return true; + } + } while (m_hFind != INVALID_HANDLE_VALUE && ::FindNextFile(m_hFind, &wfd)); // checking m_hFind in case other thread changed it (it shouldn't happen though) + + Close(); + } + + return false; + } + + void TLocalFilesystemFind::InternalClose() + { + if(m_hFind != INVALID_HANDLE_VALUE) + { + LOG_TRACE(m_spLog) << "Closing finder" << GetFindLogData(); + FindClose(m_hFind); + } + m_hFind = INVALID_HANDLE_VALUE; + } + + std::wstring TLocalFilesystemFind::GetFindLogData() const + { + std::wstringstream wss; + wss << L" (directory: " << m_pathDir << L", mask: " << m_pathMask << L", handle: " << m_hFind << L")"; + return wss.str(); + } + + void TLocalFilesystemFind::Close() + { + InternalClose(); + } +} Index: src/libchcore/TLocalFilesystemFind.h =================================================================== diff -u -rf8fcbbd1d2321cf0c8be79526c449384af654e49 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TLocalFilesystemFind.h (.../TLocalFilesystemFind.h) (revision f8fcbbd1d2321cf0c8be79526c449384af654e49) +++ src/libchcore/TLocalFilesystemFind.h (.../TLocalFilesystemFind.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,58 +1,58 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOCALFILESYSTEMFIND_H__ -#define __TLOCALFILESYSTEMFIND_H__ - -#include "libchcore.h" -#include "TFileInfoFwd.h" -#include "TPath.h" -#include "IFilesystemFind.h" -#include "..\liblogger\TLogger.h" - -namespace chcore -{ - class LIBCHCORE_API TLocalFilesystemFind : public IFilesystemFind - { - public: - virtual ~TLocalFilesystemFind(); - - virtual bool FindNext(TFileInfoPtr& rspFileInfo) override; - virtual void Close() override; - - private: - TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask, const logger::TLogFileDataPtr& spLogFileData); - - void InternalClose(); - std::wstring GetFindLogData() const; - - private: - TSmartPath m_pathDir; - TSmartPath m_pathMask; - HANDLE m_hFind; - -#pragma warning(push) -#pragma warning(disable: 4251) - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - - friend class TLocalFilesystem; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOCALFILESYSTEMFIND_H__ +#define __TLOCALFILESYSTEMFIND_H__ + +#include "libchcore.h" +#include "TFileInfoFwd.h" +#include "TPath.h" +#include "IFilesystemFind.h" +#include "..\liblogger\TLogger.h" + +namespace chcore +{ + class LIBCHCORE_API TLocalFilesystemFind : public IFilesystemFind + { + public: + virtual ~TLocalFilesystemFind(); + + virtual bool FindNext(TFileInfoPtr& rspFileInfo) override; + virtual void Close() override; + + private: + TLocalFilesystemFind(const TSmartPath& pathDir, const TSmartPath& pathMask, const logger::TLogFileDataPtr& spLogFileData); + + void InternalClose(); + std::wstring GetFindLogData() const; + + private: + TSmartPath m_pathDir; + TSmartPath m_pathMask; + HANDLE m_hFind; + +#pragma warning(push) +#pragma warning(disable: 4251) + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + + friend class TLocalFilesystem; + }; +} + +#endif Index: src/libchcore/TModPathContainer.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TModPathContainer.cpp (.../TModPathContainer.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TModPathContainer.cpp (.../TModPathContainer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,337 +1,337 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TModPathContainer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TPathContainer.h" -#include "ISerializerRowData.h" - -namespace chcore -{ - // ============================================================================ - /// TModPathContainer::TModPathContainer - /// @date 2009/11/30 - /// - /// @brief Constructs an empty path container object. - // ============================================================================ - TModPathContainer::TModPathContainer() : - m_vPaths(), - m_oidNextObjectID(1) - { - } - - // ============================================================================ - /// TModPathContainer::TModPathContainer - /// @date 2009/11/30 - /// - /// @brief Constructs the path container object from another path container. - /// @param[in] rSrcContainer - path container to copy paths from. - // ============================================================================ - TModPathContainer::TModPathContainer(const TModPathContainer& rSrcContainer) : - m_vPaths(rSrcContainer.m_vPaths), - m_oidNextObjectID(rSrcContainer.m_oidNextObjectID) - { - } - - // ============================================================================ - /// TModPathContainer::~TModPathContainer - /// @date 2009/11/30 - /// - /// @brief Destructs this path container object. - // ============================================================================ - TModPathContainer::~TModPathContainer() - { - } - - // ============================================================================ - /// TModPathContainer::operator= - /// @date 2009/11/30 - /// - /// @brief Assigns another path container object to this one. - /// @param[in] rSrcContainer - container with paths to copy from. - /// @return Reference to this object. - // ============================================================================ - TModPathContainer& TModPathContainer::operator=(const TModPathContainer& rSrcContainer) - { - if (this != &rSrcContainer) - { - m_vPaths = rSrcContainer.m_vPaths; - m_oidNextObjectID = rSrcContainer.m_oidNextObjectID; - } - - return *this; - } - - TModPathContainer& TModPathContainer::operator=(const TPathContainer& rSrcContainer) - { - Clear(true); - - for (size_t stIndex = 0; stIndex < rSrcContainer.GetCount(); ++stIndex) - { - m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(rSrcContainer.GetAt(stIndex), true))); - } - - return *this; - } - - // ============================================================================ - /// TModPathContainer::Add - /// @date 2009/11/30 - /// - /// @brief Adds a path to the end of list. - /// @param[in] spPath - path to be added. - // ============================================================================ - void TModPathContainer::Add(const TSmartPath& spPath) - { - m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(spPath, true))); - } - - // ============================================================================ - /// TModPathContainer::GetAt - /// @date 2009/11/30 - /// - /// @brief Retrieves path at specified index. - /// @param[in] stIndex - index at which to retrieve item. - /// @return Reference to the path object. - // ============================================================================ - const TSmartPath& TModPathContainer::GetAt(size_t stIndex) const - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - DataMap::const_iterator iter = m_vPaths.cbegin() + stIndex; - return iter->second; - } - - // ============================================================================ - /// TModPathContainer::GetAt - /// @date 2009/11/30 - /// - /// @brief Retrieves path at specified index. - /// @param[in] stIndex - index at which to retrieve item. - /// @return Reference to the path object. - // ============================================================================ - TSmartPath& TModPathContainer::GetAt(size_t stIndex) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - DataMap::iterator iter = m_vPaths.begin() + stIndex; - return iter->second.Modify(); - } - - object_id_t TModPathContainer::GetOidAt(size_t stIndex) const - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - DataMap::const_iterator iter = m_vPaths.begin() + stIndex; - return iter->first; - } - - // ============================================================================ - /// TModPathContainer::SetAt - /// @date 2009/11/30 - /// - /// @brief Sets a path at a specified index. - /// @param[in] stIndex - index at which to set the path. - /// @param[in] spPath - path to be set. - // ============================================================================ - void TModPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - DataMap::iterator iter = m_vPaths.begin() + stIndex; - iter->second = spPath; - } - - // ============================================================================ - /// TModPathContainer::DeleteAt - /// @date 2009/11/30 - /// - /// @brief Removes a path from container at specified index. - /// @param[in] stIndex - index at which to delete. - // ============================================================================ - void TModPathContainer::DeleteAt(size_t stIndex) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - DataMap::iterator iterDel = m_vPaths.begin() + stIndex; - m_setRemovedItems.Add(iterDel->first); - m_vPaths.erase(iterDel); - } - - // ============================================================================ - /// TModPathContainer::Clear - /// @date 2009/11/30 - /// - /// @brief Removes all paths from this container. - // ============================================================================ - void TModPathContainer::Clear(bool bClearModificationsData) - { - if (!bClearModificationsData) - { - for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) - { - m_setRemovedItems.Add(iterDel->first); - } - } - else - { - m_setRemovedItems.Clear(); - m_oidNextObjectID = 1; - } - - m_vPaths.clear(); - } - - // ============================================================================ - /// TModPathContainer::GetCount - /// @date 2009/11/30 - /// - /// @brief Retrieves count of elements in the container. - /// @return Count of elements. - // ============================================================================ - size_t TModPathContainer::GetCount() const - { - return m_vPaths.size(); - } - - // ============================================================================ - /// TModPathContainer::GetCount - /// @date 2010/10/12 - /// - /// @brief Retrieves info if this container is empty. - /// @return True if empty, false otherwise. - // ============================================================================ - bool TModPathContainer::IsEmpty() const - { - return m_vPaths.empty(); - } - - const TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) const - { - return m_vPaths.at(oidObjectID); - } - - TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) - { - return m_vPaths.at(oidObjectID).Modify(); - } - - void TModPathContainer::SetByOid(object_id_t oidObjectID, const TSmartPath& spPath) - { - DataMap::iterator iterFnd = m_vPaths.find(oidObjectID); - if (iterFnd != m_vPaths.end()) - iterFnd->second = spPath; - else - m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(spPath, true))); - } - - void TModPathContainer::DeleteOid(object_id_t oidObjectID) - { - m_vPaths.erase(oidObjectID); - m_setRemovedItems.Add(oidObjectID); - } - - bool TModPathContainer::HasModifications() const - { - if (!m_setRemovedItems.IsEmpty()) - return true; - - for (DataMap::const_iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) - { - if (iterDel->second.IsModified() || iterDel->second.IsAdded()) - return true; - } - - return false; - } - - void TModPathContainer::ClearModifications() - { - m_setRemovedItems.Clear(); - - for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) - { - iterDel->second.ClearModifications(); - } - } - - void TModPathContainer::Store(const ISerializerContainerPtr& spContainer) const - { - InitColumns(spContainer); - - // delete items first - spContainer->DeleteRows(m_setRemovedItems); - m_setRemovedItems.Clear(); - - // add/modify - for (DataMap::const_iterator iterPath = m_vPaths.begin(); iterPath != m_vPaths.end(); ++iterPath) - { - const TModificationTracker& rItem = iterPath->second; - - if (rItem.IsModified()) - { - ISerializerRowData& rRow = spContainer->GetRow(iterPath->first, rItem.IsAdded()); - rRow.SetValue(_T("path"), rItem); - - rItem.ClearModifications(); - } - else - continue; - } - } - - void TModPathContainer::Load(const ISerializerContainerPtr& spContainer) - { - m_setRemovedItems.Clear(); - m_vPaths.clear(); - m_oidNextObjectID = 1; - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - while (spRowReader->Next()) - { - object_id_t oidObjectID = 0; - TSmartPath path; - - spRowReader->GetValue(_T("id"), oidObjectID); - spRowReader->GetValue(_T("path"), path); - - m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(path, false))); - } - - ClearModifications(); - } - - void TModPathContainer::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TModPathContainer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TPathContainer.h" +#include "ISerializerRowData.h" + +namespace chcore +{ + // ============================================================================ + /// TModPathContainer::TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs an empty path container object. + // ============================================================================ + TModPathContainer::TModPathContainer() : + m_vPaths(), + m_oidNextObjectID(1) + { + } + + // ============================================================================ + /// TModPathContainer::TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs the path container object from another path container. + /// @param[in] rSrcContainer - path container to copy paths from. + // ============================================================================ + TModPathContainer::TModPathContainer(const TModPathContainer& rSrcContainer) : + m_vPaths(rSrcContainer.m_vPaths), + m_oidNextObjectID(rSrcContainer.m_oidNextObjectID) + { + } + + // ============================================================================ + /// TModPathContainer::~TModPathContainer + /// @date 2009/11/30 + /// + /// @brief Destructs this path container object. + // ============================================================================ + TModPathContainer::~TModPathContainer() + { + } + + // ============================================================================ + /// TModPathContainer::operator= + /// @date 2009/11/30 + /// + /// @brief Assigns another path container object to this one. + /// @param[in] rSrcContainer - container with paths to copy from. + /// @return Reference to this object. + // ============================================================================ + TModPathContainer& TModPathContainer::operator=(const TModPathContainer& rSrcContainer) + { + if (this != &rSrcContainer) + { + m_vPaths = rSrcContainer.m_vPaths; + m_oidNextObjectID = rSrcContainer.m_oidNextObjectID; + } + + return *this; + } + + TModPathContainer& TModPathContainer::operator=(const TPathContainer& rSrcContainer) + { + Clear(true); + + for (size_t stIndex = 0; stIndex < rSrcContainer.GetCount(); ++stIndex) + { + m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(rSrcContainer.GetAt(stIndex), true))); + } + + return *this; + } + + // ============================================================================ + /// TModPathContainer::Add + /// @date 2009/11/30 + /// + /// @brief Adds a path to the end of list. + /// @param[in] spPath - path to be added. + // ============================================================================ + void TModPathContainer::Add(const TSmartPath& spPath) + { + m_vPaths.insert(std::make_pair(m_oidNextObjectID++, TModificationTracker(spPath, true))); + } + + // ============================================================================ + /// TModPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + const TSmartPath& TModPathContainer::GetAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + DataMap::const_iterator iter = m_vPaths.cbegin() + stIndex; + return iter->second; + } + + // ============================================================================ + /// TModPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + TSmartPath& TModPathContainer::GetAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + DataMap::iterator iter = m_vPaths.begin() + stIndex; + return iter->second.Modify(); + } + + object_id_t TModPathContainer::GetOidAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + DataMap::const_iterator iter = m_vPaths.begin() + stIndex; + return iter->first; + } + + // ============================================================================ + /// TModPathContainer::SetAt + /// @date 2009/11/30 + /// + /// @brief Sets a path at a specified index. + /// @param[in] stIndex - index at which to set the path. + /// @param[in] spPath - path to be set. + // ============================================================================ + void TModPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + DataMap::iterator iter = m_vPaths.begin() + stIndex; + iter->second = spPath; + } + + // ============================================================================ + /// TModPathContainer::DeleteAt + /// @date 2009/11/30 + /// + /// @brief Removes a path from container at specified index. + /// @param[in] stIndex - index at which to delete. + // ============================================================================ + void TModPathContainer::DeleteAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + DataMap::iterator iterDel = m_vPaths.begin() + stIndex; + m_setRemovedItems.Add(iterDel->first); + m_vPaths.erase(iterDel); + } + + // ============================================================================ + /// TModPathContainer::Clear + /// @date 2009/11/30 + /// + /// @brief Removes all paths from this container. + // ============================================================================ + void TModPathContainer::Clear(bool bClearModificationsData) + { + if (!bClearModificationsData) + { + for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + m_setRemovedItems.Add(iterDel->first); + } + } + else + { + m_setRemovedItems.Clear(); + m_oidNextObjectID = 1; + } + + m_vPaths.clear(); + } + + // ============================================================================ + /// TModPathContainer::GetCount + /// @date 2009/11/30 + /// + /// @brief Retrieves count of elements in the container. + /// @return Count of elements. + // ============================================================================ + size_t TModPathContainer::GetCount() const + { + return m_vPaths.size(); + } + + // ============================================================================ + /// TModPathContainer::GetCount + /// @date 2010/10/12 + /// + /// @brief Retrieves info if this container is empty. + /// @return True if empty, false otherwise. + // ============================================================================ + bool TModPathContainer::IsEmpty() const + { + return m_vPaths.empty(); + } + + const TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) const + { + return m_vPaths.at(oidObjectID); + } + + TSmartPath& TModPathContainer::GetAtOid(object_id_t oidObjectID) + { + return m_vPaths.at(oidObjectID).Modify(); + } + + void TModPathContainer::SetByOid(object_id_t oidObjectID, const TSmartPath& spPath) + { + DataMap::iterator iterFnd = m_vPaths.find(oidObjectID); + if (iterFnd != m_vPaths.end()) + iterFnd->second = spPath; + else + m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(spPath, true))); + } + + void TModPathContainer::DeleteOid(object_id_t oidObjectID) + { + m_vPaths.erase(oidObjectID); + m_setRemovedItems.Add(oidObjectID); + } + + bool TModPathContainer::HasModifications() const + { + if (!m_setRemovedItems.IsEmpty()) + return true; + + for (DataMap::const_iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + if (iterDel->second.IsModified() || iterDel->second.IsAdded()) + return true; + } + + return false; + } + + void TModPathContainer::ClearModifications() + { + m_setRemovedItems.Clear(); + + for (DataMap::iterator iterDel = m_vPaths.begin(); iterDel != m_vPaths.end(); ++iterDel) + { + iterDel->second.ClearModifications(); + } + } + + void TModPathContainer::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); + + // delete items first + spContainer->DeleteRows(m_setRemovedItems); + m_setRemovedItems.Clear(); + + // add/modify + for (DataMap::const_iterator iterPath = m_vPaths.begin(); iterPath != m_vPaths.end(); ++iterPath) + { + const TModificationTracker& rItem = iterPath->second; + + if (rItem.IsModified()) + { + ISerializerRowData& rRow = spContainer->GetRow(iterPath->first, rItem.IsAdded()); + rRow.SetValue(_T("path"), rItem); + + rItem.ClearModifications(); + } + else + continue; + } + } + + void TModPathContainer::Load(const ISerializerContainerPtr& spContainer) + { + m_setRemovedItems.Clear(); + m_vPaths.clear(); + m_oidNextObjectID = 1; + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + while (spRowReader->Next()) + { + object_id_t oidObjectID = 0; + TSmartPath path; + + spRowReader->GetValue(_T("id"), oidObjectID); + spRowReader->GetValue(_T("path"), path); + + m_vPaths.insert(std::make_pair(oidObjectID, TModificationTracker(path, false))); + } + + ClearModifications(); + } + + void TModPathContainer::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + } + } +} Index: src/libchcore/TModPathContainer.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TModPathContainer.h (.../TModPathContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TModPathContainer.h (.../TModPathContainer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,92 +1,92 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TMODPATHCONTAINER_H__ -#define __TMODPATHCONTAINER_H__ - -#include "libchcore.h" -#include -#include "TModificationTracker.h" -#include "TPath.h" -#include "ISerializerContainer.h" -#include "TRemovedObjects.h" - -namespace chcore -{ - class LIBCHCORE_API TModPathContainer - { - public: - TModPathContainer(); - TModPathContainer(const TModPathContainer& rSrcContainer); - ~TModPathContainer(); - - TModPathContainer& operator=(const TModPathContainer& rSrcContainer); - TModPathContainer& operator=(const TPathContainer& rSrcContainer); - -#pragma region Index-based interface - void Add(const TSmartPath& spPath); - - const TSmartPath& GetAt(size_t stIndex) const; - TSmartPath& GetAt(size_t stIndex); - object_id_t GetOidAt(size_t stIndex) const; - - void SetAt(size_t stIndex, const TSmartPath& spPath); - - void DeleteAt(size_t stIndex); -#pragma endregion - -#pragma region Object id-based interface - const TSmartPath& GetAtOid(object_id_t oidObjectID) const; - TSmartPath& GetAtOid(object_id_t oidObjectID); - - void SetByOid(object_id_t oidObjectID, const TSmartPath& spPath); - void DeleteOid(object_id_t oidObjectID); -#pragma endregion - -#pragma region Generic interface - void Clear(bool bClearModificationsData); - - size_t GetCount() const; - bool IsEmpty() const; -#pragma endregion - -#pragma region Modifications management - bool HasModifications() const; - void ClearModifications(); -#pragma endregion - -#pragma region Serialization - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - -#pragma endregion - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - mutable TRemovedObjects m_setRemovedItems; - typedef boost::container::flat_map > DataMap; - DataMap m_vPaths; -#pragma warning(pop) - object_id_t m_oidNextObjectID; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TMODPATHCONTAINER_H__ +#define __TMODPATHCONTAINER_H__ + +#include "libchcore.h" +#include +#include "TModificationTracker.h" +#include "TPath.h" +#include "ISerializerContainer.h" +#include "TRemovedObjects.h" + +namespace chcore +{ + class LIBCHCORE_API TModPathContainer + { + public: + TModPathContainer(); + TModPathContainer(const TModPathContainer& rSrcContainer); + ~TModPathContainer(); + + TModPathContainer& operator=(const TModPathContainer& rSrcContainer); + TModPathContainer& operator=(const TPathContainer& rSrcContainer); + +#pragma region Index-based interface + void Add(const TSmartPath& spPath); + + const TSmartPath& GetAt(size_t stIndex) const; + TSmartPath& GetAt(size_t stIndex); + object_id_t GetOidAt(size_t stIndex) const; + + void SetAt(size_t stIndex, const TSmartPath& spPath); + + void DeleteAt(size_t stIndex); +#pragma endregion + +#pragma region Object id-based interface + const TSmartPath& GetAtOid(object_id_t oidObjectID) const; + TSmartPath& GetAtOid(object_id_t oidObjectID); + + void SetByOid(object_id_t oidObjectID, const TSmartPath& spPath); + void DeleteOid(object_id_t oidObjectID); +#pragma endregion + +#pragma region Generic interface + void Clear(bool bClearModificationsData); + + size_t GetCount() const; + bool IsEmpty() const; +#pragma endregion + +#pragma region Modifications management + bool HasModifications() const; + void ClearModifications(); +#pragma endregion + +#pragma region Serialization + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + +#pragma endregion + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + mutable TRemovedObjects m_setRemovedItems; + typedef boost::container::flat_map > DataMap; + DataMap m_vPaths; +#pragma warning(pop) + object_id_t m_oidNextObjectID; + }; +} + +#endif Index: src/libchcore/TModificationTracker.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TModificationTracker.h (.../TModificationTracker.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TModificationTracker.h (.../TModificationTracker.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,111 +1,111 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TMODIFICATIONTRACKER_H__ -#define __TMODIFICATIONTRACKER_H__ - -namespace chcore -{ - template - class TModificationTracker - { - public: - TModificationTracker() : - m_tValue(), - m_chModified(eMod_Modified) - { - } - - template - TModificationTracker(const V& rValue, bool bAdded) : - m_tValue(rValue), - m_chModified((char)eMod_Modified | (bAdded ? (char)eMod_Added : (char)eMod_None)) - { - } - - TModificationTracker(const TModificationTracker& rSrc) : - m_chModified(rSrc.m_chModified), - m_tValue(rSrc.m_tValue) - { - } - - TModificationTracker& operator=(const TModificationTracker& rSrc) - { - m_chModified = rSrc.m_chModified; - m_tValue = rSrc.m_tValue; - - return *this; - } - - template - TModificationTracker& operator=(const V& rValue) - { - if (m_tValue != rValue) - { - m_tValue = rValue; - m_chModified |= eMod_Modified; - } - - return *this; - } - - operator const T&() const - { - return m_tValue; - } - - const T& Get() const - { - return m_tValue; - } - - T& Modify() - { - m_chModified |= eMod_Modified; - return m_tValue; - } - - void ClearModifications() const - { - m_chModified = eMod_None; - } - - bool IsModified() const - { - return m_chModified != 0; // must also include 'Added' status! - } - - bool IsAdded() const - { - return (m_chModified & eMod_Added) != 0; - } - - private: - enum EModifiedFlags - { - eMod_None = 0, - eMod_Added = 1, - eMod_Modified = 2 - }; - - T m_tValue; - mutable char m_chModified; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TMODIFICATIONTRACKER_H__ +#define __TMODIFICATIONTRACKER_H__ + +namespace chcore +{ + template + class TModificationTracker + { + public: + TModificationTracker() : + m_tValue(), + m_chModified(eMod_Modified) + { + } + + template + TModificationTracker(const V& rValue, bool bAdded) : + m_tValue(rValue), + m_chModified((char)eMod_Modified | (bAdded ? (char)eMod_Added : (char)eMod_None)) + { + } + + TModificationTracker(const TModificationTracker& rSrc) : + m_chModified(rSrc.m_chModified), + m_tValue(rSrc.m_tValue) + { + } + + TModificationTracker& operator=(const TModificationTracker& rSrc) + { + m_chModified = rSrc.m_chModified; + m_tValue = rSrc.m_tValue; + + return *this; + } + + template + TModificationTracker& operator=(const V& rValue) + { + if (m_tValue != rValue) + { + m_tValue = rValue; + m_chModified |= eMod_Modified; + } + + return *this; + } + + operator const T&() const + { + return m_tValue; + } + + const T& Get() const + { + return m_tValue; + } + + T& Modify() + { + m_chModified |= eMod_Modified; + return m_tValue; + } + + void ClearModifications() const + { + m_chModified = eMod_None; + } + + bool IsModified() const + { + return m_chModified != 0; // must also include 'Added' status! + } + + bool IsAdded() const + { + return (m_chModified & eMod_Added) != 0; + } + + private: + enum EModifiedFlags + { + eMod_None = 0, + eMod_Added = 1, + eMod_Modified = 2 + }; + + T m_tValue; + mutable char m_chModified; + }; +} + +#endif Index: src/libchcore/TObsoleteFiles.cpp =================================================================== diff -u -ra6834b56f41e9e4a44a2869ffdad1599da9b24c4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TObsoleteFiles.cpp (.../TObsoleteFiles.cpp) (revision a6834b56f41e9e4a44a2869ffdad1599da9b24c4) +++ src/libchcore/TObsoleteFiles.cpp (.../TObsoleteFiles.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,114 +1,114 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TObsoleteFiles.h" -#include "ISerializerContainer.h" - -namespace chcore -{ - ObsoleteFileInfo::ObsoleteFileInfo(const TSmartPath& path, bool bAdded) : - m_path(path), - m_bAdded(bAdded) - { - } - - ObsoleteFileInfo::ObsoleteFileInfo() : - m_bAdded(false) - { - } - - TObsoleteFiles::TObsoleteFiles() : - m_oidLast(0) - { - } - - TObsoleteFiles::~TObsoleteFiles() - { - } - - void TObsoleteFiles::DeleteObsoleteFile(const TSmartPath& pathToDelete) - { - if (!DeleteFile(pathToDelete.ToString()) && GetLastError() != ERROR_FILE_NOT_FOUND) - m_mapPaths.insert(std::make_pair(++m_oidLast, ObsoleteFileInfo(pathToDelete, true))); - } - - void TObsoleteFiles::Store(const ISerializerContainerPtr& spContainer) const - { - InitColumns(spContainer); - - spContainer->DeleteRows(m_setRemovedObjects); - m_setRemovedObjects.Clear(); - - for (MapPaths::const_iterator iter = m_mapPaths.begin(); iter != m_mapPaths.end(); ++iter) - { - if (iter->second.m_bAdded) - { - ISerializerRowData& rRow = spContainer->GetRow(iter->first, true); - rRow.SetValue(_T("path"), iter->second.m_path); - } - - iter->second.m_bAdded = false; - } - } - - void TObsoleteFiles::Load(const ISerializerContainerPtr& spContainer) - { - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - ObsoleteFileInfo tEntry; - object_id_t oid = 0; - while (spRowReader->Next()) - { - spRowReader->GetValue(_T("id"), oid); - spRowReader->GetValue(_T("path"), tEntry.m_path); - tEntry.m_bAdded = false; - - m_mapPaths.insert(std::make_pair(oid, tEntry)); - m_oidLast = std::max(m_oidLast, oid); - } - - m_setRemovedObjects.Clear(); - - // try to delete files - MapPaths::iterator iter = m_mapPaths.begin(); - while (iter != m_mapPaths.end()) - { - BOOL bDeleted = DeleteFile(iter->second.m_path.ToString()); - if (bDeleted || GetLastError() == ERROR_FILE_NOT_FOUND) - { - m_setRemovedObjects.Add(iter->first); - iter = m_mapPaths.erase(iter); - } - else - ++iter; - } - } - - void TObsoleteFiles::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TObsoleteFiles.h" +#include "ISerializerContainer.h" + +namespace chcore +{ + ObsoleteFileInfo::ObsoleteFileInfo(const TSmartPath& path, bool bAdded) : + m_path(path), + m_bAdded(bAdded) + { + } + + ObsoleteFileInfo::ObsoleteFileInfo() : + m_bAdded(false) + { + } + + TObsoleteFiles::TObsoleteFiles() : + m_oidLast(0) + { + } + + TObsoleteFiles::~TObsoleteFiles() + { + } + + void TObsoleteFiles::DeleteObsoleteFile(const TSmartPath& pathToDelete) + { + if (!DeleteFile(pathToDelete.ToString()) && GetLastError() != ERROR_FILE_NOT_FOUND) + m_mapPaths.insert(std::make_pair(++m_oidLast, ObsoleteFileInfo(pathToDelete, true))); + } + + void TObsoleteFiles::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); + + spContainer->DeleteRows(m_setRemovedObjects); + m_setRemovedObjects.Clear(); + + for (MapPaths::const_iterator iter = m_mapPaths.begin(); iter != m_mapPaths.end(); ++iter) + { + if (iter->second.m_bAdded) + { + ISerializerRowData& rRow = spContainer->GetRow(iter->first, true); + rRow.SetValue(_T("path"), iter->second.m_path); + } + + iter->second.m_bAdded = false; + } + } + + void TObsoleteFiles::Load(const ISerializerContainerPtr& spContainer) + { + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + ObsoleteFileInfo tEntry; + object_id_t oid = 0; + while (spRowReader->Next()) + { + spRowReader->GetValue(_T("id"), oid); + spRowReader->GetValue(_T("path"), tEntry.m_path); + tEntry.m_bAdded = false; + + m_mapPaths.insert(std::make_pair(oid, tEntry)); + m_oidLast = std::max(m_oidLast, oid); + } + + m_setRemovedObjects.Clear(); + + // try to delete files + MapPaths::iterator iter = m_mapPaths.begin(); + while (iter != m_mapPaths.end()) + { + BOOL bDeleted = DeleteFile(iter->second.m_path.ToString()); + if (bDeleted || GetLastError() == ERROR_FILE_NOT_FOUND) + { + m_setRemovedObjects.Add(iter->first); + iter = m_mapPaths.erase(iter); + } + else + ++iter; + } + } + + void TObsoleteFiles::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("path"), IColumnsDefinition::eType_path); + } + } +} Index: src/libchcore/TObsoleteFiles.h =================================================================== diff -u -ra6834b56f41e9e4a44a2869ffdad1599da9b24c4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TObsoleteFiles.h (.../TObsoleteFiles.h) (revision a6834b56f41e9e4a44a2869ffdad1599da9b24c4) +++ src/libchcore/TObsoleteFiles.h (.../TObsoleteFiles.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,65 +1,65 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TOBSOLETEFILES_H__ -#define __TOBSOLETEFILES_H__ - -#include "libchcore.h" -#include "TPath.h" -#include -#include "ISerializerRowData.h" -#include "SerializerDataTypes.h" -#include "TRemovedObjects.h" - -namespace chcore -{ - struct ObsoleteFileInfo - { - ObsoleteFileInfo(); - ObsoleteFileInfo(const TSmartPath& path, bool bAdded); - - TSmartPath m_path; - mutable bool m_bAdded; - }; - - class LIBCHCORE_API TObsoleteFiles - { - public: - TObsoleteFiles(); - virtual ~TObsoleteFiles(); - - void DeleteObsoleteFile(const TSmartPath& pathToDelete); - - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - typedef std::map MapPaths; - MapPaths m_mapPaths; -#pragma warning(pop) - - mutable TRemovedObjects m_setRemovedObjects; - object_id_t m_oidLast; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TOBSOLETEFILES_H__ +#define __TOBSOLETEFILES_H__ + +#include "libchcore.h" +#include "TPath.h" +#include +#include "ISerializerRowData.h" +#include "SerializerDataTypes.h" +#include "TRemovedObjects.h" + +namespace chcore +{ + struct ObsoleteFileInfo + { + ObsoleteFileInfo(); + ObsoleteFileInfo(const TSmartPath& path, bool bAdded); + + TSmartPath m_path; + mutable bool m_bAdded; + }; + + class LIBCHCORE_API TObsoleteFiles + { + public: + TObsoleteFiles(); + virtual ~TObsoleteFiles(); + + void DeleteObsoleteFile(const TSmartPath& pathToDelete); + + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + typedef std::map MapPaths; + MapPaths m_mapPaths; +#pragma warning(pop) + + mutable TRemovedObjects m_setRemovedObjects; + object_id_t m_oidLast; + }; +} + +#endif Index: src/libchcore/TOverlappedDataBuffer.cpp =================================================================== diff -u -r685d0da3259dd94327ee8d644a88c155585b8249 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TOverlappedDataBuffer.cpp (.../TOverlappedDataBuffer.cpp) (revision 685d0da3259dd94327ee8d644a88c155585b8249) +++ src/libchcore/TOverlappedDataBuffer.cpp (.../TOverlappedDataBuffer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,119 +1,119 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TDataBuffer.cpp -/// @date 2012/03/04 -/// @brief Contains class representing buffer for data. -// ============================================================================ -#include "stdafx.h" -#include "TOverlappedDataBuffer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - bool CompareBufferPositions::operator()(const TOverlappedDataBuffer* pBufferA, const TOverlappedDataBuffer* pBufferB) const - { - if(!pBufferA) - throw TCoreException(eErr_InvalidArgument, L"pBufferA", LOCATION); - if(!pBufferB) - throw TCoreException(eErr_InvalidArgument, L"pBufferB", LOCATION); - - return pBufferA->GetFilePosition() < pBufferB->GetFilePosition(); - } - - TOverlappedDataBuffer::TOverlappedDataBuffer(size_t stBufferSize, void* pParam) : - m_pParam(pParam) - { - // initialize OVERLAPPED members - Internal = 0; - InternalHigh = 0; - Offset = 0; - OffsetHigh = 0; - hEvent = nullptr; - - // create buffer - ReinitializeBuffer(stBufferSize); - } - - TOverlappedDataBuffer::~TOverlappedDataBuffer() - { - ReleaseBuffer(); - } - - void TOverlappedDataBuffer::ReinitializeBuffer(size_t stNewBufferSize) - { - if (stNewBufferSize == 0) - throw TCoreException(eErr_InvalidArgument, L"Cannot create 0-sized buffer", LOCATION); - - if (stNewBufferSize != m_stBufferSize) - { - ReleaseBuffer(); - - m_pBuffer = VirtualAlloc(nullptr, stNewBufferSize, MEM_COMMIT, PAGE_READWRITE); - if (!m_pBuffer) - throw TCoreException(eErr_CannotAllocateMemory, L"VirtualAlloc failed", LOCATION); - m_stBufferSize = stNewBufferSize; - } - } - - void TOverlappedDataBuffer::ReleaseBuffer() - { - if (m_pBuffer) - { - VirtualFree(m_pBuffer, 0, MEM_RELEASE); - m_stBufferSize = 0; - m_pBuffer = nullptr; - } - } - - LPVOID TOverlappedDataBuffer::GetBufferPtr() - { - return m_pBuffer; - } - - void TOverlappedDataBuffer::InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize) - { - SetRequestedDataSize(dwRequestedSize); - SetFilePosition(ullPosition); - SetRealDataSize(0); - SetLastPart(false); - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); - } - - void TOverlappedDataBuffer::InitForWrite() - { - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); - } - - void TOverlappedDataBuffer::Reset() - { - SetRequestedDataSize(0); - SetFilePosition(0); - SetRealDataSize(0); - SetLastPart(false); - SetErrorCode(ERROR_SUCCESS); - SetStatusCode(0); - SetBytesTransferred(0); - SetParam(nullptr); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TDataBuffer.cpp +/// @date 2012/03/04 +/// @brief Contains class representing buffer for data. +// ============================================================================ +#include "stdafx.h" +#include "TOverlappedDataBuffer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + bool CompareBufferPositions::operator()(const TOverlappedDataBuffer* pBufferA, const TOverlappedDataBuffer* pBufferB) const + { + if(!pBufferA) + throw TCoreException(eErr_InvalidArgument, L"pBufferA", LOCATION); + if(!pBufferB) + throw TCoreException(eErr_InvalidArgument, L"pBufferB", LOCATION); + + return pBufferA->GetFilePosition() < pBufferB->GetFilePosition(); + } + + TOverlappedDataBuffer::TOverlappedDataBuffer(size_t stBufferSize, void* pParam) : + m_pParam(pParam) + { + // initialize OVERLAPPED members + Internal = 0; + InternalHigh = 0; + Offset = 0; + OffsetHigh = 0; + hEvent = nullptr; + + // create buffer + ReinitializeBuffer(stBufferSize); + } + + TOverlappedDataBuffer::~TOverlappedDataBuffer() + { + ReleaseBuffer(); + } + + void TOverlappedDataBuffer::ReinitializeBuffer(size_t stNewBufferSize) + { + if (stNewBufferSize == 0) + throw TCoreException(eErr_InvalidArgument, L"Cannot create 0-sized buffer", LOCATION); + + if (stNewBufferSize != m_stBufferSize) + { + ReleaseBuffer(); + + m_pBuffer = VirtualAlloc(nullptr, stNewBufferSize, MEM_COMMIT, PAGE_READWRITE); + if (!m_pBuffer) + throw TCoreException(eErr_CannotAllocateMemory, L"VirtualAlloc failed", LOCATION); + m_stBufferSize = stNewBufferSize; + } + } + + void TOverlappedDataBuffer::ReleaseBuffer() + { + if (m_pBuffer) + { + VirtualFree(m_pBuffer, 0, MEM_RELEASE); + m_stBufferSize = 0; + m_pBuffer = nullptr; + } + } + + LPVOID TOverlappedDataBuffer::GetBufferPtr() + { + return m_pBuffer; + } + + void TOverlappedDataBuffer::InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize) + { + SetRequestedDataSize(dwRequestedSize); + SetFilePosition(ullPosition); + SetRealDataSize(0); + SetLastPart(false); + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + } + + void TOverlappedDataBuffer::InitForWrite() + { + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + } + + void TOverlappedDataBuffer::Reset() + { + SetRequestedDataSize(0); + SetFilePosition(0); + SetRealDataSize(0); + SetLastPart(false); + SetErrorCode(ERROR_SUCCESS); + SetStatusCode(0); + SetBytesTransferred(0); + SetParam(nullptr); + } +} Index: src/libchcore/TOverlappedDataBuffer.h =================================================================== diff -u -rb941384e121190b6107f1c99b3233667e3daf4ce -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TOverlappedDataBuffer.h (.../TOverlappedDataBuffer.h) (revision b941384e121190b6107f1c99b3233667e3daf4ce) +++ src/libchcore/TOverlappedDataBuffer.h (.../TOverlappedDataBuffer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,103 +1,103 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TOverlappedDataBuffer.h -/// @date 2012/03/04 -/// @brief Contains class representing buffer for data. -// ============================================================================ -#ifndef __TDATABUFFER_H__ -#define __TDATABUFFER_H__ - -namespace chcore -{ - class TOverlappedDataBuffer; - - struct CompareBufferPositions - { - bool operator()(const TOverlappedDataBuffer* rBufferA, const TOverlappedDataBuffer* rBufferB) const; - }; - - class TOverlappedDataBuffer : public OVERLAPPED - { - public: - // construction/destruction - TOverlappedDataBuffer(size_t stBufferSize, void* pParam); - TOverlappedDataBuffer(const TOverlappedDataBuffer&) = delete; - TOverlappedDataBuffer(TOverlappedDataBuffer&& rSrc) = delete; - - ~TOverlappedDataBuffer(); - - // operators - TOverlappedDataBuffer& operator=(const TOverlappedDataBuffer&) = delete; - TOverlappedDataBuffer& operator=(TOverlappedDataBuffer&& rSrc) = delete; - - // interface methods - // buffer size management - void ReinitializeBuffer(size_t stNewBufferSize); - LPVOID GetBufferPtr(); - - size_t GetBufferSize() const { return m_stBufferSize; } - - // members - DWORD GetRequestedDataSize() const { return m_dwRequestedDataSize; } - void SetRequestedDataSize(DWORD dwRequestedSize) { m_dwRequestedDataSize = dwRequestedSize; } - - DWORD GetRealDataSize() const { return m_dwRealDataSize; } - void SetRealDataSize(DWORD dwRealDataSize) { m_dwRealDataSize = dwRealDataSize; } - - void SetLastPart(bool bLastPart) { m_bLastPart = bLastPart; } - bool IsLastPart() const { return m_bLastPart; } - - DWORD GetErrorCode() const { return m_dwErrorCode; } - void SetErrorCode(DWORD dwErrorCode) { m_dwErrorCode = dwErrorCode; } - bool HasError() const { return m_dwErrorCode != ERROR_SUCCESS; } - - // OVERLAPPED interface - ULONG_PTR GetStatusCode() const { return Internal; } - void SetStatusCode(ULONG_PTR ulStatusCode) { Internal = ulStatusCode; } - - void SetBytesTransferred(ULONG_PTR ulBytes) { InternalHigh = ulBytes; } - ULONG_PTR GetBytesTransferred() const { return InternalHigh; } - - unsigned long long GetFilePosition() const { return (unsigned long long)OffsetHigh << 32 | Offset; } - void SetFilePosition(unsigned long long ullPosition) { OffsetHigh = (DWORD)(ullPosition >> 32); Offset = (DWORD)ullPosition; } - - void* GetParam() const { return m_pParam; } - void SetParam(void* pParam) { m_pParam = pParam; } - - // composite initialization - void InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize); - void InitForWrite(); - void Reset(); - - private: - void ReleaseBuffer(); - - private: - LPVOID m_pBuffer = nullptr; // pointer to the allocated buffer - size_t m_stBufferSize = 0; // total buffer size - DWORD m_dwRequestedDataSize = 0; // part of the buffer that is to be used for data transfer (<= m_stBufferSize) - DWORD m_dwRealDataSize = 0; // data size as reported by read operation - DWORD m_dwErrorCode = 0; // win32 error code - bool m_bLastPart = false; // marks the last part of the file - - void* m_pParam = nullptr; // pointer to the queue where this object resides - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TOverlappedDataBuffer.h +/// @date 2012/03/04 +/// @brief Contains class representing buffer for data. +// ============================================================================ +#ifndef __TDATABUFFER_H__ +#define __TDATABUFFER_H__ + +namespace chcore +{ + class TOverlappedDataBuffer; + + struct CompareBufferPositions + { + bool operator()(const TOverlappedDataBuffer* rBufferA, const TOverlappedDataBuffer* rBufferB) const; + }; + + class TOverlappedDataBuffer : public OVERLAPPED + { + public: + // construction/destruction + TOverlappedDataBuffer(size_t stBufferSize, void* pParam); + TOverlappedDataBuffer(const TOverlappedDataBuffer&) = delete; + TOverlappedDataBuffer(TOverlappedDataBuffer&& rSrc) = delete; + + ~TOverlappedDataBuffer(); + + // operators + TOverlappedDataBuffer& operator=(const TOverlappedDataBuffer&) = delete; + TOverlappedDataBuffer& operator=(TOverlappedDataBuffer&& rSrc) = delete; + + // interface methods + // buffer size management + void ReinitializeBuffer(size_t stNewBufferSize); + LPVOID GetBufferPtr(); + + size_t GetBufferSize() const { return m_stBufferSize; } + + // members + DWORD GetRequestedDataSize() const { return m_dwRequestedDataSize; } + void SetRequestedDataSize(DWORD dwRequestedSize) { m_dwRequestedDataSize = dwRequestedSize; } + + DWORD GetRealDataSize() const { return m_dwRealDataSize; } + void SetRealDataSize(DWORD dwRealDataSize) { m_dwRealDataSize = dwRealDataSize; } + + void SetLastPart(bool bLastPart) { m_bLastPart = bLastPart; } + bool IsLastPart() const { return m_bLastPart; } + + DWORD GetErrorCode() const { return m_dwErrorCode; } + void SetErrorCode(DWORD dwErrorCode) { m_dwErrorCode = dwErrorCode; } + bool HasError() const { return m_dwErrorCode != ERROR_SUCCESS; } + + // OVERLAPPED interface + ULONG_PTR GetStatusCode() const { return Internal; } + void SetStatusCode(ULONG_PTR ulStatusCode) { Internal = ulStatusCode; } + + void SetBytesTransferred(ULONG_PTR ulBytes) { InternalHigh = ulBytes; } + ULONG_PTR GetBytesTransferred() const { return InternalHigh; } + + unsigned long long GetFilePosition() const { return (unsigned long long)OffsetHigh << 32 | Offset; } + void SetFilePosition(unsigned long long ullPosition) { OffsetHigh = (DWORD)(ullPosition >> 32); Offset = (DWORD)ullPosition; } + + void* GetParam() const { return m_pParam; } + void SetParam(void* pParam) { m_pParam = pParam; } + + // composite initialization + void InitForRead(unsigned long long ullPosition, DWORD dwRequestedSize); + void InitForWrite(); + void Reset(); + + private: + void ReleaseBuffer(); + + private: + LPVOID m_pBuffer = nullptr; // pointer to the allocated buffer + size_t m_stBufferSize = 0; // total buffer size + DWORD m_dwRequestedDataSize = 0; // part of the buffer that is to be used for data transfer (<= m_stBufferSize) + DWORD m_dwRealDataSize = 0; // data size as reported by read operation + DWORD m_dwErrorCode = 0; // win32 error code + bool m_bLastPart = false; // marks the last part of the file + + void* m_pParam = nullptr; // pointer to the queue where this object resides + }; +} + +#endif Index: src/libchcore/TPath.cpp =================================================================== diff -u -rf866db90e4b058a4f2e13cc6cf076d1e0bf2d956 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPath.cpp (.../TPath.cpp) (revision f866db90e4b058a4f2e13cc6cf076d1e0bf2d956) +++ src/libchcore/TPath.cpp (.../TPath.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,951 +1,951 @@ -/*************************************************************************** -* Copyright (C) 2001-2008 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#include "stdafx.h" -#include -#include -#include "TPath.h" -#pragma warning(push) -#pragma warning(disable: 4996) -#include -#pragma warning(pop) -#include -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TPathContainer.h" -#include "TStringArray.h" - -namespace chcore -{ -#define DEFAULT_PATH_SEPARATOR _T("\\") - - // ============================================================================ - /// TSmartPath::TSmartPath - /// @date 2009/11/29 - /// - /// @brief Constructs an empty path. - // ============================================================================ - TSmartPath::TSmartPath() : - m_strPath() - { - } - - // ============================================================================ - /// TSmartPath::TSmartPath - /// @date 2009/11/29 - /// - /// @brief Constructs path object from another path object. - /// @param[in] spPath - reference to another path object. - // ============================================================================ - TSmartPath::TSmartPath(const TSmartPath& spPath) : - m_strPath(spPath.m_strPath) - { - } - - // ============================================================================ - /// TSmartPath::~TSmartPath - /// @date 2009/11/29 - /// - /// @brief - /// @return - // ============================================================================ - TSmartPath::~TSmartPath() - { - Clear(); - } - - // ============================================================================ - /// TSmartPath::Clear - /// @date 2009/11/29 - /// - /// @brief Clears this object. - // ============================================================================ - void TSmartPath::Clear() throw() - { - m_strPath.Clear(); - } - - - TSmartPath TSmartPath::AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists) const - { - TSmartPath pathNew(*this); - pathNew.Append(pathToAppend, bEnsurePathSeparatorExists); - - return pathNew; - } - - TSmartPath& TSmartPath::Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists) - { - // if there is no path inside rPath, then there is no point in doing anything - if (!pathToAppend.m_strPath.IsEmpty()) - { - // if this path is empty, then optimize by just assigning the input path to this one - if (m_strPath.IsEmpty()) - *this = pathToAppend; - else - { - if (bEnsurePathSeparatorExists) - { - // detect separators - bool bThisEndsWithSeparator = EndsWithSeparator(); - bool bInStartsWithSeparator = pathToAppend.StartsWithSeparator(); - - if (!bThisEndsWithSeparator && !bInStartsWithSeparator) - m_strPath += _T("\\") + pathToAppend.m_strPath; - else if (bThisEndsWithSeparator ^ bInStartsWithSeparator) - m_strPath += pathToAppend.m_strPath; - else - { - m_strPath.Delete(m_strPath.GetLength() - 1, 1); - m_strPath += pathToAppend.m_strPath; - } - } - else - m_strPath += pathToAppend.m_strPath; - } - } - - return *this; - } - - // ============================================================================ - /// TSmartPath::operator= - /// @date 2009/11/29 - /// - /// @brief Assigns a path from other path object. - /// @param[in] spPath - path object from which we want to get path. - /// @return Reference to this object. - // ============================================================================ - TSmartPath& TSmartPath::operator=(const TSmartPath& spPath) - { - if (this != &spPath) - { - Clear(); - m_strPath = spPath.m_strPath; - } - - return *this; - } - - // ============================================================================ - /// TSmartPath::operator== - /// @date 2009/11/29 - /// - /// @brief Compares paths (case sensitive). - /// @param[in] rPath - path to compare this object to. - /// @return True if equal, false otherwise. - // ============================================================================ - bool TSmartPath::operator==(const TSmartPath& rPath) const - { - return Compare(rPath) == 0; - } - - - bool TSmartPath::operator!=(const TSmartPath& rPath) const - { - return Compare(rPath) != 0; - } - - // ============================================================================ - /// TSmartPath::operator< - /// @date 2009/11/29 - /// - /// @brief Compares paths (case sensitive). - /// @param[in] rPath - input path to compare. - /// @return True if this object is less than rPath, false otherwise. - // ============================================================================ - bool TSmartPath::operator<(const TSmartPath& rPath) const - { - return Compare(rPath) < 0; - } - - // ============================================================================ - /// TSmartPath::operator> - /// @date 2009/11/29 - /// - /// @brief Compares paths (case sensitive). - /// @param[in] rPath - input path to compare. - /// @return True if this object is less than rPath, false otherwise. - // ============================================================================ - bool TSmartPath::operator>(const TSmartPath& rPath) const - { - return Compare(rPath) > 0; - } - - // ============================================================================ - /// TSmartPath::operator+ - /// @date 2009/11/29 - /// - /// @brief Concatenates two paths, returns the result. - /// @param[in] rPath - path to concatenate. - /// @return New path object with the results of concatenation. - // ============================================================================ - TSmartPath TSmartPath::operator+(const TSmartPath& rPath) const - { - return AppendCopy(rPath, true); - } - - // ============================================================================ - /// TSmartPath::operator+= - /// @date 2009/11/29 - /// - /// @brief Concatenates provided path to our own. - /// @param[in] rPath - path to concatenate. - /// @return Reference to this object. - // ============================================================================ - TSmartPath& TSmartPath::operator+=(const TSmartPath& rPath) - { - return Append(rPath, true); - } - - // ============================================================================ - /// TSmartPath::FromString - /// @date 2010/10/12 - /// - /// @brief Initializes this path object with path contained in string. - /// @param[in] pszPath - string containing path. - // ============================================================================ - void TSmartPath::FromString(const wchar_t* pszPath) - { - if (!pszPath) - throw TCoreException(eErr_InvalidArgument, L"pszPath", LOCATION); - - m_strPath = pszPath; - } - - // ============================================================================ - /// TSmartPath::FromString - /// @date 2010/10/12 - /// - /// @brief Initializes this path object with path contained in string. - /// @param[in] strPath - string containing path. - // ============================================================================ - void TSmartPath::FromString(const TString& strPath) - { - m_strPath = strPath; - } - - // ============================================================================ - /// TSmartPath::ToString - /// @date 2010/10/12 - /// - /// @brief Retrieves the pointer to a string containing path. - /// @return Pointer to the string containing path. - // ============================================================================ - const wchar_t* TSmartPath::ToString() const - { - return m_strPath.c_str(); - } - - // ============================================================================ - /// TSmartPath::ToString - /// @date 2010/10/12 - /// - /// @brief Retrieves the string containing path. - /// @return String containing path. - // ============================================================================ - TString TSmartPath::ToWString() const - { - return m_strPath; - } - - // ============================================================================ - /// TSmartPath::Compare - /// @date 2009/11/29 - /// - /// @brief Compares paths. - /// @param[in] rPath - path to compare to. - /// @return Result of the comparison. - // ============================================================================ - int TSmartPath::Compare(const TSmartPath& rPath, bool bCaseSensitive) const - { - if (bCaseSensitive) - return m_strPath.Compare(rPath.m_strPath); - else - return m_strPath.CompareNoCase(rPath.m_strPath); - } - - // ============================================================================ - /// TSmartPath::SplitPath - /// @date 2011/04/05 - /// - /// @brief Splits path to components. - /// @param[in] vComponents - receives the split path. - // ============================================================================ - void TSmartPath::SplitPath(TPathContainer& vComponents) const - { - vComponents.Clear(); - - if (IsNetworkPath()) - { - // server name first - vComponents.Add(GetServerName()); - - // now the split directories - TPathContainer vDirSplit; - TSmartPath spDir = GetFileDir(); - spDir.SplitPath(vDirSplit); - - vComponents.Append(vDirSplit); - - // and file name last - vComponents.Add(GetFileName()); - } - else - { - TStringArray vStrings; - m_strPath.Split(_T("\\/"), vStrings); - - for (size_t stIndex = 0; stIndex < vStrings.GetCount(); ++stIndex) - { - const TString& strComponent = vStrings.GetAt(stIndex); - if (!strComponent.IsEmpty()) - vComponents.Add(PathFromWString(strComponent)); - } - } - } - - // ============================================================================ - /// TSmartPath::IsChildOf - /// @date 2009/11/29 - /// - /// @brief Checks if this path starts with the path specified as parameter. - /// @param[in] rPath - path to check this one against. - /// @return True if this path starts with the provided one, false otherwise. - // ============================================================================ - bool TSmartPath::IsChildOf(const TSmartPath& rPath, bool bCaseSensitive) const - { - if (bCaseSensitive) - return m_strPath.StartsWith(rPath.m_strPath.c_str()); - else - return m_strPath.StartsWithNoCase(rPath.m_strPath.c_str()); - } - - // ============================================================================ - /// TSmartPath::MakeRelativePath - /// @date 2010/10/12 - /// - /// @brief Converts this path to be relative to the reference, base path. - /// @param[in] rReferenceBasePath - Path which will be base path to this relative path. - /// @param[in] bCaseSensitive - Compare path with case sensitivity on/off. - /// @return True if conversion to relative path succeeded, false otherwise. - // ============================================================================ - bool TSmartPath::MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive) - { - bool bStartsWith = false; - if (bCaseSensitive) - bStartsWith = m_strPath.StartsWith(rReferenceBasePath.m_strPath.c_str()); - else - bStartsWith = m_strPath.StartsWithNoCase(rReferenceBasePath.m_strPath.c_str()); - - if (bStartsWith) - { - m_strPath.Delete(0, rReferenceBasePath.m_strPath.GetLength()); - return true; - } - else - return false; - } - - bool TSmartPath::MakeAbsolutePath(const TSmartPath& rReferenceBasePath) - { - if (!IsRelativePath()) - return false; - - bool bHasSeparator = rReferenceBasePath.EndsWithSeparator(); - if (!bHasSeparator) - PrependSeparatorIfDoesNotExist(); - else - StripSeparatorAtFront(); - - m_strPath = rReferenceBasePath.ToString() + m_strPath; - - return true; - } - - // ============================================================================ - /// TSmartPath::AppendIfNotExists - /// @date 2009/11/29 - /// - /// @brief Appends a specified suffix if not present. - /// @param[in] pszPostfix - string to check against. - // ============================================================================ - void TSmartPath::AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive) - { - BOOST_ASSERT(pszPostfix); - if (!pszPostfix) - return; - - bool bEndsWith = false; - if (bCaseSensitive) - bEndsWith = m_strPath.EndsWith(pszPostfix); - else - bEndsWith = m_strPath.EndsWithNoCase(pszPostfix); - - if (!bEndsWith) - m_strPath += pszPostfix; - } - - // ============================================================================ - /// TSmartPath::CutIfExists - /// @date 2010/10/07 - /// - /// @brief Cuts a specified suffix if present. - /// @param[in] pszPostfix - string to check against. - // ============================================================================ - void TSmartPath::CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive) - { - BOOST_ASSERT(pszPostfix); - if (!pszPostfix) - return; - - bool bEndsWith = false; - if (bCaseSensitive) - bEndsWith = m_strPath.EndsWith(pszPostfix); - else - bEndsWith = m_strPath.EndsWithNoCase(pszPostfix); - - if (bEndsWith) - m_strPath.Delete(m_strPath.GetLength() - _tcslen(pszPostfix), m_strPath.GetLength() - _tcslen(pszPostfix)); - } - - // ============================================================================ - /// TSmartPath::IsNetworkPath - /// @date 2010/10/17 - /// - /// @brief Checks if the path is network one (\\server_name...) - /// @return True if it is, false otherwise. - // ============================================================================ - bool TSmartPath::IsNetworkPath() const - { - return (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1))); // "\\server_name" - } - - // ============================================================================ - /// TSmartPath::IsDrive - /// @date 2011/04/05 - /// - /// @brief Checks if this path contains only drive specification (i.e. c:) - /// @return True if it is, false otherwise. - // ============================================================================ - bool TSmartPath::IsDrive() const - { - return (m_strPath.GetLength() == 2 && m_strPath.GetAt(1) == _T(':')); - } - - bool TSmartPath::IsDriveWithRootDir() const - { - return (m_strPath.GetLength() == 3 && m_strPath.GetAt(1) == _T(':') && m_strPath.GetAt(2) == _T('\\')); - } - - // ============================================================================ - /// TSmartPath::HasDrive - /// @date 2010/10/16 - /// - /// @brief Checks if path has a drive component. - /// @return True if it has, false otherwise. - // ============================================================================ - bool TSmartPath::HasDrive() const - { - return (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')); - } - - // ============================================================================ - /// TSmartPath::GetDrive - /// @date 2010/10/16 - /// - /// @brief Retrieves drive from path. - /// @return Path with drive, empty if drive does not exist. - // ============================================================================ - TSmartPath TSmartPath::GetDrive() const - { - if (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) - { - if (m_strPath.GetLength() == 2) - return *this; - else - return PathFromWString(m_strPath.Left(2)); // c: for c:\windows\test.cpp - } - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::GetDriveLetter - /// @date 2011/07/17 - /// - /// @brief Retrieves drive letter from path. - /// @return Drive letter or zero in case path does not have drive. - // ============================================================================ - wchar_t TSmartPath::GetDriveLetter() const - { - if (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) - { - wchar_t wchDrive = m_strPath.GetAt(0); - if (wchDrive >= L'a' && wchDrive <= L'z') - wchDrive = L'A' + wchDrive - L'a'; - return wchDrive; - } - - return L'\0'; - } - - TSmartPath TSmartPath::GetDriveLetterAsPath() const - { - if(m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) - return PathFromWString(m_strPath.Left(1)); // c for c:\windows\test.cpp - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::IsServerName - /// @date 2011/04/05 - /// - /// @brief Checks if this path contains only the server specification (i.e. \\server - witn no ending backslash) - /// @return True is this path contains only server specification. - // ============================================================================ - bool TSmartPath::IsServerName() const - { - return (m_strPath.GetLength() > 2 && // must have at least 3 characters... - IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && // ... the first two of which are separators... - std::isalnum(m_strPath.GetAt(2)) && // ... followed by at least one alphanumeric character... - m_strPath.FindFirstOf(_T("\\/"), 3) == TString::npos); // ... with no additional separators (so \\abc is true, \\abc\ is not). - } - - // ============================================================================ - /// TSmartPath::HasServerName - /// @date 2010/10/17 - /// - /// @brief - /// @return - // ============================================================================ - bool TSmartPath::HasServerName() const - { - return (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && std::isalnum(m_strPath.GetAt(2))); - } - - // ============================================================================ - /// TSmartPath::GetServerName - /// @date 2010/10/17 - /// - /// @brief Retrieves server name from path (if network path). - /// @return Path containing server name (with prepended \\) - // ============================================================================ - TSmartPath TSmartPath::GetServerName() const - { - TString wstrPath; - if (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && std::isalnum(m_strPath.GetAt(2))) - { - size_t stEndPos = m_strPath.FindFirstOf(_T("\\/"), 2); - if (stEndPos == TString::npos) - wstrPath = m_strPath; - else - wstrPath = m_strPath.Left(stEndPos); - return PathFromWString(wstrPath); - } - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::HasFileRoot - /// @date 2010/10/17 - /// - /// @brief Checks if this path has a file root part. - /// @return True if it has, false otherwise. - // ============================================================================ - bool TSmartPath::HasFileRoot() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/")); - return (stIndex != TString::npos); - } - - // ============================================================================ - /// TSmartPath::GetFileRoot - /// @date 2010/10/17 - /// - /// @brief Retrieves the root of the file. - /// @return File root as path, empty path if does not exist. - // ============================================================================ - TSmartPath TSmartPath::GetFileRoot() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/")); - if (stIndex != TString::npos) - return PathFromWString(m_strPath.Left(stIndex + 1)); - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::HasFileDir - /// @date 2010/10/16 - /// - /// @brief Checks if path contains directory specification. - /// @return True if it contains one, false otherwise. - // ============================================================================ - bool TSmartPath::HasFileDir() const - { - size_t stStart = 0; - if (IsNetworkPath()) - stStart = m_strPath.FindFirstOf(_T("/\\"), 2); - else - stStart = m_strPath.FindFirstOf(_T("/\\")); - - size_t stEnd = m_strPath.FindLastOf(_T("/\\")); - return (stStart != TString::npos && stEnd >= stStart); - } - - // ============================================================================ - /// TSmartPath::GetFileDir - /// @date 2010/10/16 - /// - /// @brief Retrieves the directory specification from path. - /// @return Directory specification, empty path if not found. - // ============================================================================ - TSmartPath TSmartPath::GetFileDir() const - { - size_t stStart = 0; - if (IsNetworkPath()) - stStart = m_strPath.FindFirstOf(_T("/\\"), 2); - else if (HasDrive()) - stStart = m_strPath.FindFirstOf(_T("/\\")); - else - stStart = 0; - - size_t stEnd = m_strPath.FindLastOf(_T("/\\")); - if (stStart != TString::npos && stEnd >= stStart) - return PathFromWString(m_strPath.MidRange(stStart, stEnd + 1)); - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::HasFileTitle - /// @date 2010/10/16 - /// - /// @brief Checks if the path has file title part. - /// @return True if it has one, false otherwise. - // ============================================================================ - bool TSmartPath::HasFileTitle() const - { - size_t stStart = m_strPath.FindLastOf(_T("/\\")); - size_t stEnd = m_strPath.FindLastOf(_T(".")); - if ((stStart == TString::npos && stEnd == TString::npos)) - return !IsEmpty(); - if (stStart == TString::npos) // if does not exist, start from beginning - stStart = 0; - if (stEnd == TString::npos || stEnd < stStart) // if does not exist or we have ".\\", use up to the end - stEnd = m_strPath.GetLength(); - - return stEnd > stStart + 1; - } - - // ============================================================================ - /// TSmartPath::GetFileTitle - /// @date 2010/10/16 - /// - /// @brief Retrieves file title from path. - /// @return File title. Empty if does not exist. - // ============================================================================ - TSmartPath TSmartPath::GetFileTitle() const - { - size_t stStart = m_strPath.FindLastOf(_T("/\\")); - size_t stEnd = m_strPath.FindLastOf(_T(".")); - if ((stStart == TString::npos && stEnd == TString::npos)) - return *this; - if (stStart == TString::npos) // if does not exist, start from beginning - stStart = 0; - else - ++stStart; - if (stEnd == TString::npos || stEnd < stStart) // if does not exist or we have ".\\", use up to the end - stEnd = m_strPath.GetLength(); - - return PathFromWString(m_strPath.MidRange(stStart, stEnd)); - } - - // ============================================================================ - /// TSmartPath::HasExtension - /// @date 2010/10/16 - /// - /// @brief Checks if this path has a file extension. - /// @return True if it has, false otherwise. - // ============================================================================ - bool TSmartPath::HasExtension() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/.")); - - return stIndex != TString::npos && (m_strPath.GetAt(stIndex) == _T('.')); - } - - // ============================================================================ - /// TSmartPath::GetExtension - /// @date 2010/10/16 - /// - /// @brief Retrieves file extension from this path. - /// @return Extension part or empty if does not exist. - // ============================================================================ - TSmartPath TSmartPath::GetExtension() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/.")); - - if (stIndex != TString::npos && m_strPath.GetAt(stIndex) == _T('.')) - return PathFromWString(m_strPath.MidRange(stIndex, m_strPath.GetLength())); // ".txt" for "c:\windows\test.txt" - - return TSmartPath(); - } - - // ============================================================================ - /// TSmartPath::HasFileName - /// @date 2010/10/16 - /// - /// @brief Checks if this path contains filename part. - /// @return True if filename exists, false otherwise. - // ============================================================================ - bool TSmartPath::HasFileName() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/")); - if (stIndex == TString::npos) // no path separator? - return true; - else - return (stIndex != TString::npos && stIndex != m_strPath.GetLength() - 1); - } - - // ============================================================================ - /// TSmartPath::GetFileName - /// @date 2010/10/16 - /// - /// @brief Retrieves filename part of this path. - /// @return Filename, or empty if does not exist. - // ============================================================================ - TSmartPath TSmartPath::GetFileName() const - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/")); - if (stIndex != TString::npos) - return PathFromWString(m_strPath.MidRange(stIndex + 1, m_strPath.GetLength())); // "test.txt" for "c:\windows\test.txt" - else - return *this; - } - - // ============================================================================ - /// TSmartPath::DeleteFileName - /// @date 2010/10/17 - /// - /// @brief Deletes the filename part of this path if exists. - // ============================================================================ - void TSmartPath::DeleteFileName() - { - size_t stIndex = m_strPath.FindLastOf(_T("\\/")); - if (stIndex != TString::npos) - m_strPath.Delete(stIndex + 1, m_strPath.GetLength() - stIndex - 1); // "test.txt" for "c:\windows\test.txt" - else - { - // no path separator inside - everything in this path is a filename - Clear(); - } - } - - TSmartPath TSmartPath::GetParent() const - { - if (IsServerName() || IsDrive()) - return TSmartPath(); - - TSmartPath pathResult(*this); - - if (pathResult.EndsWithSeparator()) - { - pathResult.StripSeparatorAtEnd(); - if (pathResult.IsDrive() || pathResult.IsServerName()) - return pathResult; - } - - pathResult.DeleteFileName(); - - return pathResult; - } - - // ============================================================================ - /// TSmartPath::EndsWithSeparator - /// @date 2010/10/16 - /// - /// @brief Checks if path end with a path separator (/ or \) - /// @return True if path ends with separator, false otherwise. - // ============================================================================ - bool TSmartPath::EndsWithSeparator() const - { - size_t stThisSize = m_strPath.GetLength(); - if (stThisSize > 0) - { - wchar_t wchLastChar = m_strPath.GetAt(stThisSize - 1); - return (wchLastChar == _T('\\') || wchLastChar == _T('/')); - } - - return false; - } - - // ============================================================================ - /// TSmartPath::AppendSeparatorIfDoesNotExist - /// @date 2010/10/16 - /// - /// @brief Appends separator to this path if does not exist already. - // ============================================================================ - void TSmartPath::AppendSeparatorIfDoesNotExist() - { - if (!EndsWithSeparator()) - m_strPath += _T("\\"); - } - - // ============================================================================ - /// TSmartPath::StripSeparatorAtEnd - /// @date 2010/10/17 - /// - /// @brief Strips separator at the end of path if exists. - // ============================================================================ - void TSmartPath::StripSeparatorAtEnd() - { - if (EndsWithSeparator()) - m_strPath.Delete(m_strPath.GetLength() - 1, 1); - } - - // ============================================================================ - /// TSmartPath::StartsWithSeparator - /// @date 2010/10/16 - /// - /// @brief Checks if path starts with a separator. - /// @return True if path starts with separator, false otherwise. - // ============================================================================ - bool TSmartPath::StartsWithSeparator() const - { - wchar_t wchLastChar = 0; - if (m_strPath.GetLength() > 0) - wchLastChar = m_strPath.GetAt(0); - - return (wchLastChar == _T('\\') || wchLastChar == _T('/')); - } - - // ============================================================================ - /// TSmartPath::PrependSeparatorIfDoesNotExist - /// @date 2010/10/17 - /// - /// @brief Prepends a separator to this path if not exist already. - // ============================================================================ - void TSmartPath::PrependSeparatorIfDoesNotExist() - { - if (!StartsWithSeparator()) - m_strPath = _T("\\") + m_strPath; - } - - // ============================================================================ - /// TSmartPath::StripSeparatorAtFront - /// @date 2010/10/17 - /// - /// @brief Strips separator at the front of this path (if exists). - // ============================================================================ - void TSmartPath::StripSeparatorAtFront() - { - if (StartsWithSeparator()) - m_strPath.Delete(0, 1); - } - - void TSmartPath::StripPath(const wchar_t* pszToStrip) - { - m_strPath.Replace(pszToStrip, L""); - } - - // ============================================================================ - /// TSmartPath::IsEmpty - /// @date 2010/10/07 - /// - /// @brief Prepares the path to be written to. - // ============================================================================ - bool TSmartPath::IsEmpty() const - { - return m_strPath.IsEmpty(); - } - - // ============================================================================ - /// TSmartPath::GetLength - /// @date 2011/04/05 - /// - /// @brief Retrieves path length in characters. - /// @return Path length. - // ============================================================================ - size_t TSmartPath::GetLength() const - { - return m_strPath.GetLength(); - } - - // ============================================================================ - /// TSmartPath::IsSeparator - /// @date 2010/10/17 - /// - /// @brief Checks if the character is a separator. - /// @param[in] wchSeparator - Character to be checked. - /// @return True if it is a separator, false otherwise. - // ============================================================================ - bool TSmartPath::IsSeparator(wchar_t wchSeparator) - { - return (wchSeparator == _T('\\') || wchSeparator == _T('/')); - } - - bool TSmartPath::IsRelativePath() const - { - return !HasDrive() && !HasServerName(); - } - - bool TSmartPath::StartsWith(const TSmartPath& rPath, bool bCaseSensitive) const - { - if(bCaseSensitive) - return m_strPath.StartsWith(rPath.m_strPath.c_str()); - - return m_strPath.StartsWithNoCase(rPath.m_strPath.c_str()); - } - - // ============================================================================ - /// PathFromString - /// @date 2010/10/12 - /// - /// @brief Creates a path object from string. - /// @param[in] pszPath - string containing path. - /// @return New path object. - // ============================================================================ - TSmartPath PathFromString(const wchar_t* pszPath) - { - if (!pszPath) - throw TCoreException(eErr_InvalidArgument, L"pszPath", LOCATION); - - TSmartPath spPath; - spPath.FromString(pszPath); - return spPath; - } - - // ============================================================================ - /// PathFromWString - /// @date 2010/10/12 - /// - /// @brief Creates a path object from string. - /// @param[in] pszPath - string containing path. - /// @return New path object. - // ============================================================================ - TSmartPath PathFromWString(const TString& strPath) - { - TSmartPath spPath; - spPath.FromString(strPath); - return spPath; - } -} +/*************************************************************************** +* Copyright (C) 2001-2008 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#include "stdafx.h" +#include +#include +#include "TPath.h" +#pragma warning(push) +#pragma warning(disable: 4996) +#include +#pragma warning(pop) +#include +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TPathContainer.h" +#include "TStringArray.h" + +namespace chcore +{ +#define DEFAULT_PATH_SEPARATOR _T("\\") + + // ============================================================================ + /// TSmartPath::TSmartPath + /// @date 2009/11/29 + /// + /// @brief Constructs an empty path. + // ============================================================================ + TSmartPath::TSmartPath() : + m_strPath() + { + } + + // ============================================================================ + /// TSmartPath::TSmartPath + /// @date 2009/11/29 + /// + /// @brief Constructs path object from another path object. + /// @param[in] spPath - reference to another path object. + // ============================================================================ + TSmartPath::TSmartPath(const TSmartPath& spPath) : + m_strPath(spPath.m_strPath) + { + } + + // ============================================================================ + /// TSmartPath::~TSmartPath + /// @date 2009/11/29 + /// + /// @brief + /// @return + // ============================================================================ + TSmartPath::~TSmartPath() + { + Clear(); + } + + // ============================================================================ + /// TSmartPath::Clear + /// @date 2009/11/29 + /// + /// @brief Clears this object. + // ============================================================================ + void TSmartPath::Clear() throw() + { + m_strPath.Clear(); + } + + + TSmartPath TSmartPath::AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists) const + { + TSmartPath pathNew(*this); + pathNew.Append(pathToAppend, bEnsurePathSeparatorExists); + + return pathNew; + } + + TSmartPath& TSmartPath::Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists) + { + // if there is no path inside rPath, then there is no point in doing anything + if (!pathToAppend.m_strPath.IsEmpty()) + { + // if this path is empty, then optimize by just assigning the input path to this one + if (m_strPath.IsEmpty()) + *this = pathToAppend; + else + { + if (bEnsurePathSeparatorExists) + { + // detect separators + bool bThisEndsWithSeparator = EndsWithSeparator(); + bool bInStartsWithSeparator = pathToAppend.StartsWithSeparator(); + + if (!bThisEndsWithSeparator && !bInStartsWithSeparator) + m_strPath += _T("\\") + pathToAppend.m_strPath; + else if (bThisEndsWithSeparator ^ bInStartsWithSeparator) + m_strPath += pathToAppend.m_strPath; + else + { + m_strPath.Delete(m_strPath.GetLength() - 1, 1); + m_strPath += pathToAppend.m_strPath; + } + } + else + m_strPath += pathToAppend.m_strPath; + } + } + + return *this; + } + + // ============================================================================ + /// TSmartPath::operator= + /// @date 2009/11/29 + /// + /// @brief Assigns a path from other path object. + /// @param[in] spPath - path object from which we want to get path. + /// @return Reference to this object. + // ============================================================================ + TSmartPath& TSmartPath::operator=(const TSmartPath& spPath) + { + if (this != &spPath) + { + Clear(); + m_strPath = spPath.m_strPath; + } + + return *this; + } + + // ============================================================================ + /// TSmartPath::operator== + /// @date 2009/11/29 + /// + /// @brief Compares paths (case sensitive). + /// @param[in] rPath - path to compare this object to. + /// @return True if equal, false otherwise. + // ============================================================================ + bool TSmartPath::operator==(const TSmartPath& rPath) const + { + return Compare(rPath) == 0; + } + + + bool TSmartPath::operator!=(const TSmartPath& rPath) const + { + return Compare(rPath) != 0; + } + + // ============================================================================ + /// TSmartPath::operator< + /// @date 2009/11/29 + /// + /// @brief Compares paths (case sensitive). + /// @param[in] rPath - input path to compare. + /// @return True if this object is less than rPath, false otherwise. + // ============================================================================ + bool TSmartPath::operator<(const TSmartPath& rPath) const + { + return Compare(rPath) < 0; + } + + // ============================================================================ + /// TSmartPath::operator> + /// @date 2009/11/29 + /// + /// @brief Compares paths (case sensitive). + /// @param[in] rPath - input path to compare. + /// @return True if this object is less than rPath, false otherwise. + // ============================================================================ + bool TSmartPath::operator>(const TSmartPath& rPath) const + { + return Compare(rPath) > 0; + } + + // ============================================================================ + /// TSmartPath::operator+ + /// @date 2009/11/29 + /// + /// @brief Concatenates two paths, returns the result. + /// @param[in] rPath - path to concatenate. + /// @return New path object with the results of concatenation. + // ============================================================================ + TSmartPath TSmartPath::operator+(const TSmartPath& rPath) const + { + return AppendCopy(rPath, true); + } + + // ============================================================================ + /// TSmartPath::operator+= + /// @date 2009/11/29 + /// + /// @brief Concatenates provided path to our own. + /// @param[in] rPath - path to concatenate. + /// @return Reference to this object. + // ============================================================================ + TSmartPath& TSmartPath::operator+=(const TSmartPath& rPath) + { + return Append(rPath, true); + } + + // ============================================================================ + /// TSmartPath::FromString + /// @date 2010/10/12 + /// + /// @brief Initializes this path object with path contained in string. + /// @param[in] pszPath - string containing path. + // ============================================================================ + void TSmartPath::FromString(const wchar_t* pszPath) + { + if (!pszPath) + throw TCoreException(eErr_InvalidArgument, L"pszPath", LOCATION); + + m_strPath = pszPath; + } + + // ============================================================================ + /// TSmartPath::FromString + /// @date 2010/10/12 + /// + /// @brief Initializes this path object with path contained in string. + /// @param[in] strPath - string containing path. + // ============================================================================ + void TSmartPath::FromString(const TString& strPath) + { + m_strPath = strPath; + } + + // ============================================================================ + /// TSmartPath::ToString + /// @date 2010/10/12 + /// + /// @brief Retrieves the pointer to a string containing path. + /// @return Pointer to the string containing path. + // ============================================================================ + const wchar_t* TSmartPath::ToString() const + { + return m_strPath.c_str(); + } + + // ============================================================================ + /// TSmartPath::ToString + /// @date 2010/10/12 + /// + /// @brief Retrieves the string containing path. + /// @return String containing path. + // ============================================================================ + TString TSmartPath::ToWString() const + { + return m_strPath; + } + + // ============================================================================ + /// TSmartPath::Compare + /// @date 2009/11/29 + /// + /// @brief Compares paths. + /// @param[in] rPath - path to compare to. + /// @return Result of the comparison. + // ============================================================================ + int TSmartPath::Compare(const TSmartPath& rPath, bool bCaseSensitive) const + { + if (bCaseSensitive) + return m_strPath.Compare(rPath.m_strPath); + else + return m_strPath.CompareNoCase(rPath.m_strPath); + } + + // ============================================================================ + /// TSmartPath::SplitPath + /// @date 2011/04/05 + /// + /// @brief Splits path to components. + /// @param[in] vComponents - receives the split path. + // ============================================================================ + void TSmartPath::SplitPath(TPathContainer& vComponents) const + { + vComponents.Clear(); + + if (IsNetworkPath()) + { + // server name first + vComponents.Add(GetServerName()); + + // now the split directories + TPathContainer vDirSplit; + TSmartPath spDir = GetFileDir(); + spDir.SplitPath(vDirSplit); + + vComponents.Append(vDirSplit); + + // and file name last + vComponents.Add(GetFileName()); + } + else + { + TStringArray vStrings; + m_strPath.Split(_T("\\/"), vStrings); + + for (size_t stIndex = 0; stIndex < vStrings.GetCount(); ++stIndex) + { + const TString& strComponent = vStrings.GetAt(stIndex); + if (!strComponent.IsEmpty()) + vComponents.Add(PathFromWString(strComponent)); + } + } + } + + // ============================================================================ + /// TSmartPath::IsChildOf + /// @date 2009/11/29 + /// + /// @brief Checks if this path starts with the path specified as parameter. + /// @param[in] rPath - path to check this one against. + /// @return True if this path starts with the provided one, false otherwise. + // ============================================================================ + bool TSmartPath::IsChildOf(const TSmartPath& rPath, bool bCaseSensitive) const + { + if (bCaseSensitive) + return m_strPath.StartsWith(rPath.m_strPath.c_str()); + else + return m_strPath.StartsWithNoCase(rPath.m_strPath.c_str()); + } + + // ============================================================================ + /// TSmartPath::MakeRelativePath + /// @date 2010/10/12 + /// + /// @brief Converts this path to be relative to the reference, base path. + /// @param[in] rReferenceBasePath - Path which will be base path to this relative path. + /// @param[in] bCaseSensitive - Compare path with case sensitivity on/off. + /// @return True if conversion to relative path succeeded, false otherwise. + // ============================================================================ + bool TSmartPath::MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive) + { + bool bStartsWith = false; + if (bCaseSensitive) + bStartsWith = m_strPath.StartsWith(rReferenceBasePath.m_strPath.c_str()); + else + bStartsWith = m_strPath.StartsWithNoCase(rReferenceBasePath.m_strPath.c_str()); + + if (bStartsWith) + { + m_strPath.Delete(0, rReferenceBasePath.m_strPath.GetLength()); + return true; + } + else + return false; + } + + bool TSmartPath::MakeAbsolutePath(const TSmartPath& rReferenceBasePath) + { + if (!IsRelativePath()) + return false; + + bool bHasSeparator = rReferenceBasePath.EndsWithSeparator(); + if (!bHasSeparator) + PrependSeparatorIfDoesNotExist(); + else + StripSeparatorAtFront(); + + m_strPath = rReferenceBasePath.ToString() + m_strPath; + + return true; + } + + // ============================================================================ + /// TSmartPath::AppendIfNotExists + /// @date 2009/11/29 + /// + /// @brief Appends a specified suffix if not present. + /// @param[in] pszPostfix - string to check against. + // ============================================================================ + void TSmartPath::AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive) + { + BOOST_ASSERT(pszPostfix); + if (!pszPostfix) + return; + + bool bEndsWith = false; + if (bCaseSensitive) + bEndsWith = m_strPath.EndsWith(pszPostfix); + else + bEndsWith = m_strPath.EndsWithNoCase(pszPostfix); + + if (!bEndsWith) + m_strPath += pszPostfix; + } + + // ============================================================================ + /// TSmartPath::CutIfExists + /// @date 2010/10/07 + /// + /// @brief Cuts a specified suffix if present. + /// @param[in] pszPostfix - string to check against. + // ============================================================================ + void TSmartPath::CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive) + { + BOOST_ASSERT(pszPostfix); + if (!pszPostfix) + return; + + bool bEndsWith = false; + if (bCaseSensitive) + bEndsWith = m_strPath.EndsWith(pszPostfix); + else + bEndsWith = m_strPath.EndsWithNoCase(pszPostfix); + + if (bEndsWith) + m_strPath.Delete(m_strPath.GetLength() - _tcslen(pszPostfix), m_strPath.GetLength() - _tcslen(pszPostfix)); + } + + // ============================================================================ + /// TSmartPath::IsNetworkPath + /// @date 2010/10/17 + /// + /// @brief Checks if the path is network one (\\server_name...) + /// @return True if it is, false otherwise. + // ============================================================================ + bool TSmartPath::IsNetworkPath() const + { + return (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1))); // "\\server_name" + } + + // ============================================================================ + /// TSmartPath::IsDrive + /// @date 2011/04/05 + /// + /// @brief Checks if this path contains only drive specification (i.e. c:) + /// @return True if it is, false otherwise. + // ============================================================================ + bool TSmartPath::IsDrive() const + { + return (m_strPath.GetLength() == 2 && m_strPath.GetAt(1) == _T(':')); + } + + bool TSmartPath::IsDriveWithRootDir() const + { + return (m_strPath.GetLength() == 3 && m_strPath.GetAt(1) == _T(':') && m_strPath.GetAt(2) == _T('\\')); + } + + // ============================================================================ + /// TSmartPath::HasDrive + /// @date 2010/10/16 + /// + /// @brief Checks if path has a drive component. + /// @return True if it has, false otherwise. + // ============================================================================ + bool TSmartPath::HasDrive() const + { + return (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')); + } + + // ============================================================================ + /// TSmartPath::GetDrive + /// @date 2010/10/16 + /// + /// @brief Retrieves drive from path. + /// @return Path with drive, empty if drive does not exist. + // ============================================================================ + TSmartPath TSmartPath::GetDrive() const + { + if (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) + { + if (m_strPath.GetLength() == 2) + return *this; + else + return PathFromWString(m_strPath.Left(2)); // c: for c:\windows\test.cpp + } + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::GetDriveLetter + /// @date 2011/07/17 + /// + /// @brief Retrieves drive letter from path. + /// @return Drive letter or zero in case path does not have drive. + // ============================================================================ + wchar_t TSmartPath::GetDriveLetter() const + { + if (m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) + { + wchar_t wchDrive = m_strPath.GetAt(0); + if (wchDrive >= L'a' && wchDrive <= L'z') + wchDrive = L'A' + wchDrive - L'a'; + return wchDrive; + } + + return L'\0'; + } + + TSmartPath TSmartPath::GetDriveLetterAsPath() const + { + if(m_strPath.GetLength() >= 2 && m_strPath.GetAt(1) == _T(':')) + return PathFromWString(m_strPath.Left(1)); // c for c:\windows\test.cpp + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::IsServerName + /// @date 2011/04/05 + /// + /// @brief Checks if this path contains only the server specification (i.e. \\server - witn no ending backslash) + /// @return True is this path contains only server specification. + // ============================================================================ + bool TSmartPath::IsServerName() const + { + return (m_strPath.GetLength() > 2 && // must have at least 3 characters... + IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && // ... the first two of which are separators... + std::isalnum(m_strPath.GetAt(2)) && // ... followed by at least one alphanumeric character... + m_strPath.FindFirstOf(_T("\\/"), 3) == TString::npos); // ... with no additional separators (so \\abc is true, \\abc\ is not). + } + + // ============================================================================ + /// TSmartPath::HasServerName + /// @date 2010/10/17 + /// + /// @brief + /// @return + // ============================================================================ + bool TSmartPath::HasServerName() const + { + return (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && std::isalnum(m_strPath.GetAt(2))); + } + + // ============================================================================ + /// TSmartPath::GetServerName + /// @date 2010/10/17 + /// + /// @brief Retrieves server name from path (if network path). + /// @return Path containing server name (with prepended \\) + // ============================================================================ + TSmartPath TSmartPath::GetServerName() const + { + TString wstrPath; + if (m_strPath.GetLength() > 2 && IsSeparator(m_strPath.GetAt(0)) && IsSeparator(m_strPath.GetAt(1)) && std::isalnum(m_strPath.GetAt(2))) + { + size_t stEndPos = m_strPath.FindFirstOf(_T("\\/"), 2); + if (stEndPos == TString::npos) + wstrPath = m_strPath; + else + wstrPath = m_strPath.Left(stEndPos); + return PathFromWString(wstrPath); + } + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::HasFileRoot + /// @date 2010/10/17 + /// + /// @brief Checks if this path has a file root part. + /// @return True if it has, false otherwise. + // ============================================================================ + bool TSmartPath::HasFileRoot() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/")); + return (stIndex != TString::npos); + } + + // ============================================================================ + /// TSmartPath::GetFileRoot + /// @date 2010/10/17 + /// + /// @brief Retrieves the root of the file. + /// @return File root as path, empty path if does not exist. + // ============================================================================ + TSmartPath TSmartPath::GetFileRoot() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/")); + if (stIndex != TString::npos) + return PathFromWString(m_strPath.Left(stIndex + 1)); + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::HasFileDir + /// @date 2010/10/16 + /// + /// @brief Checks if path contains directory specification. + /// @return True if it contains one, false otherwise. + // ============================================================================ + bool TSmartPath::HasFileDir() const + { + size_t stStart = 0; + if (IsNetworkPath()) + stStart = m_strPath.FindFirstOf(_T("/\\"), 2); + else + stStart = m_strPath.FindFirstOf(_T("/\\")); + + size_t stEnd = m_strPath.FindLastOf(_T("/\\")); + return (stStart != TString::npos && stEnd >= stStart); + } + + // ============================================================================ + /// TSmartPath::GetFileDir + /// @date 2010/10/16 + /// + /// @brief Retrieves the directory specification from path. + /// @return Directory specification, empty path if not found. + // ============================================================================ + TSmartPath TSmartPath::GetFileDir() const + { + size_t stStart = 0; + if (IsNetworkPath()) + stStart = m_strPath.FindFirstOf(_T("/\\"), 2); + else if (HasDrive()) + stStart = m_strPath.FindFirstOf(_T("/\\")); + else + stStart = 0; + + size_t stEnd = m_strPath.FindLastOf(_T("/\\")); + if (stStart != TString::npos && stEnd >= stStart) + return PathFromWString(m_strPath.MidRange(stStart, stEnd + 1)); + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::HasFileTitle + /// @date 2010/10/16 + /// + /// @brief Checks if the path has file title part. + /// @return True if it has one, false otherwise. + // ============================================================================ + bool TSmartPath::HasFileTitle() const + { + size_t stStart = m_strPath.FindLastOf(_T("/\\")); + size_t stEnd = m_strPath.FindLastOf(_T(".")); + if ((stStart == TString::npos && stEnd == TString::npos)) + return !IsEmpty(); + if (stStart == TString::npos) // if does not exist, start from beginning + stStart = 0; + if (stEnd == TString::npos || stEnd < stStart) // if does not exist or we have ".\\", use up to the end + stEnd = m_strPath.GetLength(); + + return stEnd > stStart + 1; + } + + // ============================================================================ + /// TSmartPath::GetFileTitle + /// @date 2010/10/16 + /// + /// @brief Retrieves file title from path. + /// @return File title. Empty if does not exist. + // ============================================================================ + TSmartPath TSmartPath::GetFileTitle() const + { + size_t stStart = m_strPath.FindLastOf(_T("/\\")); + size_t stEnd = m_strPath.FindLastOf(_T(".")); + if ((stStart == TString::npos && stEnd == TString::npos)) + return *this; + if (stStart == TString::npos) // if does not exist, start from beginning + stStart = 0; + else + ++stStart; + if (stEnd == TString::npos || stEnd < stStart) // if does not exist or we have ".\\", use up to the end + stEnd = m_strPath.GetLength(); + + return PathFromWString(m_strPath.MidRange(stStart, stEnd)); + } + + // ============================================================================ + /// TSmartPath::HasExtension + /// @date 2010/10/16 + /// + /// @brief Checks if this path has a file extension. + /// @return True if it has, false otherwise. + // ============================================================================ + bool TSmartPath::HasExtension() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/.")); + + return stIndex != TString::npos && (m_strPath.GetAt(stIndex) == _T('.')); + } + + // ============================================================================ + /// TSmartPath::GetExtension + /// @date 2010/10/16 + /// + /// @brief Retrieves file extension from this path. + /// @return Extension part or empty if does not exist. + // ============================================================================ + TSmartPath TSmartPath::GetExtension() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/.")); + + if (stIndex != TString::npos && m_strPath.GetAt(stIndex) == _T('.')) + return PathFromWString(m_strPath.MidRange(stIndex, m_strPath.GetLength())); // ".txt" for "c:\windows\test.txt" + + return TSmartPath(); + } + + // ============================================================================ + /// TSmartPath::HasFileName + /// @date 2010/10/16 + /// + /// @brief Checks if this path contains filename part. + /// @return True if filename exists, false otherwise. + // ============================================================================ + bool TSmartPath::HasFileName() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/")); + if (stIndex == TString::npos) // no path separator? + return true; + else + return (stIndex != TString::npos && stIndex != m_strPath.GetLength() - 1); + } + + // ============================================================================ + /// TSmartPath::GetFileName + /// @date 2010/10/16 + /// + /// @brief Retrieves filename part of this path. + /// @return Filename, or empty if does not exist. + // ============================================================================ + TSmartPath TSmartPath::GetFileName() const + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/")); + if (stIndex != TString::npos) + return PathFromWString(m_strPath.MidRange(stIndex + 1, m_strPath.GetLength())); // "test.txt" for "c:\windows\test.txt" + else + return *this; + } + + // ============================================================================ + /// TSmartPath::DeleteFileName + /// @date 2010/10/17 + /// + /// @brief Deletes the filename part of this path if exists. + // ============================================================================ + void TSmartPath::DeleteFileName() + { + size_t stIndex = m_strPath.FindLastOf(_T("\\/")); + if (stIndex != TString::npos) + m_strPath.Delete(stIndex + 1, m_strPath.GetLength() - stIndex - 1); // "test.txt" for "c:\windows\test.txt" + else + { + // no path separator inside - everything in this path is a filename + Clear(); + } + } + + TSmartPath TSmartPath::GetParent() const + { + if (IsServerName() || IsDrive()) + return TSmartPath(); + + TSmartPath pathResult(*this); + + if (pathResult.EndsWithSeparator()) + { + pathResult.StripSeparatorAtEnd(); + if (pathResult.IsDrive() || pathResult.IsServerName()) + return pathResult; + } + + pathResult.DeleteFileName(); + + return pathResult; + } + + // ============================================================================ + /// TSmartPath::EndsWithSeparator + /// @date 2010/10/16 + /// + /// @brief Checks if path end with a path separator (/ or \) + /// @return True if path ends with separator, false otherwise. + // ============================================================================ + bool TSmartPath::EndsWithSeparator() const + { + size_t stThisSize = m_strPath.GetLength(); + if (stThisSize > 0) + { + wchar_t wchLastChar = m_strPath.GetAt(stThisSize - 1); + return (wchLastChar == _T('\\') || wchLastChar == _T('/')); + } + + return false; + } + + // ============================================================================ + /// TSmartPath::AppendSeparatorIfDoesNotExist + /// @date 2010/10/16 + /// + /// @brief Appends separator to this path if does not exist already. + // ============================================================================ + void TSmartPath::AppendSeparatorIfDoesNotExist() + { + if (!EndsWithSeparator()) + m_strPath += _T("\\"); + } + + // ============================================================================ + /// TSmartPath::StripSeparatorAtEnd + /// @date 2010/10/17 + /// + /// @brief Strips separator at the end of path if exists. + // ============================================================================ + void TSmartPath::StripSeparatorAtEnd() + { + if (EndsWithSeparator()) + m_strPath.Delete(m_strPath.GetLength() - 1, 1); + } + + // ============================================================================ + /// TSmartPath::StartsWithSeparator + /// @date 2010/10/16 + /// + /// @brief Checks if path starts with a separator. + /// @return True if path starts with separator, false otherwise. + // ============================================================================ + bool TSmartPath::StartsWithSeparator() const + { + wchar_t wchLastChar = 0; + if (m_strPath.GetLength() > 0) + wchLastChar = m_strPath.GetAt(0); + + return (wchLastChar == _T('\\') || wchLastChar == _T('/')); + } + + // ============================================================================ + /// TSmartPath::PrependSeparatorIfDoesNotExist + /// @date 2010/10/17 + /// + /// @brief Prepends a separator to this path if not exist already. + // ============================================================================ + void TSmartPath::PrependSeparatorIfDoesNotExist() + { + if (!StartsWithSeparator()) + m_strPath = _T("\\") + m_strPath; + } + + // ============================================================================ + /// TSmartPath::StripSeparatorAtFront + /// @date 2010/10/17 + /// + /// @brief Strips separator at the front of this path (if exists). + // ============================================================================ + void TSmartPath::StripSeparatorAtFront() + { + if (StartsWithSeparator()) + m_strPath.Delete(0, 1); + } + + void TSmartPath::StripPath(const wchar_t* pszToStrip) + { + m_strPath.Replace(pszToStrip, L""); + } + + // ============================================================================ + /// TSmartPath::IsEmpty + /// @date 2010/10/07 + /// + /// @brief Prepares the path to be written to. + // ============================================================================ + bool TSmartPath::IsEmpty() const + { + return m_strPath.IsEmpty(); + } + + // ============================================================================ + /// TSmartPath::GetLength + /// @date 2011/04/05 + /// + /// @brief Retrieves path length in characters. + /// @return Path length. + // ============================================================================ + size_t TSmartPath::GetLength() const + { + return m_strPath.GetLength(); + } + + // ============================================================================ + /// TSmartPath::IsSeparator + /// @date 2010/10/17 + /// + /// @brief Checks if the character is a separator. + /// @param[in] wchSeparator - Character to be checked. + /// @return True if it is a separator, false otherwise. + // ============================================================================ + bool TSmartPath::IsSeparator(wchar_t wchSeparator) + { + return (wchSeparator == _T('\\') || wchSeparator == _T('/')); + } + + bool TSmartPath::IsRelativePath() const + { + return !HasDrive() && !HasServerName(); + } + + bool TSmartPath::StartsWith(const TSmartPath& rPath, bool bCaseSensitive) const + { + if(bCaseSensitive) + return m_strPath.StartsWith(rPath.m_strPath.c_str()); + + return m_strPath.StartsWithNoCase(rPath.m_strPath.c_str()); + } + + // ============================================================================ + /// PathFromString + /// @date 2010/10/12 + /// + /// @brief Creates a path object from string. + /// @param[in] pszPath - string containing path. + /// @return New path object. + // ============================================================================ + TSmartPath PathFromString(const wchar_t* pszPath) + { + if (!pszPath) + throw TCoreException(eErr_InvalidArgument, L"pszPath", LOCATION); + + TSmartPath spPath; + spPath.FromString(pszPath); + return spPath; + } + + // ============================================================================ + /// PathFromWString + /// @date 2010/10/12 + /// + /// @brief Creates a path object from string. + /// @param[in] pszPath - string containing path. + /// @return New path object. + // ============================================================================ + TSmartPath PathFromWString(const TString& strPath) + { + TSmartPath spPath; + spPath.FromString(strPath); + return spPath; + } +} Index: src/libchcore/TPath.h =================================================================== diff -u -rf8fcbbd1d2321cf0c8be79526c449384af654e49 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPath.h (.../TPath.h) (revision f8fcbbd1d2321cf0c8be79526c449384af654e49) +++ src/libchcore/TPath.h (.../TPath.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,140 +1,140 @@ -/*************************************************************************** -* Copyright (C) 2001-2008 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __TPATH_H__ -#define __TPATH_H__ - -#include "libchcore.h" -#include "TString.h" - -namespace chcore -{ - class TSmartPath; - class TPathContainer; - - class LIBCHCORE_API TSmartPath - { - protected: - static const bool DefaultCaseSensitivity = false; - - public: - // Construction/destruction - TSmartPath(); - TSmartPath(const TSmartPath& spPath); - - ~TSmartPath(); - - // operators - TSmartPath& operator=(const TSmartPath& spPath); - - bool operator==(const TSmartPath& rPath) const; - bool operator!=(const TSmartPath& rPath) const; - bool operator<(const TSmartPath& rPath) const; - bool operator>(const TSmartPath& rPath) const; - - TSmartPath operator+(const TSmartPath& rPath) const; - TSmartPath& operator+=(const TSmartPath& rPath); - - // from/to string conversions - void FromString(const wchar_t* pszPath); - void FromString(const TString& strPath); - - const wchar_t* ToString() const; - TString ToWString() const; - - // other operations - void Clear() throw(); - - TSmartPath AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true) const; - TSmartPath& Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true); - - void SplitPath(TPathContainer& vComponents) const; - - int Compare(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; - bool IsChildOf(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; - - bool MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive = DefaultCaseSensitivity); - bool MakeAbsolutePath(const TSmartPath& rReferenceBasePath); - - void AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); - void CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); - - bool IsNetworkPath() const; - bool IsRelativePath() const; - - bool IsDrive() const; - bool IsDriveWithRootDir() const; - bool HasDrive() const; - TSmartPath GetDrive() const; // c: for c:\windows\test.txt - wchar_t GetDriveLetter() const; // 'c' for c:\windows\test.txt, null for non-drive based paths - TSmartPath GetDriveLetterAsPath() const; // 'c' for c:\windows\test.txt, null for non-drive based paths - - bool IsServerName() const; - bool HasServerName() const; - TSmartPath GetServerName() const; - - bool HasFileRoot() const; - TSmartPath GetFileRoot() const; // "c:\windows\" for "c:\windows\test.txt" - - bool HasFileDir() const; // \windows\ for c:\windows\test.txt - TSmartPath GetFileDir() const; // \windows\ for c:\windows\test.txt - - bool HasFileTitle() const; // test for c:\windows\test.txt - TSmartPath GetFileTitle() const; // test for c:\windows\test.txt - - bool HasExtension() const; // txt for c:\windows\test.txt - TSmartPath GetExtension() const; // txt for c:\windows\test.txt - - bool HasFileName() const; // test.txt for c:\windows\test.txt - TSmartPath GetFileName() const; // test.txt for c:\windows\test.txt - void DeleteFileName(); // c:\windows\ for c:\windows\test.txt - - TSmartPath GetParent() const; - - bool EndsWithSeparator() const; - void AppendSeparatorIfDoesNotExist(); - void StripSeparatorAtEnd(); - - bool StartsWithSeparator() const; - void PrependSeparatorIfDoesNotExist(); - void StripSeparatorAtFront(); - - void StripPath(const wchar_t* pszToStrip); - - bool StartsWith(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; - - bool IsEmpty() const; - size_t GetLength() const; - - protected: - static bool IsSeparator(wchar_t wchSeparator); - - protected: - TString m_strPath; - }; - - LIBCHCORE_API TSmartPath PathFromString(const wchar_t* pszPath); - LIBCHCORE_API TSmartPath PathFromWString(const TString& strPath); - - inline std::wostream& operator<<(std::wostream& os, const TSmartPath& rPath) - { - return os << std::wstring(rPath.ToString()); - } -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2008 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __TPATH_H__ +#define __TPATH_H__ + +#include "libchcore.h" +#include "TString.h" + +namespace chcore +{ + class TSmartPath; + class TPathContainer; + + class LIBCHCORE_API TSmartPath + { + protected: + static const bool DefaultCaseSensitivity = false; + + public: + // Construction/destruction + TSmartPath(); + TSmartPath(const TSmartPath& spPath); + + ~TSmartPath(); + + // operators + TSmartPath& operator=(const TSmartPath& spPath); + + bool operator==(const TSmartPath& rPath) const; + bool operator!=(const TSmartPath& rPath) const; + bool operator<(const TSmartPath& rPath) const; + bool operator>(const TSmartPath& rPath) const; + + TSmartPath operator+(const TSmartPath& rPath) const; + TSmartPath& operator+=(const TSmartPath& rPath); + + // from/to string conversions + void FromString(const wchar_t* pszPath); + void FromString(const TString& strPath); + + const wchar_t* ToString() const; + TString ToWString() const; + + // other operations + void Clear() throw(); + + TSmartPath AppendCopy(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true) const; + TSmartPath& Append(const TSmartPath& pathToAppend, bool bEnsurePathSeparatorExists = true); + + void SplitPath(TPathContainer& vComponents) const; + + int Compare(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; + bool IsChildOf(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; + + bool MakeRelativePath(const TSmartPath& rReferenceBasePath, bool bCaseSensitive = DefaultCaseSensitivity); + bool MakeAbsolutePath(const TSmartPath& rReferenceBasePath); + + void AppendIfNotExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); + void CutIfExists(const wchar_t* pszPostfix, bool bCaseSensitive = DefaultCaseSensitivity); + + bool IsNetworkPath() const; + bool IsRelativePath() const; + + bool IsDrive() const; + bool IsDriveWithRootDir() const; + bool HasDrive() const; + TSmartPath GetDrive() const; // c: for c:\windows\test.txt + wchar_t GetDriveLetter() const; // 'c' for c:\windows\test.txt, null for non-drive based paths + TSmartPath GetDriveLetterAsPath() const; // 'c' for c:\windows\test.txt, null for non-drive based paths + + bool IsServerName() const; + bool HasServerName() const; + TSmartPath GetServerName() const; + + bool HasFileRoot() const; + TSmartPath GetFileRoot() const; // "c:\windows\" for "c:\windows\test.txt" + + bool HasFileDir() const; // \windows\ for c:\windows\test.txt + TSmartPath GetFileDir() const; // \windows\ for c:\windows\test.txt + + bool HasFileTitle() const; // test for c:\windows\test.txt + TSmartPath GetFileTitle() const; // test for c:\windows\test.txt + + bool HasExtension() const; // txt for c:\windows\test.txt + TSmartPath GetExtension() const; // txt for c:\windows\test.txt + + bool HasFileName() const; // test.txt for c:\windows\test.txt + TSmartPath GetFileName() const; // test.txt for c:\windows\test.txt + void DeleteFileName(); // c:\windows\ for c:\windows\test.txt + + TSmartPath GetParent() const; + + bool EndsWithSeparator() const; + void AppendSeparatorIfDoesNotExist(); + void StripSeparatorAtEnd(); + + bool StartsWithSeparator() const; + void PrependSeparatorIfDoesNotExist(); + void StripSeparatorAtFront(); + + void StripPath(const wchar_t* pszToStrip); + + bool StartsWith(const TSmartPath& rPath, bool bCaseSensitive = DefaultCaseSensitivity) const; + + bool IsEmpty() const; + size_t GetLength() const; + + protected: + static bool IsSeparator(wchar_t wchSeparator); + + protected: + TString m_strPath; + }; + + LIBCHCORE_API TSmartPath PathFromString(const wchar_t* pszPath); + LIBCHCORE_API TSmartPath PathFromWString(const TString& strPath); + + inline std::wostream& operator<<(std::wostream& os, const TSmartPath& rPath) + { + return os << std::wstring(rPath.ToString()); + } +} + +#endif Index: src/libchcore/TPathContainer.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPathContainer.cpp (.../TPathContainer.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TPathContainer.cpp (.../TPathContainer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,220 +1,220 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TPathContainer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TStringArray.h" - -namespace chcore -{ - // ============================================================================ - /// TPathContainer::TPathContainer - /// @date 2009/11/30 - /// - /// @brief Constructs an empty path container object. - // ============================================================================ - TPathContainer::TPathContainer() : - m_vPaths() - { - } - - // ============================================================================ - /// TPathContainer::TPathContainer - /// @date 2009/11/30 - /// - /// @brief Constructs the path container object from another path container. - /// @param[in] rSrcContainer - path container to copy paths from. - // ============================================================================ - TPathContainer::TPathContainer(const TPathContainer& rSrcContainer) : - m_vPaths(rSrcContainer.m_vPaths) - { - } - - // ============================================================================ - /// TPathContainer::~TPathContainer - /// @date 2009/11/30 - /// - /// @brief Destructs this path container object. - // ============================================================================ - TPathContainer::~TPathContainer() - { - } - - // ============================================================================ - /// TPathContainer::operator= - /// @date 2009/11/30 - /// - /// @brief Assigns another path container object to this one. - /// @param[in] rSrcContainer - container with paths to copy from. - /// @return Reference to this object. - // ============================================================================ - TPathContainer& TPathContainer::operator=(const TPathContainer& rSrcContainer) - { - if (this != &rSrcContainer) - m_vPaths = rSrcContainer.m_vPaths; - - return *this; - } - - // ============================================================================ - /// TPathContainer::Add - /// @date 2009/11/30 - /// - /// @brief Adds a path to the end of list. - /// @param[in] spPath - path to be added. - // ============================================================================ - void TPathContainer::Add(const TSmartPath& spPath) - { - m_vPaths.push_back(spPath); - } - - void TPathContainer::Append(const TPathContainer& vPaths) - { - m_vPaths.insert(m_vPaths.end(), vPaths.m_vPaths.begin(), vPaths.m_vPaths.end()); - } - - // ============================================================================ - /// TPathContainer::GetAt - /// @date 2009/11/30 - /// - /// @brief Retrieves path at specified index. - /// @param[in] stIndex - index at which to retrieve item. - /// @return Reference to the path object. - // ============================================================================ - const TSmartPath& TPathContainer::GetAt(size_t stIndex) const - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vPaths.at(stIndex); - } - - // ============================================================================ - /// TPathContainer::GetAt - /// @date 2009/11/30 - /// - /// @brief Retrieves path at specified index. - /// @param[in] stIndex - index at which to retrieve item. - /// @return Reference to the path object. - // ============================================================================ - TSmartPath& TPathContainer::GetAt(size_t stIndex) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vPaths.at(stIndex); - } - - // ============================================================================ - /// TPathContainer::SetAt - /// @date 2009/11/30 - /// - /// @brief Sets a path at a specified index. - /// @param[in] stIndex - index at which to set the path. - /// @param[in] spPath - path to be set. - // ============================================================================ - void TPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vPaths[stIndex] = spPath; - } - - // ============================================================================ - /// TPathContainer::DeleteAt - /// @date 2009/11/30 - /// - /// @brief Removes a path from container at specified index. - /// @param[in] stIndex - index at which to delete. - // ============================================================================ - void TPathContainer::DeleteAt(size_t stIndex) - { - if (stIndex > m_vPaths.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vPaths.erase(m_vPaths.begin() + stIndex); - } - - // ============================================================================ - /// TPathContainer::Clear - /// @date 2009/11/30 - /// - /// @brief Removes all paths from this container. - // ============================================================================ - void TPathContainer::Clear() - { - m_vPaths.clear(); - } - - // ============================================================================ - /// TPathContainer::GetCount - /// @date 2009/11/30 - /// - /// @brief Retrieves count of elements in the container. - /// @return Count of elements. - // ============================================================================ - size_t TPathContainer::GetCount() const - { - return m_vPaths.size(); - } - - // ============================================================================ - /// TPathContainer::GetCount - /// @date 2010/10/12 - /// - /// @brief Retrieves info if this container is empty. - /// @return True if empty, false otherwise. - // ============================================================================ - bool TPathContainer::IsEmpty() const - { - return m_vPaths.empty(); - } - - void TPathContainer::StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const - { - TStringArray vPaths; - - // store as vector of strings (ineffective; should be done better) - for(const TSmartPath& spPath : m_vPaths) - { - vPaths.Add(spPath.ToWString()); - } - - rConfig.SetValue(pszPropName, vPaths); - } - - bool TPathContainer::ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName) - { - m_vPaths.clear(); - - TStringArray vPaths; - if (rConfig.GetValue(pszPropName, vPaths)) - { - for (size_t stIndex = 0; stIndex < vPaths.GetCount(); ++stIndex) - { - m_vPaths.push_back(PathFromWString(vPaths.GetAt(stIndex))); - } - return true; - } - else - return false; - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TPathContainer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TStringArray.h" + +namespace chcore +{ + // ============================================================================ + /// TPathContainer::TPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs an empty path container object. + // ============================================================================ + TPathContainer::TPathContainer() : + m_vPaths() + { + } + + // ============================================================================ + /// TPathContainer::TPathContainer + /// @date 2009/11/30 + /// + /// @brief Constructs the path container object from another path container. + /// @param[in] rSrcContainer - path container to copy paths from. + // ============================================================================ + TPathContainer::TPathContainer(const TPathContainer& rSrcContainer) : + m_vPaths(rSrcContainer.m_vPaths) + { + } + + // ============================================================================ + /// TPathContainer::~TPathContainer + /// @date 2009/11/30 + /// + /// @brief Destructs this path container object. + // ============================================================================ + TPathContainer::~TPathContainer() + { + } + + // ============================================================================ + /// TPathContainer::operator= + /// @date 2009/11/30 + /// + /// @brief Assigns another path container object to this one. + /// @param[in] rSrcContainer - container with paths to copy from. + /// @return Reference to this object. + // ============================================================================ + TPathContainer& TPathContainer::operator=(const TPathContainer& rSrcContainer) + { + if (this != &rSrcContainer) + m_vPaths = rSrcContainer.m_vPaths; + + return *this; + } + + // ============================================================================ + /// TPathContainer::Add + /// @date 2009/11/30 + /// + /// @brief Adds a path to the end of list. + /// @param[in] spPath - path to be added. + // ============================================================================ + void TPathContainer::Add(const TSmartPath& spPath) + { + m_vPaths.push_back(spPath); + } + + void TPathContainer::Append(const TPathContainer& vPaths) + { + m_vPaths.insert(m_vPaths.end(), vPaths.m_vPaths.begin(), vPaths.m_vPaths.end()); + } + + // ============================================================================ + /// TPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + const TSmartPath& TPathContainer::GetAt(size_t stIndex) const + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vPaths.at(stIndex); + } + + // ============================================================================ + /// TPathContainer::GetAt + /// @date 2009/11/30 + /// + /// @brief Retrieves path at specified index. + /// @param[in] stIndex - index at which to retrieve item. + /// @return Reference to the path object. + // ============================================================================ + TSmartPath& TPathContainer::GetAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vPaths.at(stIndex); + } + + // ============================================================================ + /// TPathContainer::SetAt + /// @date 2009/11/30 + /// + /// @brief Sets a path at a specified index. + /// @param[in] stIndex - index at which to set the path. + /// @param[in] spPath - path to be set. + // ============================================================================ + void TPathContainer::SetAt(size_t stIndex, const TSmartPath& spPath) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vPaths[stIndex] = spPath; + } + + // ============================================================================ + /// TPathContainer::DeleteAt + /// @date 2009/11/30 + /// + /// @brief Removes a path from container at specified index. + /// @param[in] stIndex - index at which to delete. + // ============================================================================ + void TPathContainer::DeleteAt(size_t stIndex) + { + if (stIndex > m_vPaths.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vPaths.erase(m_vPaths.begin() + stIndex); + } + + // ============================================================================ + /// TPathContainer::Clear + /// @date 2009/11/30 + /// + /// @brief Removes all paths from this container. + // ============================================================================ + void TPathContainer::Clear() + { + m_vPaths.clear(); + } + + // ============================================================================ + /// TPathContainer::GetCount + /// @date 2009/11/30 + /// + /// @brief Retrieves count of elements in the container. + /// @return Count of elements. + // ============================================================================ + size_t TPathContainer::GetCount() const + { + return m_vPaths.size(); + } + + // ============================================================================ + /// TPathContainer::GetCount + /// @date 2010/10/12 + /// + /// @brief Retrieves info if this container is empty. + /// @return True if empty, false otherwise. + // ============================================================================ + bool TPathContainer::IsEmpty() const + { + return m_vPaths.empty(); + } + + void TPathContainer::StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const + { + TStringArray vPaths; + + // store as vector of strings (ineffective; should be done better) + for(const TSmartPath& spPath : m_vPaths) + { + vPaths.Add(spPath.ToWString()); + } + + rConfig.SetValue(pszPropName, vPaths); + } + + bool TPathContainer::ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName) + { + m_vPaths.clear(); + + TStringArray vPaths; + if (rConfig.GetValue(pszPropName, vPaths)) + { + for (size_t stIndex = 0; stIndex < vPaths.GetCount(); ++stIndex) + { + m_vPaths.push_back(PathFromWString(vPaths.GetAt(stIndex))); + } + return true; + } + else + return false; + } +} Index: src/libchcore/TPathContainer.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPathContainer.h (.../TPathContainer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TPathContainer.h (.../TPathContainer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,64 +1,64 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TPATHCONTAINER_H__ -#define __TPATHCONTAINER_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "TConfig.h" - -namespace chcore -{ - class LIBCHCORE_API TPathContainer - { - public: - TPathContainer(); - TPathContainer(const TPathContainer& rSrcContainer); - ~TPathContainer(); - - TPathContainer& operator=(const TPathContainer& rSrcContainer); - - void Add(const TSmartPath& spPath); - void Append(const TPathContainer& vPaths); - - const TSmartPath& GetAt(size_t stIndex) const; - TSmartPath& GetAt(size_t stIndex); - - void SetAt(size_t stIndex, const TSmartPath& spPath); - - void DeleteAt(size_t stIndex); - void Clear(); - - size_t GetCount() const; - bool IsEmpty() const; - - void StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const; - bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vPaths; -#pragma warning(pop) - }; -} - -CONFIG_MEMBER_SERIALIZATION(TPathContainer) - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TPATHCONTAINER_H__ +#define __TPATHCONTAINER_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "TConfig.h" + +namespace chcore +{ + class LIBCHCORE_API TPathContainer + { + public: + TPathContainer(); + TPathContainer(const TPathContainer& rSrcContainer); + ~TPathContainer(); + + TPathContainer& operator=(const TPathContainer& rSrcContainer); + + void Add(const TSmartPath& spPath); + void Append(const TPathContainer& vPaths); + + const TSmartPath& GetAt(size_t stIndex) const; + TSmartPath& GetAt(size_t stIndex); + + void SetAt(size_t stIndex, const TSmartPath& spPath); + + void DeleteAt(size_t stIndex); + void Clear(); + + size_t GetCount() const; + bool IsEmpty() const; + + void StoreInConfig(TConfig& rConfig, PCTSTR pszPropName) const; + bool ReadFromConfig(const TConfig& rConfig, PCTSTR pszPropName); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vPaths; +#pragma warning(pop) + }; +} + +CONFIG_MEMBER_SERIALIZATION(TPathContainer) + +#endif Index: src/libchcore/TPlainStringPool.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPlainStringPool.cpp (.../TPlainStringPool.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TPlainStringPool.cpp (.../TPlainStringPool.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,95 +1,95 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TPlainStringPool.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TPlainStringPool::TPlainStringPool() - { - } - - TPlainStringPool::~TPlainStringPool() - { - Clear(); - } - - wchar_t* TPlainStringPool::Alloc(size_t stCount) - { - if (stCount > BlockSize) - throw TCoreException(eErr_InvalidArgument, L"stCount", LOCATION); - - // find block where the new string would fit - size_t stBlockCount = m_vBlocks.size(); - for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) - { - if (m_vBlocks[stIndex].second >= stCount) - { - wchar_t* pszResult = m_vBlocks[stIndex].first + BlockSize - m_vBlocks[stIndex].second; - m_vBlocks[stIndex].second -= stCount; - return pszResult; - } - } - - wchar_t* pszBuffer = AllocNewBlock(); - m_vBlocks.back().second -= stCount; - - return pszBuffer; - } - - wchar_t* TPlainStringPool::AllocForString(const wchar_t* pszString) - { - size_t stLen = wcslen(pszString) + 1; - - wchar_t* pszBuffer = Alloc(stLen); - wmemcpy_s(pszBuffer, BlockSize, pszString, stLen); - - return pszBuffer; - } - - void TPlainStringPool::Clear(bool bLeaveSingleEmptyBlock) - { - size_t stBlockCount = m_vBlocks.size(); - for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) - { - if (!bLeaveSingleEmptyBlock || stIndex != 0) - { - delete[] m_vBlocks[stIndex].first; - } - } - - if (bLeaveSingleEmptyBlock) - { - if (m_vBlocks.size() > 1) - m_vBlocks.erase(m_vBlocks.begin() + 1, m_vBlocks.end()); - } - else - m_vBlocks.clear(); - } - - wchar_t* TPlainStringPool::AllocNewBlock() - { - wchar_t* pszBlock = new wchar_t[BlockSize]; - m_vBlocks.push_back(std::make_pair(pszBlock, BlockSize)); - - return pszBlock; - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TPlainStringPool.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TPlainStringPool::TPlainStringPool() + { + } + + TPlainStringPool::~TPlainStringPool() + { + Clear(); + } + + wchar_t* TPlainStringPool::Alloc(size_t stCount) + { + if (stCount > BlockSize) + throw TCoreException(eErr_InvalidArgument, L"stCount", LOCATION); + + // find block where the new string would fit + size_t stBlockCount = m_vBlocks.size(); + for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) + { + if (m_vBlocks[stIndex].second >= stCount) + { + wchar_t* pszResult = m_vBlocks[stIndex].first + BlockSize - m_vBlocks[stIndex].second; + m_vBlocks[stIndex].second -= stCount; + return pszResult; + } + } + + wchar_t* pszBuffer = AllocNewBlock(); + m_vBlocks.back().second -= stCount; + + return pszBuffer; + } + + wchar_t* TPlainStringPool::AllocForString(const wchar_t* pszString) + { + size_t stLen = wcslen(pszString) + 1; + + wchar_t* pszBuffer = Alloc(stLen); + wmemcpy_s(pszBuffer, BlockSize, pszString, stLen); + + return pszBuffer; + } + + void TPlainStringPool::Clear(bool bLeaveSingleEmptyBlock) + { + size_t stBlockCount = m_vBlocks.size(); + for (size_t stIndex = 0; stIndex < stBlockCount; ++stIndex) + { + if (!bLeaveSingleEmptyBlock || stIndex != 0) + { + delete[] m_vBlocks[stIndex].first; + } + } + + if (bLeaveSingleEmptyBlock) + { + if (m_vBlocks.size() > 1) + m_vBlocks.erase(m_vBlocks.begin() + 1, m_vBlocks.end()); + } + else + m_vBlocks.clear(); + } + + wchar_t* TPlainStringPool::AllocNewBlock() + { + wchar_t* pszBlock = new wchar_t[BlockSize]; + m_vBlocks.push_back(std::make_pair(pszBlock, BlockSize)); + + return pszBlock; + } +} Index: src/libchcore/TPlainStringPool.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TPlainStringPool.h (.../TPlainStringPool.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TPlainStringPool.h (.../TPlainStringPool.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,51 +1,51 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TPLAINSTRINGPOOL_H__ -#define __TPLAINSTRINGPOOL_H__ - -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API TPlainStringPool - { - public: - static const size_t BlockSize = 256 * 1024; - - public: - TPlainStringPool(); - ~TPlainStringPool(); - - wchar_t* Alloc(size_t stCount); - wchar_t* AllocForString(const wchar_t* pszString); - - void Clear(bool bLeaveSingleEmptyBlock = true); - - private: - wchar_t* AllocNewBlock(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector > m_vBlocks; // memory blocks of size BlockSize => remaining size -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TPLAINSTRINGPOOL_H__ +#define __TPLAINSTRINGPOOL_H__ + +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API TPlainStringPool + { + public: + static const size_t BlockSize = 256 * 1024; + + public: + TPlainStringPool(); + ~TPlainStringPool(); + + wchar_t* Alloc(size_t stCount); + wchar_t* AllocForString(const wchar_t* pszString); + + void Clear(bool bLeaveSingleEmptyBlock = true); + + private: + wchar_t* AllocNewBlock(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector > m_vBlocks; // memory blocks of size BlockSize => remaining size +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TRemovedObjects.cpp =================================================================== diff -u -rc22b1c58209159971a479a90c5fc2b79030f7674 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TRemovedObjects.cpp (.../TRemovedObjects.cpp) (revision c22b1c58209159971a479a90c5fc2b79030f7674) +++ src/libchcore/TRemovedObjects.cpp (.../TRemovedObjects.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,61 +1,61 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TRemovedObjects.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TRemovedObjects::TRemovedObjects() - { - } - - TRemovedObjects::~TRemovedObjects() - { - } - - void TRemovedObjects::Add(object_id_t oidObjectID) - { - m_setObjects.insert(oidObjectID); - } - - size_t TRemovedObjects::GetCount() const - { - return m_setObjects.size(); - } - - object_id_t TRemovedObjects::GetAt(size_t stIndex) const - { - if (stIndex >= m_setObjects.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return *(m_setObjects.begin() + stIndex); - } - - void TRemovedObjects::Clear() - { - m_setObjects.clear(); - } - - bool TRemovedObjects::IsEmpty() const - { - return m_setObjects.empty(); - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TRemovedObjects.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TRemovedObjects::TRemovedObjects() + { + } + + TRemovedObjects::~TRemovedObjects() + { + } + + void TRemovedObjects::Add(object_id_t oidObjectID) + { + m_setObjects.insert(oidObjectID); + } + + size_t TRemovedObjects::GetCount() const + { + return m_setObjects.size(); + } + + object_id_t TRemovedObjects::GetAt(size_t stIndex) const + { + if (stIndex >= m_setObjects.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return *(m_setObjects.begin() + stIndex); + } + + void TRemovedObjects::Clear() + { + m_setObjects.clear(); + } + + bool TRemovedObjects::IsEmpty() const + { + return m_setObjects.empty(); + } +} Index: src/libchcore/TRemovedObjects.h =================================================================== diff -u -rc22b1c58209159971a479a90c5fc2b79030f7674 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TRemovedObjects.h (.../TRemovedObjects.h) (revision c22b1c58209159971a479a90c5fc2b79030f7674) +++ src/libchcore/TRemovedObjects.h (.../TRemovedObjects.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,49 +1,49 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TREMOVEDOBJECTS_H__ -#define __TREMOVEDOBJECTS_H__ - -#include "libchcore.h" -#include "SerializerDataTypes.h" -#include - -namespace chcore -{ - class LIBCHCORE_API TRemovedObjects - { - public: - TRemovedObjects(); - ~TRemovedObjects(); - - void Add(object_id_t oidObjectID); - size_t GetCount() const; - object_id_t GetAt(size_t stIndex) const; - void Clear(); - - bool IsEmpty() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - boost::container::flat_set m_setObjects; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TREMOVEDOBJECTS_H__ +#define __TREMOVEDOBJECTS_H__ + +#include "libchcore.h" +#include "SerializerDataTypes.h" +#include + +namespace chcore +{ + class LIBCHCORE_API TRemovedObjects + { + public: + TRemovedObjects(); + ~TRemovedObjects(); + + void Add(object_id_t oidObjectID); + size_t GetCount() const; + object_id_t GetAt(size_t stIndex) const; + void Clear(); + + bool IsEmpty() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + boost::container::flat_set m_setObjects; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSQLiteColumnDefinition.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteColumnDefinition.cpp (.../TSQLiteColumnDefinition.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSQLiteColumnDefinition.cpp (.../TSQLiteColumnDefinition.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,89 +1,89 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteColumnDefinition.h" -#include "ErrorCodes.h" -#include "TCoreException.h" - -namespace chcore -{ - TSQLiteColumnsDefinition::TSQLiteColumnsDefinition() - { - } - - TSQLiteColumnsDefinition::~TSQLiteColumnsDefinition() - { - } - - size_t TSQLiteColumnsDefinition::AddColumn(const TString& strColumnName, ETypes eColType) - { - m_vColumns.push_back(std::make_pair(strColumnName, eColType)); - return m_vColumns.size() - 1; - } - - void TSQLiteColumnsDefinition::Clear() - { - m_vColumns.clear(); - } - - size_t TSQLiteColumnsDefinition::GetColumnIndex(const wchar_t* strColumnName) - { - size_t stPos = 0; - for (VecColumns::const_iterator iterFnd = m_vColumns.begin(); iterFnd != m_vColumns.end(); ++iterFnd) - { - if (iterFnd->first == strColumnName) - return stPos; - ++stPos; - } - - throw TCoreException(eErr_BoundsExceeded, L"Column name not found", LOCATION); - } - - const TString& TSQLiteColumnsDefinition::GetColumnName(size_t stIndex) const - { - return m_vColumns.at(stIndex).first; - } - - size_t TSQLiteColumnsDefinition::GetCount() const - { - return m_vColumns.size(); - } - - bool TSQLiteColumnsDefinition::IsEmpty() const - { - return m_vColumns.empty(); - } - - TString TSQLiteColumnsDefinition::GetCommaSeparatedColumns() const - { - TString strColumns; - for(VecColumns::value_type pairCol : m_vColumns) - { - strColumns += pairCol.first + _T(","); - } - - strColumns.TrimRightSelf(_T(",")); - return strColumns; - } - - IColumnsDefinition::ETypes TSQLiteColumnsDefinition::GetColumnType(size_t stIndex) const - { - return m_vColumns.at(stIndex).second; - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteColumnDefinition.h" +#include "ErrorCodes.h" +#include "TCoreException.h" + +namespace chcore +{ + TSQLiteColumnsDefinition::TSQLiteColumnsDefinition() + { + } + + TSQLiteColumnsDefinition::~TSQLiteColumnsDefinition() + { + } + + size_t TSQLiteColumnsDefinition::AddColumn(const TString& strColumnName, ETypes eColType) + { + m_vColumns.push_back(std::make_pair(strColumnName, eColType)); + return m_vColumns.size() - 1; + } + + void TSQLiteColumnsDefinition::Clear() + { + m_vColumns.clear(); + } + + size_t TSQLiteColumnsDefinition::GetColumnIndex(const wchar_t* strColumnName) + { + size_t stPos = 0; + for (VecColumns::const_iterator iterFnd = m_vColumns.begin(); iterFnd != m_vColumns.end(); ++iterFnd) + { + if (iterFnd->first == strColumnName) + return stPos; + ++stPos; + } + + throw TCoreException(eErr_BoundsExceeded, L"Column name not found", LOCATION); + } + + const TString& TSQLiteColumnsDefinition::GetColumnName(size_t stIndex) const + { + return m_vColumns.at(stIndex).first; + } + + size_t TSQLiteColumnsDefinition::GetCount() const + { + return m_vColumns.size(); + } + + bool TSQLiteColumnsDefinition::IsEmpty() const + { + return m_vColumns.empty(); + } + + TString TSQLiteColumnsDefinition::GetCommaSeparatedColumns() const + { + TString strColumns; + for(VecColumns::value_type pairCol : m_vColumns) + { + strColumns += pairCol.first + _T(","); + } + + strColumns.TrimRightSelf(_T(",")); + return strColumns; + } + + IColumnsDefinition::ETypes TSQLiteColumnsDefinition::GetColumnType(size_t stIndex) const + { + return m_vColumns.at(stIndex).second; + } +} Index: src/libchcore/TSQLiteColumnDefinition.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteColumnDefinition.h (.../TSQLiteColumnDefinition.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSQLiteColumnDefinition.h (.../TSQLiteColumnDefinition.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,55 +1,55 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITECOLUMNDEFINITION_H__ -#define __TSQLITECOLUMNDEFINITION_H__ - -#include "libchcore.h" -#include "TString.h" -#include -#include "IColumnsDefinition.h" - -namespace chcore -{ - class LIBCHCORE_API TSQLiteColumnsDefinition : public IColumnsDefinition - { - public: - TSQLiteColumnsDefinition(); - virtual ~TSQLiteColumnsDefinition(); - - virtual size_t AddColumn(const TString& strColumnName, ETypes eColType); - virtual void Clear(); - - virtual size_t GetColumnIndex(const wchar_t* strColumnName); - virtual ETypes GetColumnType(size_t stIndex) const; - virtual const TString& GetColumnName(size_t stIndex) const; - virtual size_t GetCount() const; - virtual bool IsEmpty() const; - - virtual TString GetCommaSeparatedColumns() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - typedef std::vector> VecColumns; - VecColumns m_vColumns; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITECOLUMNDEFINITION_H__ +#define __TSQLITECOLUMNDEFINITION_H__ + +#include "libchcore.h" +#include "TString.h" +#include +#include "IColumnsDefinition.h" + +namespace chcore +{ + class LIBCHCORE_API TSQLiteColumnsDefinition : public IColumnsDefinition + { + public: + TSQLiteColumnsDefinition(); + virtual ~TSQLiteColumnsDefinition(); + + virtual size_t AddColumn(const TString& strColumnName, ETypes eColType); + virtual void Clear(); + + virtual size_t GetColumnIndex(const wchar_t* strColumnName); + virtual ETypes GetColumnType(size_t stIndex) const; + virtual const TString& GetColumnName(size_t stIndex) const; + virtual size_t GetCount() const; + virtual bool IsEmpty() const; + + virtual TString GetCommaSeparatedColumns() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + typedef std::vector> VecColumns; + VecColumns m_vColumns; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSQLiteDatabase.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteDatabase.cpp (.../TSQLiteDatabase.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/TSQLiteDatabase.cpp (.../TSQLiteDatabase.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,69 +1,69 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteDatabase.h" -#include "sqlite3/sqlite3.h" -#include "ErrorCodes.h" -#include "TSQLiteException.h" - -namespace chcore -{ - namespace sqlite - { - TSQLiteDatabase::TSQLiteDatabase(const TSmartPath& pathDatabase) : - m_pDBHandle(nullptr), - m_bInTransaction(false), - m_pathDatabase(pathDatabase) - { - int iResult = sqlite3_open16(m_pathDatabase.ToString(), &m_pDBHandle); - if (iResult != SQLITE_OK) - { - const wchar_t* pszMsg = (const wchar_t*)sqlite3_errmsg16(m_pDBHandle); - throw TSQLiteException(eErr_SQLiteCannotOpenDatabase, iResult, pszMsg, LOCATION); - } - } - - TSQLiteDatabase::~TSQLiteDatabase() - { - int iResult = sqlite3_close_v2(m_pDBHandle); // handles properly the nullptr DB Handle - iResult; - _ASSERTE(iResult == SQLITE_OK); - } - - HANDLE TSQLiteDatabase::GetHandle() - { - return m_pDBHandle; - } - - bool TSQLiteDatabase::GetInTransaction() const - { - return m_bInTransaction; - } - - void TSQLiteDatabase::SetInTransaction(bool bInTransaction) - { - m_bInTransaction = bInTransaction; - } - - TSmartPath TSQLiteDatabase::GetLocation() const - { - return m_pathDatabase; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteDatabase.h" +#include "sqlite3/sqlite3.h" +#include "ErrorCodes.h" +#include "TSQLiteException.h" + +namespace chcore +{ + namespace sqlite + { + TSQLiteDatabase::TSQLiteDatabase(const TSmartPath& pathDatabase) : + m_pDBHandle(nullptr), + m_bInTransaction(false), + m_pathDatabase(pathDatabase) + { + int iResult = sqlite3_open16(m_pathDatabase.ToString(), &m_pDBHandle); + if (iResult != SQLITE_OK) + { + const wchar_t* pszMsg = (const wchar_t*)sqlite3_errmsg16(m_pDBHandle); + throw TSQLiteException(eErr_SQLiteCannotOpenDatabase, iResult, pszMsg, LOCATION); + } + } + + TSQLiteDatabase::~TSQLiteDatabase() + { + int iResult = sqlite3_close_v2(m_pDBHandle); // handles properly the nullptr DB Handle + iResult; + _ASSERTE(iResult == SQLITE_OK); + } + + HANDLE TSQLiteDatabase::GetHandle() + { + return m_pDBHandle; + } + + bool TSQLiteDatabase::GetInTransaction() const + { + return m_bInTransaction; + } + + void TSQLiteDatabase::SetInTransaction(bool bInTransaction) + { + m_bInTransaction = bInTransaction; + } + + TSmartPath TSQLiteDatabase::GetLocation() const + { + return m_pathDatabase; + } + } +} Index: src/libchcore/TSQLiteDatabase.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteDatabase.h (.../TSQLiteDatabase.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteDatabase.h (.../TSQLiteDatabase.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,57 +1,57 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITEDATABASE_H__ -#define __TSQLITEDATABASE_H__ - -#include "TPath.h" - -struct sqlite3; - -namespace chcore -{ - namespace sqlite - { - class TSQLiteDatabase - { - public: - explicit TSQLiteDatabase(const TSmartPath& strFilename); - ~TSQLiteDatabase(); - - HANDLE GetHandle(); - - TSmartPath GetLocation() const; - - bool GetInTransaction() const; - - protected: - void SetInTransaction(bool bInTransaction); - - private: - TSmartPath m_pathDatabase; - sqlite3* m_pDBHandle; - bool m_bInTransaction; // global transaction state - - friend class TSQLiteTransaction; - }; - - typedef std::shared_ptr TSQLiteDatabasePtr; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITEDATABASE_H__ +#define __TSQLITEDATABASE_H__ + +#include "TPath.h" + +struct sqlite3; + +namespace chcore +{ + namespace sqlite + { + class TSQLiteDatabase + { + public: + explicit TSQLiteDatabase(const TSmartPath& strFilename); + ~TSQLiteDatabase(); + + HANDLE GetHandle(); + + TSmartPath GetLocation() const; + + bool GetInTransaction() const; + + protected: + void SetInTransaction(bool bInTransaction); + + private: + TSmartPath m_pathDatabase; + sqlite3* m_pDBHandle; + bool m_bInTransaction; // global transaction state + + friend class TSQLiteTransaction; + }; + + typedef std::shared_ptr TSQLiteDatabasePtr; + } +} + +#endif Index: src/libchcore/TSQLiteException.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteException.cpp (.../TSQLiteException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSQLiteException.cpp (.../TSQLiteException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,43 +1,43 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteException.h" - -namespace chcore -{ - namespace sqlite - { - TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_iSQLiteError(iSQLiteError) - { - } - - TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), - m_iSQLiteError(iSQLiteError) - { - } - - int TSQLiteException::GetSQLiteError() const - { - return m_iSQLiteError; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteException.h" + +namespace chcore +{ + namespace sqlite + { + TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_iSQLiteError(iSQLiteError) + { + } + + TSQLiteException::TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction), + m_iSQLiteError(iSQLiteError) + { + } + + int TSQLiteException::GetSQLiteError() const + { + return m_iSQLiteError; + } + } +} Index: src/libchcore/TSQLiteException.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteException.h (.../TSQLiteException.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteException.h (.../TSQLiteException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,42 +1,42 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITEEXCEPTION_H__ -#define __TSQLITEEXCEPTION_H__ - -#include "TBaseException.h" - -namespace chcore -{ - namespace sqlite - { - class TSQLiteException : public TBaseException - { - public: - TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - - int GetSQLiteError() const; - - private: - int m_iSQLiteError; - }; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITEEXCEPTION_H__ +#define __TSQLITEEXCEPTION_H__ + +#include "TBaseException.h" + +namespace chcore +{ + namespace sqlite + { + class TSQLiteException : public TBaseException + { + public: + TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TSQLiteException(EGeneralErrors eErrorCode, int iSQLiteError, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + + int GetSQLiteError() const; + + private: + int m_iSQLiteError; + }; + } +} + +#endif Index: src/libchcore/TSQLiteSerializer.cpp =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializer.cpp (.../TSQLiteSerializer.cpp) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteSerializer.cpp (.../TSQLiteSerializer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,111 +1,111 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteSerializer.h" -#include "TSQLiteSerializerContainer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TSQLiteTransaction.h" -#include "TSQLiteStatement.h" -#include "TSimpleTimer.h" -#include "SerializerTrace.h" - -namespace chcore -{ - using namespace sqlite; - - TSQLiteSerializer::TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema) : - m_spDatabase(new TSQLiteDatabase(pathDB)), - m_spSchema(spSchema) - { - if(!m_spDatabase) - throw TCoreException(eErr_InvalidArgument, L"m_spDatabase", LOCATION); - if(!m_spSchema) - throw TCoreException(eErr_InvalidArgument, L"m_spSchema", LOCATION); - - // initialize db params - SetupDBOptions(); - - m_spSchema->Setup(m_spDatabase); - } - - TSQLiteSerializer::~TSQLiteSerializer() - { - // clear the containers first, so that we can safely get rid of the strings pool - m_mapContainers.clear(); - m_poolStrings.Clear(false); - } - - ISerializerContainerPtr TSQLiteSerializer::GetContainer(const TString& strContainerName) - { - ContainerMap::iterator iterMap = m_mapContainers.find(strContainerName); - if (iterMap == m_mapContainers.end()) - iterMap = m_mapContainers.insert(std::make_pair( - strContainerName, - std::make_shared(strContainerName, m_spDatabase, m_poolStrings))).first; - - return iterMap->second; - } - - TSmartPath TSQLiteSerializer::GetLocation() const - { - return m_spDatabase->GetLocation(); - } - - void TSQLiteSerializer::Flush() - { - DBTRACE0(_T(" ## Serializer::Flush() - started\n")); - - TSQLiteTransaction tran(m_spDatabase); - - TSimpleTimer timer(true); - - for (ContainerMap::iterator iterContainer = m_mapContainers.begin(); iterContainer != m_mapContainers.end(); ++iterContainer) - { - iterContainer->second->Flush(); - } - - unsigned long long ullFlushGatherTime = timer.Checkpoint(); ullFlushGatherTime; - - tran.Commit(); - - unsigned long long ullFlushCommitTime = timer.Checkpoint(); ullFlushCommitTime; - DBTRACE2(_T(" ## Serializer::Flush() - container flushes: %I64u ms, transaction commit: %I64u ms\n"), ullFlushGatherTime, ullFlushCommitTime); - - m_mapContainers.clear(); - m_poolStrings.Clear(); - - unsigned long long ullFlushClearTime = timer.Checkpoint(); ullFlushClearTime; - DBTRACE1(_T(" ## Serializer::Flush() - container clearing: %I64u ms\n"), ullFlushClearTime); - } - - void TSQLiteSerializer::SetupDBOptions() - { - /* - TSQLiteStatement tStatement(m_spDatabase); - tStatement.Prepare(_T("PRAGMA JOURNAL_MODE=WAL")); - TSQLiteStatement::EStepResult eResult = tStatement.Step(); - if(eResult != TSQLiteStatement::eStep_HasRow) - throw TCoreException(eErr_CannotSetDatabaseOptions, L"Failed to set database options", LOCATION); - - TString strResult = tStatement.GetText(0); - if(strResult != _T("wal")) - throw TCoreException(eErr_CannotSetDatabaseOptions, L"Failed to set database options", LOCATION);*/ - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteSerializer.h" +#include "TSQLiteSerializerContainer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TSQLiteTransaction.h" +#include "TSQLiteStatement.h" +#include "TSimpleTimer.h" +#include "SerializerTrace.h" + +namespace chcore +{ + using namespace sqlite; + + TSQLiteSerializer::TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema) : + m_spDatabase(new TSQLiteDatabase(pathDB)), + m_spSchema(spSchema) + { + if(!m_spDatabase) + throw TCoreException(eErr_InvalidArgument, L"m_spDatabase", LOCATION); + if(!m_spSchema) + throw TCoreException(eErr_InvalidArgument, L"m_spSchema", LOCATION); + + // initialize db params + SetupDBOptions(); + + m_spSchema->Setup(m_spDatabase); + } + + TSQLiteSerializer::~TSQLiteSerializer() + { + // clear the containers first, so that we can safely get rid of the strings pool + m_mapContainers.clear(); + m_poolStrings.Clear(false); + } + + ISerializerContainerPtr TSQLiteSerializer::GetContainer(const TString& strContainerName) + { + ContainerMap::iterator iterMap = m_mapContainers.find(strContainerName); + if (iterMap == m_mapContainers.end()) + iterMap = m_mapContainers.insert(std::make_pair( + strContainerName, + std::make_shared(strContainerName, m_spDatabase, m_poolStrings))).first; + + return iterMap->second; + } + + TSmartPath TSQLiteSerializer::GetLocation() const + { + return m_spDatabase->GetLocation(); + } + + void TSQLiteSerializer::Flush() + { + DBTRACE0(_T(" ## Serializer::Flush() - started\n")); + + TSQLiteTransaction tran(m_spDatabase); + + TSimpleTimer timer(true); + + for (ContainerMap::iterator iterContainer = m_mapContainers.begin(); iterContainer != m_mapContainers.end(); ++iterContainer) + { + iterContainer->second->Flush(); + } + + unsigned long long ullFlushGatherTime = timer.Checkpoint(); ullFlushGatherTime; + + tran.Commit(); + + unsigned long long ullFlushCommitTime = timer.Checkpoint(); ullFlushCommitTime; + DBTRACE2(_T(" ## Serializer::Flush() - container flushes: %I64u ms, transaction commit: %I64u ms\n"), ullFlushGatherTime, ullFlushCommitTime); + + m_mapContainers.clear(); + m_poolStrings.Clear(); + + unsigned long long ullFlushClearTime = timer.Checkpoint(); ullFlushClearTime; + DBTRACE1(_T(" ## Serializer::Flush() - container clearing: %I64u ms\n"), ullFlushClearTime); + } + + void TSQLiteSerializer::SetupDBOptions() + { + /* + TSQLiteStatement tStatement(m_spDatabase); + tStatement.Prepare(_T("PRAGMA JOURNAL_MODE=WAL")); + TSQLiteStatement::EStepResult eResult = tStatement.Step(); + if(eResult != TSQLiteStatement::eStep_HasRow) + throw TCoreException(eErr_CannotSetDatabaseOptions, L"Failed to set database options", LOCATION); + + TString strResult = tStatement.GetText(0); + if(strResult != _T("wal")) + throw TCoreException(eErr_CannotSetDatabaseOptions, L"Failed to set database options", LOCATION);*/ + } +} Index: src/libchcore/TSQLiteSerializer.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializer.h (.../TSQLiteSerializer.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteSerializer.h (.../TSQLiteSerializer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,63 +1,63 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESERIALIZER_H__ -#define __TSQLITESERIALIZER_H__ - -#include "libchcore.h" -#include -#include "ISerializer.h" -#include "TSQLiteDatabase.h" -#include "TString.h" -#include "ISerializerContainer.h" -#include "TPath.h" -#include "TSQLiteSerializerContainer.h" -#include "ISQLiteSerializerSchema.h" -#include "TPlainStringPool.h" - -namespace chcore -{ - class LIBCHCORE_API TSQLiteSerializer : public ISerializer - { - public: - TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema); - virtual ~TSQLiteSerializer(); - - virtual TSmartPath GetLocation() const; - - virtual ISerializerContainerPtr GetContainer(const TString& strContainerName); - virtual void Flush(); - void SetupDBOptions(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - sqlite::TSQLiteDatabasePtr m_spDatabase; - ISerializerSchemaPtr m_spSchema; - - typedef std::map ContainerMap; - ContainerMap m_mapContainers; - - TPlainStringPool m_poolStrings; -#pragma warning(pop) - }; - - typedef std::shared_ptr TSQLiteSerializerPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESERIALIZER_H__ +#define __TSQLITESERIALIZER_H__ + +#include "libchcore.h" +#include +#include "ISerializer.h" +#include "TSQLiteDatabase.h" +#include "TString.h" +#include "ISerializerContainer.h" +#include "TPath.h" +#include "TSQLiteSerializerContainer.h" +#include "ISQLiteSerializerSchema.h" +#include "TPlainStringPool.h" + +namespace chcore +{ + class LIBCHCORE_API TSQLiteSerializer : public ISerializer + { + public: + TSQLiteSerializer(const TSmartPath& pathDB, const ISerializerSchemaPtr& spSchema); + virtual ~TSQLiteSerializer(); + + virtual TSmartPath GetLocation() const; + + virtual ISerializerContainerPtr GetContainer(const TString& strContainerName); + virtual void Flush(); + void SetupDBOptions(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + sqlite::TSQLiteDatabasePtr m_spDatabase; + ISerializerSchemaPtr m_spSchema; + + typedef std::map ContainerMap; + ContainerMap m_mapContainers; + + TPlainStringPool m_poolStrings; +#pragma warning(pop) + }; + + typedef std::shared_ptr TSQLiteSerializerPtr; +} + +#endif Index: src/libchcore/TSQLiteSerializerContainer.cpp =================================================================== diff -u -rc22b1c58209159971a479a90c5fc2b79030f7674 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerContainer.cpp (.../TSQLiteSerializerContainer.cpp) (revision c22b1c58209159971a479a90c5fc2b79030f7674) +++ src/libchcore/TSQLiteSerializerContainer.cpp (.../TSQLiteSerializerContainer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,209 +1,209 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteSerializerContainer.h" -#include "TSQLiteSerializerRowData.h" -#include "ErrorCodes.h" -#include "TCoreException.h" -#include -#include "TSQLiteStatement.h" -#include "TSQLiteSerializerRowReader.h" -#include "TRemovedObjects.h" -#include "SerializerTrace.h" -#include -#include "TSerializerException.h" - -namespace chcore -{ - using namespace sqlite; - - TSQLiteSerializerContainer::TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings) : - m_strName(strName), - m_spDB(spDB), - m_pPoolRows(nullptr), - m_poolStrings(poolStrings) - { - } - - TSQLiteSerializerContainer::~TSQLiteSerializerContainer() - { - // get rid of all rows first - m_mapRows.clear(); - - // now get rid of memory pool - delete m_pPoolRows; - } - - ISerializerRowData& TSQLiteSerializerContainer::GetRow(object_id_t oidRowID, bool bMarkAsAdded) - { - RowMap::iterator iterFnd = m_mapRows.find(oidRowID); - if (iterFnd == m_mapRows.end()) - { - void* pMemoryBlock = GetPool().malloc(); - if (!pMemoryBlock) - throw TSerializerException(eErr_InternalProblem, _T("Cannot allocate memory"), LOCATION); - - iterFnd = m_mapRows.insert(std::make_pair(oidRowID, TSQLiteSerializerRowData(oidRowID, m_tColumns, bMarkAsAdded, (unsigned long long*)pMemoryBlock, GetPool().get_requested_size(), m_poolStrings))).first; - } - else if (bMarkAsAdded) - iterFnd->second.MarkAsAdded(); - - return (*iterFnd).second; - } - - void TSQLiteSerializerContainer::DeleteRow(object_id_t oidRowID) - { - RowMap::iterator iterFnd = m_mapRows.find(oidRowID); - if (iterFnd != m_mapRows.end()) - m_mapRows.erase(iterFnd); - - m_setDeleteItems.insert(oidRowID); - } - - void TSQLiteSerializerContainer::DeleteRows(const TRemovedObjects& setObjects) - { - size_t stCount = setObjects.GetCount(); - - auto iterRows = m_mapRows.begin(); - size_t stInputIndex = 0; - while(stInputIndex < stCount && iterRows != m_mapRows.end()) - { - object_id_t idInput = setObjects.GetAt(stInputIndex); - object_id_t idRows = iterRows->first; - - if(idInput < idRows) - ++stInputIndex; - else if(idInput > idRows) - ++iterRows; - else - { - // equals - iterRows = m_mapRows.erase(iterRows); - ++stInputIndex; - } - } - - while(stCount > 0) - { - m_setDeleteItems.insert(setObjects.GetAt(--stCount)); - } - } - - ISerializerRowReaderPtr TSQLiteSerializerContainer::GetRowReader() - { - TSQLiteSerializerRowReaderPtr spRowReader(new TSQLiteSerializerRowReader(m_spDB, m_tColumns, m_strName)); - return spRowReader; - } - - IColumnsDefinition& TSQLiteSerializerContainer::GetColumnsDefinition() - { - return m_tColumns; - } - - void TSQLiteSerializerContainer::Flush() - { - FlushDeletions(); - - // group rows that can be executed with one preparation - std::map> mapGroups; - std::map>::iterator iterMapGroups; - - for (RowMap::iterator iterRows = m_mapRows.begin(); iterRows != m_mapRows.end(); ++iterRows) - { - unsigned long long rowID = iterRows->second.GetChangeIdentification(); - iterMapGroups = mapGroups.find(rowID); - if (iterMapGroups == mapGroups.end()) - iterMapGroups = mapGroups.insert(std::make_pair(rowID, std::vector())).first; - - iterMapGroups->second.push_back(&iterRows->second); - } - - TSQLiteStatement tStatement(m_spDB); - - for (iterMapGroups = mapGroups.begin(); iterMapGroups != mapGroups.end(); ++iterMapGroups) - { - if (iterMapGroups->first != 0) - { - std::vector& rGroupRows = iterMapGroups->second; - - // query is generated from the first item in a group - TString strQuery = rGroupRows.front()->GetQuery(m_strName); - if (!strQuery.IsEmpty()) - { - DBTRACE2(_T("Preparing query for %lu records: %s\n"), (unsigned long)iterMapGroups->second.size(), strQuery.c_str()); - - tStatement.Prepare(strQuery.c_str()); - - for (std::vector::iterator iterRow = iterMapGroups->second.begin(); iterRow != iterMapGroups->second.end(); ++iterRow) - { - (*iterRow)->BindParamsAndExec(tStatement); - tStatement.ClearBindings(); - } - - tStatement.Close(); - } - } - } - } - - void TSQLiteSerializerContainer::FlushDeletions() - { - size_t stCount = m_setDeleteItems.size(); - if(stCount == 0) - return; - - TSQLiteStatement tStatement(m_spDB); - - TString strQuery = boost::str(boost::wformat(L"DELETE FROM %1% WHERE id=?1") % m_strName).c_str(); - tStatement.Prepare(strQuery.c_str()); - - for (object_id_t idObj : m_setDeleteItems) - { - tStatement.ClearBindings(); - tStatement.BindValue(1, idObj); - - DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); - tStatement.Step(); - } - } - - boost::pool<>& TSQLiteSerializerContainer::GetPool() - { - if (!m_pPoolRows) - m_pPoolRows = new boost::pool<>(CalculateRowMemorySize()); - else - { - if (m_pPoolRows->get_requested_size() != CalculateRowMemorySize()) - throw TSerializerException(eErr_InternalProblem, _T("Column count changed after first use"), LOCATION); - } - - return *m_pPoolRows; - } - - size_t TSQLiteSerializerContainer::CalculateRowMemorySize() const - { - // assume 64bit column mask (8 bytes) - const size_t stMaskSize = 8; - - // and additionally 64bit for each column (either for storing numbers directly or for allocating string/double) - const size_t stFieldSize = 8; - - return stMaskSize + m_tColumns.GetCount() * stFieldSize; - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteSerializerContainer.h" +#include "TSQLiteSerializerRowData.h" +#include "ErrorCodes.h" +#include "TCoreException.h" +#include +#include "TSQLiteStatement.h" +#include "TSQLiteSerializerRowReader.h" +#include "TRemovedObjects.h" +#include "SerializerTrace.h" +#include +#include "TSerializerException.h" + +namespace chcore +{ + using namespace sqlite; + + TSQLiteSerializerContainer::TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings) : + m_strName(strName), + m_spDB(spDB), + m_pPoolRows(nullptr), + m_poolStrings(poolStrings) + { + } + + TSQLiteSerializerContainer::~TSQLiteSerializerContainer() + { + // get rid of all rows first + m_mapRows.clear(); + + // now get rid of memory pool + delete m_pPoolRows; + } + + ISerializerRowData& TSQLiteSerializerContainer::GetRow(object_id_t oidRowID, bool bMarkAsAdded) + { + RowMap::iterator iterFnd = m_mapRows.find(oidRowID); + if (iterFnd == m_mapRows.end()) + { + void* pMemoryBlock = GetPool().malloc(); + if (!pMemoryBlock) + throw TSerializerException(eErr_InternalProblem, _T("Cannot allocate memory"), LOCATION); + + iterFnd = m_mapRows.insert(std::make_pair(oidRowID, TSQLiteSerializerRowData(oidRowID, m_tColumns, bMarkAsAdded, (unsigned long long*)pMemoryBlock, GetPool().get_requested_size(), m_poolStrings))).first; + } + else if (bMarkAsAdded) + iterFnd->second.MarkAsAdded(); + + return (*iterFnd).second; + } + + void TSQLiteSerializerContainer::DeleteRow(object_id_t oidRowID) + { + RowMap::iterator iterFnd = m_mapRows.find(oidRowID); + if (iterFnd != m_mapRows.end()) + m_mapRows.erase(iterFnd); + + m_setDeleteItems.insert(oidRowID); + } + + void TSQLiteSerializerContainer::DeleteRows(const TRemovedObjects& setObjects) + { + size_t stCount = setObjects.GetCount(); + + auto iterRows = m_mapRows.begin(); + size_t stInputIndex = 0; + while(stInputIndex < stCount && iterRows != m_mapRows.end()) + { + object_id_t idInput = setObjects.GetAt(stInputIndex); + object_id_t idRows = iterRows->first; + + if(idInput < idRows) + ++stInputIndex; + else if(idInput > idRows) + ++iterRows; + else + { + // equals + iterRows = m_mapRows.erase(iterRows); + ++stInputIndex; + } + } + + while(stCount > 0) + { + m_setDeleteItems.insert(setObjects.GetAt(--stCount)); + } + } + + ISerializerRowReaderPtr TSQLiteSerializerContainer::GetRowReader() + { + TSQLiteSerializerRowReaderPtr spRowReader(new TSQLiteSerializerRowReader(m_spDB, m_tColumns, m_strName)); + return spRowReader; + } + + IColumnsDefinition& TSQLiteSerializerContainer::GetColumnsDefinition() + { + return m_tColumns; + } + + void TSQLiteSerializerContainer::Flush() + { + FlushDeletions(); + + // group rows that can be executed with one preparation + std::map> mapGroups; + std::map>::iterator iterMapGroups; + + for (RowMap::iterator iterRows = m_mapRows.begin(); iterRows != m_mapRows.end(); ++iterRows) + { + unsigned long long rowID = iterRows->second.GetChangeIdentification(); + iterMapGroups = mapGroups.find(rowID); + if (iterMapGroups == mapGroups.end()) + iterMapGroups = mapGroups.insert(std::make_pair(rowID, std::vector())).first; + + iterMapGroups->second.push_back(&iterRows->second); + } + + TSQLiteStatement tStatement(m_spDB); + + for (iterMapGroups = mapGroups.begin(); iterMapGroups != mapGroups.end(); ++iterMapGroups) + { + if (iterMapGroups->first != 0) + { + std::vector& rGroupRows = iterMapGroups->second; + + // query is generated from the first item in a group + TString strQuery = rGroupRows.front()->GetQuery(m_strName); + if (!strQuery.IsEmpty()) + { + DBTRACE2(_T("Preparing query for %lu records: %s\n"), (unsigned long)iterMapGroups->second.size(), strQuery.c_str()); + + tStatement.Prepare(strQuery.c_str()); + + for (std::vector::iterator iterRow = iterMapGroups->second.begin(); iterRow != iterMapGroups->second.end(); ++iterRow) + { + (*iterRow)->BindParamsAndExec(tStatement); + tStatement.ClearBindings(); + } + + tStatement.Close(); + } + } + } + } + + void TSQLiteSerializerContainer::FlushDeletions() + { + size_t stCount = m_setDeleteItems.size(); + if(stCount == 0) + return; + + TSQLiteStatement tStatement(m_spDB); + + TString strQuery = boost::str(boost::wformat(L"DELETE FROM %1% WHERE id=?1") % m_strName).c_str(); + tStatement.Prepare(strQuery.c_str()); + + for (object_id_t idObj : m_setDeleteItems) + { + tStatement.ClearBindings(); + tStatement.BindValue(1, idObj); + + DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); + tStatement.Step(); + } + } + + boost::pool<>& TSQLiteSerializerContainer::GetPool() + { + if (!m_pPoolRows) + m_pPoolRows = new boost::pool<>(CalculateRowMemorySize()); + else + { + if (m_pPoolRows->get_requested_size() != CalculateRowMemorySize()) + throw TSerializerException(eErr_InternalProblem, _T("Column count changed after first use"), LOCATION); + } + + return *m_pPoolRows; + } + + size_t TSQLiteSerializerContainer::CalculateRowMemorySize() const + { + // assume 64bit column mask (8 bytes) + const size_t stMaskSize = 8; + + // and additionally 64bit for each column (either for storing numbers directly or for allocating string/double) + const size_t stFieldSize = 8; + + return stMaskSize + m_tColumns.GetCount() * stFieldSize; + } +} Index: src/libchcore/TSQLiteSerializerContainer.h =================================================================== diff -u -rc22b1c58209159971a479a90c5fc2b79030f7674 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerContainer.h (.../TSQLiteSerializerContainer.h) (revision c22b1c58209159971a479a90c5fc2b79030f7674) +++ src/libchcore/TSQLiteSerializerContainer.h (.../TSQLiteSerializerContainer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,81 +1,81 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESERIALIZERCONTAINER_H__ -#define __TSQLITESERIALIZERCONTAINER_H__ - -#include "libchcore.h" -#include "ISerializerRowReader.h" -#include "ISerializerContainer.h" -#include -#include "TSQLiteColumnDefinition.h" -#include "TSQLiteDatabase.h" -#include "TSQLiteSerializerRowData.h" -#include -#include - -namespace chcore -{ - class LIBCHCORE_API TSQLiteSerializerContainer : public ISerializerContainer - { - private: - TSQLiteSerializerContainer(const TSQLiteSerializerContainer&); - TSQLiteSerializerContainer& operator=(const TSQLiteSerializerContainer&); - - public: - TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings); - virtual ~TSQLiteSerializerContainer(); - - virtual IColumnsDefinition& GetColumnsDefinition(); - - virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded); - virtual void DeleteRow(object_id_t oidRowID); - virtual void DeleteRows(const TRemovedObjects& setObjects); - - virtual ISerializerRowReaderPtr GetRowReader(); - - void Flush(); - - private: - void FlushDeletions(); - boost::pool<>& GetPool(); - size_t CalculateRowMemorySize() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - TSQLiteColumnsDefinition m_tColumns; - - boost::pool<>* m_pPoolRows; - - typedef boost::container::flat_map RowMap; // maps row id to row data - RowMap m_mapRows; - - boost::container::flat_set m_setDeleteItems; - - TString m_strName; - sqlite::TSQLiteDatabasePtr m_spDB; - - TPlainStringPool& m_poolStrings; -#pragma warning(pop) - }; - - using TSQLiteSerializerContainerPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESERIALIZERCONTAINER_H__ +#define __TSQLITESERIALIZERCONTAINER_H__ + +#include "libchcore.h" +#include "ISerializerRowReader.h" +#include "ISerializerContainer.h" +#include +#include "TSQLiteColumnDefinition.h" +#include "TSQLiteDatabase.h" +#include "TSQLiteSerializerRowData.h" +#include +#include + +namespace chcore +{ + class LIBCHCORE_API TSQLiteSerializerContainer : public ISerializerContainer + { + private: + TSQLiteSerializerContainer(const TSQLiteSerializerContainer&); + TSQLiteSerializerContainer& operator=(const TSQLiteSerializerContainer&); + + public: + TSQLiteSerializerContainer(const TString& strName, const sqlite::TSQLiteDatabasePtr& spDB, TPlainStringPool& poolStrings); + virtual ~TSQLiteSerializerContainer(); + + virtual IColumnsDefinition& GetColumnsDefinition(); + + virtual ISerializerRowData& GetRow(object_id_t oidRowID, bool bMarkAsAdded); + virtual void DeleteRow(object_id_t oidRowID); + virtual void DeleteRows(const TRemovedObjects& setObjects); + + virtual ISerializerRowReaderPtr GetRowReader(); + + void Flush(); + + private: + void FlushDeletions(); + boost::pool<>& GetPool(); + size_t CalculateRowMemorySize() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + TSQLiteColumnsDefinition m_tColumns; + + boost::pool<>* m_pPoolRows; + + typedef boost::container::flat_map RowMap; // maps row id to row data + RowMap m_mapRows; + + boost::container::flat_set m_setDeleteItems; + + TString m_strName; + sqlite::TSQLiteDatabasePtr m_spDB; + + TPlainStringPool& m_poolStrings; +#pragma warning(pop) + }; + + using TSQLiteSerializerContainerPtr = std::shared_ptr; +} + +#endif Index: src/libchcore/TSQLiteSerializerFactory.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerFactory.cpp (.../TSQLiteSerializerFactory.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSQLiteSerializerFactory.cpp (.../TSQLiteSerializerFactory.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,97 +1,97 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteSerializerFactory.h" -#include -#include -#include -#include -#include "TSQLiteTaskSchema.h" -#include "TSQLiteSerializer.h" -#include "TSQLiteTaskManagerSchema.h" -#include "TCoreWin32Exception.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TSQLiteSerializerFactory::TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir) : - m_pathSerializeDir(pathSerializeDir) - { - } - - TSQLiteSerializerFactory::~TSQLiteSerializerFactory() - { - } - - ISerializerPtr TSQLiteSerializerFactory::CreateTaskManagerSerializer(bool bForceRecreate) - { - TSmartPath pathTaskManager = m_pathSerializeDir + PathFromString(_T("tasks.sqlite")); - - if (bForceRecreate) - { - if (!DeleteFile(pathTaskManager.ToString())) - { - DWORD dwLastError = GetLastError(); - if (dwLastError != ERROR_FILE_NOT_FOUND) - throw TCoreWin32Exception(eErr_CannotDeleteFile, dwLastError, L"Cannot delete tasks.sqlite file", LOCATION); - } - } - - TSQLiteSerializerPtr spSerializer(std::make_shared( - pathTaskManager, - std::make_shared())); - - return spSerializer; - } - - ISerializerPtr TSQLiteSerializerFactory::CreateTaskSerializer(const TString& strNameHint, bool bForceRecreate) - { - TString strName(strNameHint); - if (strName.IsEmpty()) - { - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - strName = boost::lexical_cast(u).c_str(); - } - - TSmartPath pathTask = PathFromWString(strName); - if (!pathTask.HasFileRoot()) - { - if (!strName.EndsWithNoCase(_T(".sqlite"))) - strName += _T(".sqlite"); - - pathTask = m_pathSerializeDir; - pathTask += PathFromWString(strName); - } - - if (bForceRecreate) - { - if (!DeleteFile(pathTask.ToString())) - { - DWORD dwLastError = GetLastError(); - if (dwLastError != ERROR_FILE_NOT_FOUND) - throw TCoreWin32Exception(eErr_CannotDeleteFile, dwLastError, L"Cannot delete task database file", LOCATION); - } - } - - TSQLiteSerializerPtr spSerializer(std::make_shared(pathTask, std::make_shared())); - - return spSerializer; - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteSerializerFactory.h" +#include +#include +#include +#include +#include "TSQLiteTaskSchema.h" +#include "TSQLiteSerializer.h" +#include "TSQLiteTaskManagerSchema.h" +#include "TCoreWin32Exception.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TSQLiteSerializerFactory::TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir) : + m_pathSerializeDir(pathSerializeDir) + { + } + + TSQLiteSerializerFactory::~TSQLiteSerializerFactory() + { + } + + ISerializerPtr TSQLiteSerializerFactory::CreateTaskManagerSerializer(bool bForceRecreate) + { + TSmartPath pathTaskManager = m_pathSerializeDir + PathFromString(_T("tasks.sqlite")); + + if (bForceRecreate) + { + if (!DeleteFile(pathTaskManager.ToString())) + { + DWORD dwLastError = GetLastError(); + if (dwLastError != ERROR_FILE_NOT_FOUND) + throw TCoreWin32Exception(eErr_CannotDeleteFile, dwLastError, L"Cannot delete tasks.sqlite file", LOCATION); + } + } + + TSQLiteSerializerPtr spSerializer(std::make_shared( + pathTaskManager, + std::make_shared())); + + return spSerializer; + } + + ISerializerPtr TSQLiteSerializerFactory::CreateTaskSerializer(const TString& strNameHint, bool bForceRecreate) + { + TString strName(strNameHint); + if (strName.IsEmpty()) + { + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + strName = boost::lexical_cast(u).c_str(); + } + + TSmartPath pathTask = PathFromWString(strName); + if (!pathTask.HasFileRoot()) + { + if (!strName.EndsWithNoCase(_T(".sqlite"))) + strName += _T(".sqlite"); + + pathTask = m_pathSerializeDir; + pathTask += PathFromWString(strName); + } + + if (bForceRecreate) + { + if (!DeleteFile(pathTask.ToString())) + { + DWORD dwLastError = GetLastError(); + if (dwLastError != ERROR_FILE_NOT_FOUND) + throw TCoreWin32Exception(eErr_CannotDeleteFile, dwLastError, L"Cannot delete task database file", LOCATION); + } + } + + TSQLiteSerializerPtr spSerializer(std::make_shared(pathTask, std::make_shared())); + + return spSerializer; + } +} Index: src/libchcore/TSQLiteSerializerFactory.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerFactory.h (.../TSQLiteSerializerFactory.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteSerializerFactory.h (.../TSQLiteSerializerFactory.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,44 +1,44 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESERIALIZERFACTORY_H__ -#define __TSQLITESERIALIZERFACTORY_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "ISerializerFactory.h" - -namespace chcore -{ - class LIBCHCORE_API TSQLiteSerializerFactory : public ISerializerFactory - { - public: - explicit TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir); - virtual ~TSQLiteSerializerFactory(); - - virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) override; - virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) override; - - private: - TSmartPath m_pathSerializeDir; - }; - - typedef std::shared_ptr TSQLiteSerializerFactoryPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESERIALIZERFACTORY_H__ +#define __TSQLITESERIALIZERFACTORY_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "ISerializerFactory.h" + +namespace chcore +{ + class LIBCHCORE_API TSQLiteSerializerFactory : public ISerializerFactory + { + public: + explicit TSQLiteSerializerFactory(const TSmartPath& pathSerializeDir); + virtual ~TSQLiteSerializerFactory(); + + virtual ISerializerPtr CreateTaskManagerSerializer(bool bForceRecreate = false) override; + virtual ISerializerPtr CreateTaskSerializer(const TString& strNameHint = _T(""), bool bForceRecreate = false) override; + + private: + TSmartPath m_pathSerializeDir; + }; + + typedef std::shared_ptr TSQLiteSerializerFactoryPtr; +} + +#endif Index: src/libchcore/TSQLiteSerializerRowData.cpp =================================================================== diff -u -ra6834b56f41e9e4a44a2869ffdad1599da9b24c4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerRowData.cpp (.../TSQLiteSerializerRowData.cpp) (revision a6834b56f41e9e4a44a2869ffdad1599da9b24c4) +++ src/libchcore/TSQLiteSerializerRowData.cpp (.../TSQLiteSerializerRowData.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,542 +1,542 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteSerializerRowData.h" -#include "TSQLiteStatement.h" -#include -#include "TSerializerException.h" -#include "ErrorCodes.h" -#include "SerializerTrace.h" -#include "TPlainStringPool.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - TSQLiteSerializerRowData::TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings) : - m_rColumns(rColumnDefinition), - m_pPoolMemory(pPoolMemory), - m_poolStrings(poolStrings) - { - if (!m_pPoolMemory) - throw TSerializerException(eErr_InvalidArgument, _T("Null memory provided"), LOCATION); - if (rColumnDefinition.GetCount() > 63) - throw TSerializerException(eErr_InternalProblem, _T("Serializer supports up to 63 columns. If more is needed the block header needs to be increased."), LOCATION); - - // initialize memory - memset((void*)pPoolMemory, 0, stPoolMemorySizeInBytes); - - // set id - size_t stIDIndex = rColumnDefinition.GetColumnIndex(_T("id")); - InternalSetValue(stIDIndex, oidRowID); - - if (bAdded) - MarkAsAdded(); - } - - TSQLiteSerializerRowData::TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc) : - m_rColumns(rSrc.m_rColumns), - m_pPoolMemory(rSrc.m_pPoolMemory), - m_poolStrings(rSrc.m_poolStrings) - { - } - - TSQLiteSerializerRowData::~TSQLiteSerializerRowData() - { - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, bool bValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_bool) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (bValue ? 1ULL : 0ULL); - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, short siValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_short) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned short*)&siValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned short usiValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ushort) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)usiValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, int iValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_int) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned int*)&iValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned int uiValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_uint) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)uiValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long lValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_long) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned long*)&lValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::InternalSetValue(size_t stColIndex, unsigned long ulValue) - { - if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulong) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = (unsigned long long)ulValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long ulValue) - { - InternalSetValue(stColIndex, ulValue); - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long long llValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_longlong) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = *(unsigned long long*)&llValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long long ullValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulonglong) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - ModifyColumnData(stColIndex) = ullValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, double dValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_double) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - BOOST_STATIC_ASSERT(sizeof(double) == sizeof(unsigned long long)); - // cppcheck-suppress invalidPointerCast - ModifyColumnData(stColIndex) = *(unsigned long long*)&dValue; - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TString& strValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_string) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - if (strValue.IsEmpty()) - ModifyColumnData(stColIndex) = (unsigned long long)0; - else - { - wchar_t* pszBuffer = m_poolStrings.AllocForString(strValue.c_str()); - ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; - } - - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TSmartPath& pathValue) - { - if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_path) - throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); - - if (pathValue.IsEmpty()) - ModifyColumnData(stColIndex) = (unsigned long long)0; - else - { - wchar_t* pszBuffer = m_poolStrings.AllocForString(pathValue.ToString()); - ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; - } - - return *this; - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, bool bValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), bValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, short iValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned short uiValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, int iValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned int uiValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long lValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), lValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long ulValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), ulValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long long llValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long long llValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, double dValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), dValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TString& strValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), strValue); - } - - ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) - { - return SetValue(m_rColumns.GetColumnIndex(strColumnName), pathValue); - } - - void TSQLiteSerializerRowData::BindParamsAndExec(sqlite::TSQLiteStatement& tStatement) - { - using namespace sqlite; - - if (IsAdded()) - { - // exec query - int iColumn = 1; - BindParams(tStatement, iColumn); - - tStatement.Step(); - } - else if (HasAnyData()) - { - int iColumn = 1; - - size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); - - BindParams(tStatement, iColumn, stIDColumnIndex); - - // bind id as the last argument - tStatement.BindValue(iColumn++, GetDataForColumn(stIDColumnIndex)); - tStatement.Step(); - - int iChanges = tStatement.Changes(); - _ASSERTE(iChanges == 1); - if (iChanges != 1) - throw TSerializerException(eErr_InvalidData, _T("Update query did not update record in the database"), LOCATION); - } - } - - TString TSQLiteSerializerRowData::GetQuery(const TString& strContainerName) const - { - if (IsAdded()) - { - // prepare insert query - TString strQuery = boost::str(boost::wformat(L"INSERT INTO %1%(") % strContainerName).c_str(); - TString strParams; - - size_t stCount = m_rColumns.GetCount(); - for (size_t stIndex = 0; stIndex < stCount; ++stIndex) - { - strQuery += boost::str(boost::wformat(_T("%1%,")) % m_rColumns.GetColumnName(stIndex)).c_str(); - strParams += _T("?,"); - } - - strQuery.TrimRightSelf(_T(",")); - strQuery += _T(") VALUES("); - - strParams.TrimRightSelf(_T(",")); - strQuery += strParams; - strQuery += _T(")"); - - return strQuery; - } - else if (HasAnyData()) - { - // prepare update query - TString strQuery = boost::str(boost::wformat(L"UPDATE %1% SET ") % strContainerName).c_str(); - - size_t stCountOfAssignments = 0; - size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); - size_t stCount = m_rColumns.GetCount(); - for (size_t stIndex = 0; stIndex < stCount; ++stIndex) - { - if (stIndex != stIDColumnIndex && HasData(stIndex)) - { - strQuery += boost::str(boost::wformat(_T("%1%=?,")) % m_rColumns.GetColumnName(stIndex)).c_str(); - ++stCountOfAssignments; - } - } - - if (stCountOfAssignments == 0) - return TString(); - - strQuery.TrimRightSelf(_T(",")); - strQuery += _T(" WHERE id=?"); - - return strQuery; - } - else - return TString(); - } - - unsigned long long TSQLiteSerializerRowData::GetChangeIdentification() const - { - return GetDataHeader(); - } - - void TSQLiteSerializerRowData::MarkAsAdded() - { - // first bit is always the "added" bit - m_pPoolMemory[0] |= AddedBit; - } - - const unsigned long long& TSQLiteSerializerRowData::GetDataForColumn(size_t stColIndex) const - { - return (m_pPoolMemory[stColIndex + 1]); - } - - unsigned long long& TSQLiteSerializerRowData::ModifyColumnData(size_t stColIndex) - { - FreeColumnData(stColIndex); - - MarkColumnUsage(stColIndex, true); - return (m_pPoolMemory[stColIndex + 1]); - } - - void TSQLiteSerializerRowData::MarkColumnUsage(size_t stIndex, bool bUsed) - { - if (stIndex >= m_rColumns.GetCount()) - throw TSerializerException(eErr_BoundsExceeded, _T("Wrong column provided"), LOCATION); - - unsigned long long ullMask = 2ULL << stIndex; - if (bUsed) - m_pPoolMemory[0] |= ullMask; - else - m_pPoolMemory[0] &= ~ullMask; - } - - bool TSQLiteSerializerRowData::IsAdded() const - { - return (m_pPoolMemory[0] & AddedBit) != 0; - } - - bool TSQLiteSerializerRowData::HasAnyData() const - { - return GetDataHeader() != 0; - } - - bool TSQLiteSerializerRowData::HasData(size_t stColumnIndex) const - { - return (GetDataHeader() & (2ULL << stColumnIndex)) != 0; - } - - void TSQLiteSerializerRowData::BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t stSkipColumn) - { - size_t stCount = m_rColumns.GetCount(); - for (size_t stColumn = 0; stColumn < stCount; ++stColumn) - { - if (stColumn == stSkipColumn) - continue; - - if (HasData(stColumn)) - { - switch (m_rColumns.GetColumnType(stColumn)) - { - case IColumnsDefinition::eType_bool: - { - bool bValue = GetDataForColumn(stColumn) != 0 ? true : false; - DBTRACE1_D(_T("- param(bool): %ld\n"), bValue ? 1l : 0l); - tStatement.BindValue(iSQLiteColumnNumber++, bValue); - break; - } - - case IColumnsDefinition::eType_short: - { - short siValue = *(short*)(unsigned short*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(short): %d\n"), siValue); - tStatement.BindValue(iSQLiteColumnNumber++, siValue); - break; - } - - case IColumnsDefinition::eType_ushort: - { - unsigned short usiValue = (unsigned short)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ushort): %u\n"), usiValue); - tStatement.BindValue(iSQLiteColumnNumber++, usiValue); - break; - } - - case IColumnsDefinition::eType_int: - { - int iValue = *(int*)(unsigned int*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(int): %ld\n"), iValue); - tStatement.BindValue(iSQLiteColumnNumber++, iValue); - break; - } - - case IColumnsDefinition::eType_uint: - { - unsigned int uiValue = (unsigned int)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(uint): %lu\n"), uiValue); - tStatement.BindValue(iSQLiteColumnNumber++, uiValue); - break; - } - - case IColumnsDefinition::eType_long: - { - long lValue = *(long*)(unsigned long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(long): %ld\n"), lValue); - tStatement.BindValue(iSQLiteColumnNumber++, lValue); - break; - } - - case IColumnsDefinition::eType_ulong: - { - unsigned long ulValue = (unsigned long)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ulong): %lu\n"), ulValue); - tStatement.BindValue(iSQLiteColumnNumber++, ulValue); - break; - } - - case IColumnsDefinition::eType_longlong: - { - long long llValue = *(long long*)(unsigned long long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(llong): %I64d\n"), llValue); - tStatement.BindValue(iSQLiteColumnNumber++, llValue); - break; - } - - case IColumnsDefinition::eType_ulonglong: - { - unsigned long long ullValue = GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(ullong): %I64u\n"), ullValue); - tStatement.BindValue(iSQLiteColumnNumber++, ullValue); - break; - } - - case IColumnsDefinition::eType_double: - { - // cppcheck-suppress invalidPointerCast - double dValue = *(double*)(unsigned long long*)&GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(double): %f\n"), dValue); - tStatement.BindValue(iSQLiteColumnNumber++, dValue); - break; - } - - case IColumnsDefinition::eType_string: - { - const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(string): %s\n"), pszValue ? pszValue : _T("")); - tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? pszValue : _T("")); - break; - } - - case IColumnsDefinition::eType_path: - { - const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); - DBTRACE1_D(_T("- param(path): %s\n"), pszValue ? pszValue : _T("")); - tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? PathFromString(pszValue) : TSmartPath()); - break; - } - - default: - throw TSerializerException(eErr_InvalidArgument, _T("Invalid type"), LOCATION); - } - } - } - } - - unsigned long long TSQLiteSerializerRowData::GetDataHeader() const - { - return m_pPoolMemory[0]; - } - - void TSQLiteSerializerRowData::FreeColumnData(size_t stColumnID) - { - if (!HasData(stColumnID)) - return; - - switch (m_rColumns.GetColumnType(stColumnID)) - { - case IColumnsDefinition::eType_path: - case IColumnsDefinition::eType_string: - { - unsigned long long& ullColumnData = m_pPoolMemory[stColumnID + 1]; - ullColumnData = 0ULL; - - break; - } - } - } - - void TSQLiteSerializerRowData::FreeAllColumnData() - { - size_t stCount = m_rColumns.GetCount(); - for (size_t stColumn = 0; stColumn < stCount; ++stColumn) - { - FreeColumnData(stColumn); - } - } - - TSQLiteSerializerRowData& TSQLiteSerializerRowData::operator=(const TSQLiteSerializerRowData& rSrc) - { - m_pPoolMemory = rSrc.m_pPoolMemory; - - return *this; - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteSerializerRowData.h" +#include "TSQLiteStatement.h" +#include +#include "TSerializerException.h" +#include "ErrorCodes.h" +#include "SerializerTrace.h" +#include "TPlainStringPool.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + TSQLiteSerializerRowData::TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings) : + m_rColumns(rColumnDefinition), + m_pPoolMemory(pPoolMemory), + m_poolStrings(poolStrings) + { + if (!m_pPoolMemory) + throw TSerializerException(eErr_InvalidArgument, _T("Null memory provided"), LOCATION); + if (rColumnDefinition.GetCount() > 63) + throw TSerializerException(eErr_InternalProblem, _T("Serializer supports up to 63 columns. If more is needed the block header needs to be increased."), LOCATION); + + // initialize memory + memset((void*)pPoolMemory, 0, stPoolMemorySizeInBytes); + + // set id + size_t stIDIndex = rColumnDefinition.GetColumnIndex(_T("id")); + InternalSetValue(stIDIndex, oidRowID); + + if (bAdded) + MarkAsAdded(); + } + + TSQLiteSerializerRowData::TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc) : + m_rColumns(rSrc.m_rColumns), + m_pPoolMemory(rSrc.m_pPoolMemory), + m_poolStrings(rSrc.m_poolStrings) + { + } + + TSQLiteSerializerRowData::~TSQLiteSerializerRowData() + { + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, bool bValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_bool) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (bValue ? 1ULL : 0ULL); + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, short siValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_short) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned short*)&siValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned short usiValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ushort) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)usiValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, int iValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_int) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned int*)&iValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned int uiValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_uint) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)uiValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long lValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_long) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)*(unsigned long*)&lValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::InternalSetValue(size_t stColIndex, unsigned long ulValue) + { + if(m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulong) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = (unsigned long long)ulValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long ulValue) + { + InternalSetValue(stColIndex, ulValue); + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, long long llValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_longlong) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = *(unsigned long long*)&llValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, unsigned long long ullValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_ulonglong) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + ModifyColumnData(stColIndex) = ullValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, double dValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_double) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + BOOST_STATIC_ASSERT(sizeof(double) == sizeof(unsigned long long)); + // cppcheck-suppress invalidPointerCast + ModifyColumnData(stColIndex) = *(unsigned long long*)&dValue; + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TString& strValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_string) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + if (strValue.IsEmpty()) + ModifyColumnData(stColIndex) = (unsigned long long)0; + else + { + wchar_t* pszBuffer = m_poolStrings.AllocForString(strValue.c_str()); + ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; + } + + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(size_t stColIndex, const TSmartPath& pathValue) + { + if (m_rColumns.GetColumnType(stColIndex) != IColumnsDefinition::eType_path) + throw TSerializerException(eErr_InvalidArgument, _T("Invalid argument type provided"), LOCATION); + + if (pathValue.IsEmpty()) + ModifyColumnData(stColIndex) = (unsigned long long)0; + else + { + wchar_t* pszBuffer = m_poolStrings.AllocForString(pathValue.ToString()); + ModifyColumnData(stColIndex) = (unsigned long long)(void*)pszBuffer; + } + + return *this; + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, bool bValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), bValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, short iValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned short uiValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, int iValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), iValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned int uiValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), uiValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long lValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), lValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long ulValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), ulValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, long long llValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, unsigned long long llValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), llValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, double dValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), dValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TString& strValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), strValue); + } + + ISerializerRowData& TSQLiteSerializerRowData::SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue) + { + return SetValue(m_rColumns.GetColumnIndex(strColumnName), pathValue); + } + + void TSQLiteSerializerRowData::BindParamsAndExec(sqlite::TSQLiteStatement& tStatement) + { + using namespace sqlite; + + if (IsAdded()) + { + // exec query + int iColumn = 1; + BindParams(tStatement, iColumn); + + tStatement.Step(); + } + else if (HasAnyData()) + { + int iColumn = 1; + + size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); + + BindParams(tStatement, iColumn, stIDColumnIndex); + + // bind id as the last argument + tStatement.BindValue(iColumn++, GetDataForColumn(stIDColumnIndex)); + tStatement.Step(); + + int iChanges = tStatement.Changes(); + _ASSERTE(iChanges == 1); + if (iChanges != 1) + throw TSerializerException(eErr_InvalidData, _T("Update query did not update record in the database"), LOCATION); + } + } + + TString TSQLiteSerializerRowData::GetQuery(const TString& strContainerName) const + { + if (IsAdded()) + { + // prepare insert query + TString strQuery = boost::str(boost::wformat(L"INSERT INTO %1%(") % strContainerName).c_str(); + TString strParams; + + size_t stCount = m_rColumns.GetCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) + { + strQuery += boost::str(boost::wformat(_T("%1%,")) % m_rColumns.GetColumnName(stIndex)).c_str(); + strParams += _T("?,"); + } + + strQuery.TrimRightSelf(_T(",")); + strQuery += _T(") VALUES("); + + strParams.TrimRightSelf(_T(",")); + strQuery += strParams; + strQuery += _T(")"); + + return strQuery; + } + else if (HasAnyData()) + { + // prepare update query + TString strQuery = boost::str(boost::wformat(L"UPDATE %1% SET ") % strContainerName).c_str(); + + size_t stCountOfAssignments = 0; + size_t stIDColumnIndex = m_rColumns.GetColumnIndex(_T("id")); + size_t stCount = m_rColumns.GetCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) + { + if (stIndex != stIDColumnIndex && HasData(stIndex)) + { + strQuery += boost::str(boost::wformat(_T("%1%=?,")) % m_rColumns.GetColumnName(stIndex)).c_str(); + ++stCountOfAssignments; + } + } + + if (stCountOfAssignments == 0) + return TString(); + + strQuery.TrimRightSelf(_T(",")); + strQuery += _T(" WHERE id=?"); + + return strQuery; + } + else + return TString(); + } + + unsigned long long TSQLiteSerializerRowData::GetChangeIdentification() const + { + return GetDataHeader(); + } + + void TSQLiteSerializerRowData::MarkAsAdded() + { + // first bit is always the "added" bit + m_pPoolMemory[0] |= AddedBit; + } + + const unsigned long long& TSQLiteSerializerRowData::GetDataForColumn(size_t stColIndex) const + { + return (m_pPoolMemory[stColIndex + 1]); + } + + unsigned long long& TSQLiteSerializerRowData::ModifyColumnData(size_t stColIndex) + { + FreeColumnData(stColIndex); + + MarkColumnUsage(stColIndex, true); + return (m_pPoolMemory[stColIndex + 1]); + } + + void TSQLiteSerializerRowData::MarkColumnUsage(size_t stIndex, bool bUsed) + { + if (stIndex >= m_rColumns.GetCount()) + throw TSerializerException(eErr_BoundsExceeded, _T("Wrong column provided"), LOCATION); + + unsigned long long ullMask = 2ULL << stIndex; + if (bUsed) + m_pPoolMemory[0] |= ullMask; + else + m_pPoolMemory[0] &= ~ullMask; + } + + bool TSQLiteSerializerRowData::IsAdded() const + { + return (m_pPoolMemory[0] & AddedBit) != 0; + } + + bool TSQLiteSerializerRowData::HasAnyData() const + { + return GetDataHeader() != 0; + } + + bool TSQLiteSerializerRowData::HasData(size_t stColumnIndex) const + { + return (GetDataHeader() & (2ULL << stColumnIndex)) != 0; + } + + void TSQLiteSerializerRowData::BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t stSkipColumn) + { + size_t stCount = m_rColumns.GetCount(); + for (size_t stColumn = 0; stColumn < stCount; ++stColumn) + { + if (stColumn == stSkipColumn) + continue; + + if (HasData(stColumn)) + { + switch (m_rColumns.GetColumnType(stColumn)) + { + case IColumnsDefinition::eType_bool: + { + bool bValue = GetDataForColumn(stColumn) != 0 ? true : false; + DBTRACE1_D(_T("- param(bool): %ld\n"), bValue ? 1l : 0l); + tStatement.BindValue(iSQLiteColumnNumber++, bValue); + break; + } + + case IColumnsDefinition::eType_short: + { + short siValue = *(short*)(unsigned short*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(short): %d\n"), siValue); + tStatement.BindValue(iSQLiteColumnNumber++, siValue); + break; + } + + case IColumnsDefinition::eType_ushort: + { + unsigned short usiValue = (unsigned short)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ushort): %u\n"), usiValue); + tStatement.BindValue(iSQLiteColumnNumber++, usiValue); + break; + } + + case IColumnsDefinition::eType_int: + { + int iValue = *(int*)(unsigned int*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(int): %ld\n"), iValue); + tStatement.BindValue(iSQLiteColumnNumber++, iValue); + break; + } + + case IColumnsDefinition::eType_uint: + { + unsigned int uiValue = (unsigned int)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(uint): %lu\n"), uiValue); + tStatement.BindValue(iSQLiteColumnNumber++, uiValue); + break; + } + + case IColumnsDefinition::eType_long: + { + long lValue = *(long*)(unsigned long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(long): %ld\n"), lValue); + tStatement.BindValue(iSQLiteColumnNumber++, lValue); + break; + } + + case IColumnsDefinition::eType_ulong: + { + unsigned long ulValue = (unsigned long)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ulong): %lu\n"), ulValue); + tStatement.BindValue(iSQLiteColumnNumber++, ulValue); + break; + } + + case IColumnsDefinition::eType_longlong: + { + long long llValue = *(long long*)(unsigned long long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(llong): %I64d\n"), llValue); + tStatement.BindValue(iSQLiteColumnNumber++, llValue); + break; + } + + case IColumnsDefinition::eType_ulonglong: + { + unsigned long long ullValue = GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(ullong): %I64u\n"), ullValue); + tStatement.BindValue(iSQLiteColumnNumber++, ullValue); + break; + } + + case IColumnsDefinition::eType_double: + { + // cppcheck-suppress invalidPointerCast + double dValue = *(double*)(unsigned long long*)&GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(double): %f\n"), dValue); + tStatement.BindValue(iSQLiteColumnNumber++, dValue); + break; + } + + case IColumnsDefinition::eType_string: + { + const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(string): %s\n"), pszValue ? pszValue : _T("")); + tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? pszValue : _T("")); + break; + } + + case IColumnsDefinition::eType_path: + { + const wchar_t* pszValue = (const wchar_t*)(unsigned long long*)GetDataForColumn(stColumn); + DBTRACE1_D(_T("- param(path): %s\n"), pszValue ? pszValue : _T("")); + tStatement.BindValue(iSQLiteColumnNumber++, pszValue ? PathFromString(pszValue) : TSmartPath()); + break; + } + + default: + throw TSerializerException(eErr_InvalidArgument, _T("Invalid type"), LOCATION); + } + } + } + } + + unsigned long long TSQLiteSerializerRowData::GetDataHeader() const + { + return m_pPoolMemory[0]; + } + + void TSQLiteSerializerRowData::FreeColumnData(size_t stColumnID) + { + if (!HasData(stColumnID)) + return; + + switch (m_rColumns.GetColumnType(stColumnID)) + { + case IColumnsDefinition::eType_path: + case IColumnsDefinition::eType_string: + { + unsigned long long& ullColumnData = m_pPoolMemory[stColumnID + 1]; + ullColumnData = 0ULL; + + break; + } + } + } + + void TSQLiteSerializerRowData::FreeAllColumnData() + { + size_t stCount = m_rColumns.GetCount(); + for (size_t stColumn = 0; stColumn < stCount; ++stColumn) + { + FreeColumnData(stColumn); + } + } + + TSQLiteSerializerRowData& TSQLiteSerializerRowData::operator=(const TSQLiteSerializerRowData& rSrc) + { + m_pPoolMemory = rSrc.m_pPoolMemory; + + return *this; + } +} Index: src/libchcore/TSQLiteSerializerRowData.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerRowData.h (.../TSQLiteSerializerRowData.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteSerializerRowData.h (.../TSQLiteSerializerRowData.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,108 +1,108 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESERIALIZERROWWRITER_H__ -#define __TSQLITESERIALIZERROWWRITER_H__ - -#include "libchcore.h" -#include "ISerializerRowData.h" -#include "TSQLiteColumnDefinition.h" -#include "ISerializerContainer.h" -#include "TSQLiteDatabase.h" -#include "TSQLiteStatement.h" -#include - -namespace chcore -{ - class TPlainStringPool; - - class LIBCHCORE_API TSQLiteSerializerRowData : public ISerializerRowData - { - private: - static const unsigned long long AddedBit = 1; - - private: - TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings); - - public: - TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc); - virtual ~TSQLiteSerializerRowData(); - - TSQLiteSerializerRowData& operator=(const TSQLiteSerializerRowData& rSrc); - - virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue); - virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue); - - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue); - virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue); - - TString GetQuery(const TString& strContainerName) const; - unsigned long long GetChangeIdentification() const; - - void BindParamsAndExec(sqlite::TSQLiteStatement& tStatement); - - private: - const unsigned long long& GetDataForColumn(size_t stColIndex) const; - unsigned long long GetDataHeader() const; - unsigned long long& ModifyColumnData(size_t stColIndex); - void FreeColumnData(size_t stColumnID); - void FreeAllColumnData(); - - void MarkAsAdded(); - bool IsAdded() const; - - bool HasAnyData() const; - void MarkColumnUsage(size_t stIndex, bool bUsed); - bool HasData(size_t stColumnIndex) const; - - void BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t bSkipColumn = (size_t)-1); - ISerializerRowData& InternalSetValue(size_t stColIndex, unsigned long ulValue); - - private: - unsigned long long* m_pPoolMemory; - - TSQLiteColumnsDefinition& m_rColumns; - TPlainStringPool& m_poolStrings; - - friend class TSQLiteSerializerContainer; - }; - - typedef std::shared_ptr TSQLiteSerializerRowDataPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESERIALIZERROWWRITER_H__ +#define __TSQLITESERIALIZERROWWRITER_H__ + +#include "libchcore.h" +#include "ISerializerRowData.h" +#include "TSQLiteColumnDefinition.h" +#include "ISerializerContainer.h" +#include "TSQLiteDatabase.h" +#include "TSQLiteStatement.h" +#include + +namespace chcore +{ + class TPlainStringPool; + + class LIBCHCORE_API TSQLiteSerializerRowData : public ISerializerRowData + { + private: + static const unsigned long long AddedBit = 1; + + private: + TSQLiteSerializerRowData(object_id_t oidRowID, TSQLiteColumnsDefinition& rColumnDefinition, bool bAdded, unsigned long long* pPoolMemory, size_t stPoolMemorySizeInBytes, TPlainStringPool& poolStrings); + + public: + TSQLiteSerializerRowData(const TSQLiteSerializerRowData& rSrc); + virtual ~TSQLiteSerializerRowData(); + + TSQLiteSerializerRowData& operator=(const TSQLiteSerializerRowData& rSrc); + + virtual ISerializerRowData& SetValue(size_t stColIndex, bool bValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, short iValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned short uiValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, int iValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned int uiValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, long lValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long ulValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, long long llValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, unsigned long long llValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, double dValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, const TString& strValue); + virtual ISerializerRowData& SetValue(size_t stColIndex, const TSmartPath& pathValue); + + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, bool bValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, short iValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned short uiValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, int iValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned int uiValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long lValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long ulValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, long long llValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, unsigned long long llValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, double dValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TString& strValue); + virtual ISerializerRowData& SetValue(const wchar_t* strColumnName, const TSmartPath& pathValue); + + TString GetQuery(const TString& strContainerName) const; + unsigned long long GetChangeIdentification() const; + + void BindParamsAndExec(sqlite::TSQLiteStatement& tStatement); + + private: + const unsigned long long& GetDataForColumn(size_t stColIndex) const; + unsigned long long GetDataHeader() const; + unsigned long long& ModifyColumnData(size_t stColIndex); + void FreeColumnData(size_t stColumnID); + void FreeAllColumnData(); + + void MarkAsAdded(); + bool IsAdded() const; + + bool HasAnyData() const; + void MarkColumnUsage(size_t stIndex, bool bUsed); + bool HasData(size_t stColumnIndex) const; + + void BindParams(sqlite::TSQLiteStatement &tStatement, int& iSQLiteColumnNumber, size_t bSkipColumn = (size_t)-1); + ISerializerRowData& InternalSetValue(size_t stColIndex, unsigned long ulValue); + + private: + unsigned long long* m_pPoolMemory; + + TSQLiteColumnsDefinition& m_rColumns; + TPlainStringPool& m_poolStrings; + + friend class TSQLiteSerializerContainer; + }; + + typedef std::shared_ptr TSQLiteSerializerRowDataPtr; +} + +#endif Index: src/libchcore/TSQLiteSerializerRowReader.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerRowReader.cpp (.../TSQLiteSerializerRowReader.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TSQLiteSerializerRowReader.cpp (.../TSQLiteSerializerRowReader.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,167 +1,167 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteSerializerRowReader.h" -#include -#include "TCoreException.h" -#include "ErrorCodes.h" -#include -#include "TSQLiteStatement.h" -#include "SerializerTrace.h" - -namespace chcore -{ - TSQLiteSerializerRowReader::TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName) : - m_spStatement(new sqlite::TSQLiteStatement(spDatabase)), - m_rColumns(rColumns), - m_bInitialized(false), - m_strContainerName(strContainerName) - { - if (m_strContainerName.IsEmpty()) - throw TCoreException(eErr_InvalidArgument, L"m_strContainerName", LOCATION); - } - - TSQLiteSerializerRowReader::~TSQLiteSerializerRowReader() - { - } - - bool TSQLiteSerializerRowReader::Next() - { - if (m_rColumns.IsEmpty()) - throw TCoreException(eErr_SerializeLoadError, L"m_rColumns is empty", LOCATION); - - if (!m_bInitialized) - { - // generate query to retrieve data from db - TString strQuery; - strQuery = boost::str(boost::wformat(L"SELECT %1% FROM %2% ORDER BY id") % m_rColumns.GetCommaSeparatedColumns().c_str() % m_strContainerName.c_str()).c_str(); - - DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); - m_spStatement->Prepare(strQuery.c_str()); - m_bInitialized = true; - } - - return m_spStatement->Step() == sqlite::TSQLiteStatement::eStep_HasRow; - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, bool& bValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), bValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, short& iValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), iValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned short& uiValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, int& iValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), iValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned int& uiValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long& lValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), lValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long& ulValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), ulValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long long& llValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), llValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long long& ullValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), ullValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, double& dValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), dValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TString& strValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), strValue); - } - - void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TSmartPath& pathValue) - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - m_spStatement->GetValue(GetColumnIndex(strColName), pathValue); - } - - int TSQLiteSerializerRowReader::GetColumnIndex(const TString& strColName) const - { - if (!m_bInitialized) - throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); - - size_t stColumn = m_rColumns.GetColumnIndex(strColName.c_str()); - return boost::numeric_cast(stColumn); - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteSerializerRowReader.h" +#include +#include "TCoreException.h" +#include "ErrorCodes.h" +#include +#include "TSQLiteStatement.h" +#include "SerializerTrace.h" + +namespace chcore +{ + TSQLiteSerializerRowReader::TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName) : + m_spStatement(new sqlite::TSQLiteStatement(spDatabase)), + m_rColumns(rColumns), + m_bInitialized(false), + m_strContainerName(strContainerName) + { + if (m_strContainerName.IsEmpty()) + throw TCoreException(eErr_InvalidArgument, L"m_strContainerName", LOCATION); + } + + TSQLiteSerializerRowReader::~TSQLiteSerializerRowReader() + { + } + + bool TSQLiteSerializerRowReader::Next() + { + if (m_rColumns.IsEmpty()) + throw TCoreException(eErr_SerializeLoadError, L"m_rColumns is empty", LOCATION); + + if (!m_bInitialized) + { + // generate query to retrieve data from db + TString strQuery; + strQuery = boost::str(boost::wformat(L"SELECT %1% FROM %2% ORDER BY id") % m_rColumns.GetCommaSeparatedColumns().c_str() % m_strContainerName.c_str()).c_str(); + + DBTRACE1_D(_T("Executing query: %s\n"), strQuery.c_str()); + m_spStatement->Prepare(strQuery.c_str()); + m_bInitialized = true; + } + + return m_spStatement->Step() == sqlite::TSQLiteStatement::eStep_HasRow; + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, bool& bValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), bValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, short& iValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), iValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned short& uiValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, int& iValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), iValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned int& uiValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), uiValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long& lValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), lValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long& ulValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), ulValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, long long& llValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), llValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, unsigned long long& ullValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), ullValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, double& dValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), dValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TString& strValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), strValue); + } + + void TSQLiteSerializerRowReader::GetValue(const TString& strColName, TSmartPath& pathValue) + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + m_spStatement->GetValue(GetColumnIndex(strColName), pathValue); + } + + int TSQLiteSerializerRowReader::GetColumnIndex(const TString& strColName) const + { + if (!m_bInitialized) + throw TCoreException(eErr_SerializeLoadError, L"Serializer not initialized", LOCATION); + + size_t stColumn = m_rColumns.GetColumnIndex(strColName.c_str()); + return boost::numeric_cast(stColumn); + } +} Index: src/libchcore/TSQLiteSerializerRowReader.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteSerializerRowReader.h (.../TSQLiteSerializerRowReader.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteSerializerRowReader.h (.../TSQLiteSerializerRowReader.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,70 +1,70 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESERIALIZERROWREADER_H__ -#define __TSQLITESERIALIZERROWREADER_H__ - -#include "libchcore.h" -#include "ISerializerRowReader.h" -#include "TSQLiteStatement.h" -#include "TSQLiteColumnDefinition.h" - -namespace chcore -{ - class LIBCHCORE_API TSQLiteSerializerRowReader : public ISerializerRowReader - { - private: - TSQLiteSerializerRowReader(const TSQLiteSerializerRowReader&); - TSQLiteSerializerRowReader& operator=(const TSQLiteSerializerRowReader&); - - public: - TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName); - virtual ~TSQLiteSerializerRowReader(); - - virtual bool Next(); - - virtual void GetValue(const TString& strColName, bool& bValue); - virtual void GetValue(const TString& strColName, short& iValue); - virtual void GetValue(const TString& strColName, unsigned short& uiValue); - virtual void GetValue(const TString& strColName, int& iValue); - virtual void GetValue(const TString& strColName, unsigned int& uiValue); - virtual void GetValue(const TString& strColName, long& lValue); - virtual void GetValue(const TString& strColName, unsigned long& ulValue); - virtual void GetValue(const TString& strColName, long long& llValue); - virtual void GetValue(const TString& strColName, unsigned long long& ullValue); - virtual void GetValue(const TString& strColName, double& dValue); - virtual void GetValue(const TString& strColName, TString& strValue); - virtual void GetValue(const TString& strColName, TSmartPath& pathValue); - - private: - int GetColumnIndex(const TString& strColName) const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - bool m_bInitialized; - sqlite::TSQLiteStatementPtr m_spStatement; - TSQLiteColumnsDefinition& m_rColumns; - TString m_strContainerName; -#pragma warning(pop) - }; - - typedef std::shared_ptr TSQLiteSerializerRowReaderPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESERIALIZERROWREADER_H__ +#define __TSQLITESERIALIZERROWREADER_H__ + +#include "libchcore.h" +#include "ISerializerRowReader.h" +#include "TSQLiteStatement.h" +#include "TSQLiteColumnDefinition.h" + +namespace chcore +{ + class LIBCHCORE_API TSQLiteSerializerRowReader : public ISerializerRowReader + { + private: + TSQLiteSerializerRowReader(const TSQLiteSerializerRowReader&); + TSQLiteSerializerRowReader& operator=(const TSQLiteSerializerRowReader&); + + public: + TSQLiteSerializerRowReader(const sqlite::TSQLiteDatabasePtr& spDatabase, TSQLiteColumnsDefinition& rColumns, const TString& strContainerName); + virtual ~TSQLiteSerializerRowReader(); + + virtual bool Next(); + + virtual void GetValue(const TString& strColName, bool& bValue); + virtual void GetValue(const TString& strColName, short& iValue); + virtual void GetValue(const TString& strColName, unsigned short& uiValue); + virtual void GetValue(const TString& strColName, int& iValue); + virtual void GetValue(const TString& strColName, unsigned int& uiValue); + virtual void GetValue(const TString& strColName, long& lValue); + virtual void GetValue(const TString& strColName, unsigned long& ulValue); + virtual void GetValue(const TString& strColName, long long& llValue); + virtual void GetValue(const TString& strColName, unsigned long long& ullValue); + virtual void GetValue(const TString& strColName, double& dValue); + virtual void GetValue(const TString& strColName, TString& strValue); + virtual void GetValue(const TString& strColName, TSmartPath& pathValue); + + private: + int GetColumnIndex(const TString& strColName) const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + bool m_bInitialized; + sqlite::TSQLiteStatementPtr m_spStatement; + TSQLiteColumnsDefinition& m_rColumns; + TString m_strContainerName; +#pragma warning(pop) + }; + + typedef std::shared_ptr TSQLiteSerializerRowReaderPtr; +} + +#endif Index: src/libchcore/TSQLiteStatement.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteStatement.cpp (.../TSQLiteStatement.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/TSQLiteStatement.cpp (.../TSQLiteStatement.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,350 +1,350 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteStatement.h" -#include "sqlite3/sqlite3.h" -#include "ErrorCodes.h" -#include "TSQLiteException.h" -#include -#include "SerializerTrace.h" - -namespace chcore -{ - namespace sqlite - { - TSQLiteStatement::TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase) : - m_pStatement(nullptr), - m_spDatabase(spDatabase), - m_bHasRow(false) - { - if (!m_spDatabase) - throw TSQLiteException(eErr_InvalidArgument, 0, _T("Invalid database provided"), LOCATION); - } - - TSQLiteStatement::~TSQLiteStatement() - { - int iResult = sqlite3_finalize(m_pStatement); - if(iResult != SQLITE_OK) - { - DBTRACE1(L"sqlite3_finalize failed with error code: %d", iResult); - } - } - - void TSQLiteStatement::Close() - { - if (m_pStatement != nullptr) - { - int iResult = sqlite3_finalize(m_pStatement); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteFinalizeError, iResult, _T("Cannot finalize statement"), LOCATION); - m_pStatement = nullptr; - } - m_bHasRow = false; - } - - void TSQLiteStatement::Prepare(PCWSTR pszQuery) - { - Close(); - - int iResult = sqlite3_prepare16_v2((sqlite3*)m_spDatabase->GetHandle(), pszQuery, -1, &m_pStatement, nullptr); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLitePrepareError, iResult, (PCTSTR)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle()), LOCATION); - } - - TSQLiteStatement::EStepResult TSQLiteStatement::Step() - { - m_bHasRow = false; - - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_step(m_pStatement); - switch (iResult) - { - case SQLITE_ROW: - m_bHasRow = true; - return eStep_HasRow; - case SQLITE_OK: - case SQLITE_DONE: - Reset(); - return eStep_Finished; - default: - { - const wchar_t* pszErrMsg = (const wchar_t*)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle()); - const size_t stMaxSize = 1024; - wchar_t szText[stMaxSize]; - _snwprintf_s(szText, stMaxSize, _TRUNCATE, L"Cannot perform step on the statement. SQLite reported error: %s", pszErrMsg); - throw TSQLiteException(eErr_SQLiteStepError, iResult, szText, LOCATION); - } - } - } - - int TSQLiteStatement::Changes() - { - return sqlite3_changes((sqlite3*)m_spDatabase->GetHandle()); - } - - void TSQLiteStatement::BindValue(int iColumn, bool bValue) - { - BindValue(iColumn, bValue ? 1 : 0); - } - - void TSQLiteStatement::BindValue(int iColumn, short siValue) - { - BindValue(iColumn, (int)siValue); - } - - void TSQLiteStatement::BindValue(int iColumn, unsigned short usiValue) - { - BindValue(iColumn, (unsigned int)usiValue); - } - - void TSQLiteStatement::BindValue(int iColumn, int iValue) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_bind_int(m_pStatement, iColumn, iValue); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); - } - - void TSQLiteStatement::BindValue(int iColumn, unsigned int uiValue) - { - BindValue(iColumn, *(int*)&uiValue); - } - - void TSQLiteStatement::BindValue(int iColumn, long lValue) - { - BindValue(iColumn, boost::numeric_cast(lValue)); - } - - void TSQLiteStatement::BindValue(int iColumn, unsigned long ulValue) - { - BindValue(iColumn, boost::numeric_cast(ulValue)); - } - - void TSQLiteStatement::BindValue(int iColumn, long long llValue) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_bind_int64(m_pStatement, iColumn, llValue); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); - } - - void TSQLiteStatement::BindValue(int iColumn, unsigned long long ullValue) - { - BindValue(iColumn, *(long long*)&ullValue); - } - - void TSQLiteStatement::BindValue(int iColumn, double dValue) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_bind_double(m_pStatement, iColumn, dValue); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); - } - - void TSQLiteStatement::BindValue(int iColumn, PCTSTR pszText) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_bind_text16(m_pStatement, iColumn, pszText, -1, SQLITE_TRANSIENT); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); - } - - void TSQLiteStatement::BindValue(int iColumn, const TString& strText) - { - BindValue(iColumn, strText.c_str()); - } - - void TSQLiteStatement::BindValue(int iColumn, const TSmartPath& path) - { - BindValue(iColumn, path.ToString()); - } - - bool TSQLiteStatement::GetBool(int iCol) - { - return GetInt(iCol) != 0; - } - - short TSQLiteStatement::GetShort(int iCol) - { - return boost::numeric_cast(GetInt(iCol)); - } - - unsigned short TSQLiteStatement::GetUShort(int iCol) - { - return boost::numeric_cast(GetUInt(iCol)); - } - - int TSQLiteStatement::GetInt(int iCol) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - if (!m_bHasRow) - throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); - - return sqlite3_column_int(m_pStatement, iCol); - } - - unsigned int TSQLiteStatement::GetUInt(int iCol) - { - int iVal = GetInt(iCol); - return *(unsigned int*)&iVal; - } - - long TSQLiteStatement::GetLong(int iCol) - { - return boost::numeric_cast(GetInt(iCol)); - } - - unsigned long TSQLiteStatement::GetULong(int iCol) - { - return boost::numeric_cast(GetUInt(iCol)); - } - - long long TSQLiteStatement::GetInt64(int iCol) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - if (!m_bHasRow) - throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); - - return sqlite3_column_int64(m_pStatement, iCol); - } - - unsigned long long TSQLiteStatement::GetUInt64(int iCol) - { - long long llVal = GetInt64(iCol); - return *(unsigned long long*)&llVal; - } - - double TSQLiteStatement::GetDouble(int iCol) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - if (!m_bHasRow) - throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); - - return sqlite3_column_double(m_pStatement, iCol); - } - - TString TSQLiteStatement::GetText(int iCol) - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - if (!m_bHasRow) - throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); - - return TString((const wchar_t*)sqlite3_column_text16(m_pStatement, iCol)); - } - - TSmartPath TSQLiteStatement::GetPath(int iCol) - { - return PathFromWString(GetText(iCol)); - } - - void TSQLiteStatement::ClearBindings() - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_clear_bindings(m_pStatement); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot clear bindings"), LOCATION); - } - - void TSQLiteStatement::Reset() - { - if (!m_pStatement) - throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); - - int iResult = sqlite3_reset(m_pStatement); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot reset statement"), LOCATION); - } - - void TSQLiteStatement::GetValue(int iCol, bool& bValue) - { - bValue = GetBool(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, short& iValue) - { - iValue = GetShort(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, unsigned short& uiValue) - { - uiValue = GetUShort(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, int& iValue) - { - iValue = GetInt(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, unsigned int& uiValue) - { - uiValue = GetUInt(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, long& lValue) - { - lValue = GetLong(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, unsigned long& ulValue) - { - ulValue = GetULong(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, long long& llValue) - { - llValue = GetInt64(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, unsigned long long& ullValue) - { - ullValue = GetUInt64(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, double& dValue) - { - dValue = GetDouble(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, TString& strValue) - { - strValue = GetText(iCol); - } - - void TSQLiteStatement::GetValue(int iCol, TSmartPath& pathValue) - { - pathValue = GetPath(iCol); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteStatement.h" +#include "sqlite3/sqlite3.h" +#include "ErrorCodes.h" +#include "TSQLiteException.h" +#include +#include "SerializerTrace.h" + +namespace chcore +{ + namespace sqlite + { + TSQLiteStatement::TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase) : + m_pStatement(nullptr), + m_spDatabase(spDatabase), + m_bHasRow(false) + { + if (!m_spDatabase) + throw TSQLiteException(eErr_InvalidArgument, 0, _T("Invalid database provided"), LOCATION); + } + + TSQLiteStatement::~TSQLiteStatement() + { + int iResult = sqlite3_finalize(m_pStatement); + if(iResult != SQLITE_OK) + { + DBTRACE1(L"sqlite3_finalize failed with error code: %d", iResult); + } + } + + void TSQLiteStatement::Close() + { + if (m_pStatement != nullptr) + { + int iResult = sqlite3_finalize(m_pStatement); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteFinalizeError, iResult, _T("Cannot finalize statement"), LOCATION); + m_pStatement = nullptr; + } + m_bHasRow = false; + } + + void TSQLiteStatement::Prepare(PCWSTR pszQuery) + { + Close(); + + int iResult = sqlite3_prepare16_v2((sqlite3*)m_spDatabase->GetHandle(), pszQuery, -1, &m_pStatement, nullptr); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLitePrepareError, iResult, (PCTSTR)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle()), LOCATION); + } + + TSQLiteStatement::EStepResult TSQLiteStatement::Step() + { + m_bHasRow = false; + + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_step(m_pStatement); + switch (iResult) + { + case SQLITE_ROW: + m_bHasRow = true; + return eStep_HasRow; + case SQLITE_OK: + case SQLITE_DONE: + Reset(); + return eStep_Finished; + default: + { + const wchar_t* pszErrMsg = (const wchar_t*)sqlite3_errmsg16((sqlite3*)m_spDatabase->GetHandle()); + const size_t stMaxSize = 1024; + wchar_t szText[stMaxSize]; + _snwprintf_s(szText, stMaxSize, _TRUNCATE, L"Cannot perform step on the statement. SQLite reported error: %s", pszErrMsg); + throw TSQLiteException(eErr_SQLiteStepError, iResult, szText, LOCATION); + } + } + } + + int TSQLiteStatement::Changes() + { + return sqlite3_changes((sqlite3*)m_spDatabase->GetHandle()); + } + + void TSQLiteStatement::BindValue(int iColumn, bool bValue) + { + BindValue(iColumn, bValue ? 1 : 0); + } + + void TSQLiteStatement::BindValue(int iColumn, short siValue) + { + BindValue(iColumn, (int)siValue); + } + + void TSQLiteStatement::BindValue(int iColumn, unsigned short usiValue) + { + BindValue(iColumn, (unsigned int)usiValue); + } + + void TSQLiteStatement::BindValue(int iColumn, int iValue) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_bind_int(m_pStatement, iColumn, iValue); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); + } + + void TSQLiteStatement::BindValue(int iColumn, unsigned int uiValue) + { + BindValue(iColumn, *(int*)&uiValue); + } + + void TSQLiteStatement::BindValue(int iColumn, long lValue) + { + BindValue(iColumn, boost::numeric_cast(lValue)); + } + + void TSQLiteStatement::BindValue(int iColumn, unsigned long ulValue) + { + BindValue(iColumn, boost::numeric_cast(ulValue)); + } + + void TSQLiteStatement::BindValue(int iColumn, long long llValue) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_bind_int64(m_pStatement, iColumn, llValue); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); + } + + void TSQLiteStatement::BindValue(int iColumn, unsigned long long ullValue) + { + BindValue(iColumn, *(long long*)&ullValue); + } + + void TSQLiteStatement::BindValue(int iColumn, double dValue) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_bind_double(m_pStatement, iColumn, dValue); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); + } + + void TSQLiteStatement::BindValue(int iColumn, PCTSTR pszText) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_bind_text16(m_pStatement, iColumn, pszText, -1, SQLITE_TRANSIENT); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot bind a parameter"), LOCATION); + } + + void TSQLiteStatement::BindValue(int iColumn, const TString& strText) + { + BindValue(iColumn, strText.c_str()); + } + + void TSQLiteStatement::BindValue(int iColumn, const TSmartPath& path) + { + BindValue(iColumn, path.ToString()); + } + + bool TSQLiteStatement::GetBool(int iCol) + { + return GetInt(iCol) != 0; + } + + short TSQLiteStatement::GetShort(int iCol) + { + return boost::numeric_cast(GetInt(iCol)); + } + + unsigned short TSQLiteStatement::GetUShort(int iCol) + { + return boost::numeric_cast(GetUInt(iCol)); + } + + int TSQLiteStatement::GetInt(int iCol) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + if (!m_bHasRow) + throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); + + return sqlite3_column_int(m_pStatement, iCol); + } + + unsigned int TSQLiteStatement::GetUInt(int iCol) + { + int iVal = GetInt(iCol); + return *(unsigned int*)&iVal; + } + + long TSQLiteStatement::GetLong(int iCol) + { + return boost::numeric_cast(GetInt(iCol)); + } + + unsigned long TSQLiteStatement::GetULong(int iCol) + { + return boost::numeric_cast(GetUInt(iCol)); + } + + long long TSQLiteStatement::GetInt64(int iCol) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + if (!m_bHasRow) + throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); + + return sqlite3_column_int64(m_pStatement, iCol); + } + + unsigned long long TSQLiteStatement::GetUInt64(int iCol) + { + long long llVal = GetInt64(iCol); + return *(unsigned long long*)&llVal; + } + + double TSQLiteStatement::GetDouble(int iCol) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + if (!m_bHasRow) + throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); + + return sqlite3_column_double(m_pStatement, iCol); + } + + TString TSQLiteStatement::GetText(int iCol) + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + if (!m_bHasRow) + throw TSQLiteException(eErr_SQLiteNoRowAvailable, 0, _T("No row available"), LOCATION); + + return TString((const wchar_t*)sqlite3_column_text16(m_pStatement, iCol)); + } + + TSmartPath TSQLiteStatement::GetPath(int iCol) + { + return PathFromWString(GetText(iCol)); + } + + void TSQLiteStatement::ClearBindings() + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_clear_bindings(m_pStatement); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot clear bindings"), LOCATION); + } + + void TSQLiteStatement::Reset() + { + if (!m_pStatement) + throw TSQLiteException(eErr_SQLiteStatementNotPrepared, 0, _T("Tried to step on unprepared statement"), LOCATION); + + int iResult = sqlite3_reset(m_pStatement); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteBindError, iResult, _T("Cannot reset statement"), LOCATION); + } + + void TSQLiteStatement::GetValue(int iCol, bool& bValue) + { + bValue = GetBool(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, short& iValue) + { + iValue = GetShort(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, unsigned short& uiValue) + { + uiValue = GetUShort(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, int& iValue) + { + iValue = GetInt(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, unsigned int& uiValue) + { + uiValue = GetUInt(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, long& lValue) + { + lValue = GetLong(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, unsigned long& ulValue) + { + ulValue = GetULong(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, long long& llValue) + { + llValue = GetInt64(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, unsigned long long& ullValue) + { + ullValue = GetUInt64(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, double& dValue) + { + dValue = GetDouble(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, TString& strValue) + { + strValue = GetText(iCol); + } + + void TSQLiteStatement::GetValue(int iCol, TSmartPath& pathValue) + { + pathValue = GetPath(iCol); + } + } +} Index: src/libchcore/TSQLiteStatement.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteStatement.h (.../TSQLiteStatement.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteStatement.h (.../TSQLiteStatement.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,106 +1,106 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITESTATEMENT_H__ -#define __TSQLITESTATEMENT_H__ - -#include "TSQLiteDatabase.h" -#include "TString.h" - -struct sqlite3_stmt; - -namespace chcore -{ - namespace sqlite - { - typedef std::shared_ptr SQLiteStatementHandle; - - class TSQLiteStatement - { - public: - enum EStepResult - { - eStep_Finished, - eStep_HasRow - }; - - public: - explicit TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase); - ~TSQLiteStatement(); - - void Close(); - - void Prepare(PCTSTR pszQuery); - - void BindValue(int iColumn, bool bValue); - void BindValue(int iColumn, short siValue); - void BindValue(int iColumn, unsigned short usiValue); - void BindValue(int iColumn, int iValue); - void BindValue(int iColumn, unsigned int uiValue); - void BindValue(int iColumn, long lValue); - void BindValue(int iColumn, unsigned long ulValue); - void BindValue(int iColumn, long long llValue); - void BindValue(int iColumn, unsigned long long ullValue); - void BindValue(int iColumn, double dValue); - void BindValue(int iColumn, PCTSTR pszText); - void BindValue(int iColumn, const TString& strText); - void BindValue(int iColumn, const TSmartPath& path); - - void ClearBindings(); - - EStepResult Step(); - int Changes(); - void Reset(); - - bool GetBool(int iCol); - short GetShort(int iCol); - unsigned short GetUShort(int iCol); - int GetInt(int iCol); - unsigned int GetUInt(int iCol); - long GetLong(int iCol); - unsigned long GetULong(int iCol); - long long GetInt64(int iCol); - unsigned long long GetUInt64(int iCol); - double GetDouble(int iCol); - TString GetText(int iCol); - TSmartPath GetPath(int iCol); - - void GetValue(int iCol, bool& bValue); - void GetValue(int iCol, short& iValue); - void GetValue(int iCol, unsigned short& uiValue); - void GetValue(int iCol, int& iValue); - void GetValue(int iCol, unsigned int& uiValue); - void GetValue(int iCol, long& lValue); - void GetValue(int iCol, unsigned long& ulValue); - void GetValue(int iCol, long long& llValue); - void GetValue(int iCol, unsigned long long& ullValue); - void GetValue(int iCol, double& dValue); - void GetValue(int iCol, TString& strValue); - void GetValue(int iCol, TSmartPath& pathValue); - - private: - sqlite3_stmt* m_pStatement; - TSQLiteDatabasePtr m_spDatabase; - bool m_bHasRow; - }; - - typedef std::shared_ptr TSQLiteStatementPtr; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITESTATEMENT_H__ +#define __TSQLITESTATEMENT_H__ + +#include "TSQLiteDatabase.h" +#include "TString.h" + +struct sqlite3_stmt; + +namespace chcore +{ + namespace sqlite + { + typedef std::shared_ptr SQLiteStatementHandle; + + class TSQLiteStatement + { + public: + enum EStepResult + { + eStep_Finished, + eStep_HasRow + }; + + public: + explicit TSQLiteStatement(const TSQLiteDatabasePtr& spDatabase); + ~TSQLiteStatement(); + + void Close(); + + void Prepare(PCTSTR pszQuery); + + void BindValue(int iColumn, bool bValue); + void BindValue(int iColumn, short siValue); + void BindValue(int iColumn, unsigned short usiValue); + void BindValue(int iColumn, int iValue); + void BindValue(int iColumn, unsigned int uiValue); + void BindValue(int iColumn, long lValue); + void BindValue(int iColumn, unsigned long ulValue); + void BindValue(int iColumn, long long llValue); + void BindValue(int iColumn, unsigned long long ullValue); + void BindValue(int iColumn, double dValue); + void BindValue(int iColumn, PCTSTR pszText); + void BindValue(int iColumn, const TString& strText); + void BindValue(int iColumn, const TSmartPath& path); + + void ClearBindings(); + + EStepResult Step(); + int Changes(); + void Reset(); + + bool GetBool(int iCol); + short GetShort(int iCol); + unsigned short GetUShort(int iCol); + int GetInt(int iCol); + unsigned int GetUInt(int iCol); + long GetLong(int iCol); + unsigned long GetULong(int iCol); + long long GetInt64(int iCol); + unsigned long long GetUInt64(int iCol); + double GetDouble(int iCol); + TString GetText(int iCol); + TSmartPath GetPath(int iCol); + + void GetValue(int iCol, bool& bValue); + void GetValue(int iCol, short& iValue); + void GetValue(int iCol, unsigned short& uiValue); + void GetValue(int iCol, int& iValue); + void GetValue(int iCol, unsigned int& uiValue); + void GetValue(int iCol, long& lValue); + void GetValue(int iCol, unsigned long& ulValue); + void GetValue(int iCol, long long& llValue); + void GetValue(int iCol, unsigned long long& ullValue); + void GetValue(int iCol, double& dValue); + void GetValue(int iCol, TString& strValue); + void GetValue(int iCol, TSmartPath& pathValue); + + private: + sqlite3_stmt* m_pStatement; + TSQLiteDatabasePtr m_spDatabase; + bool m_bHasRow; + }; + + typedef std::shared_ptr TSQLiteStatementPtr; + } +} + +#endif Index: src/libchcore/TSQLiteTaskManagerSchema.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTaskManagerSchema.cpp (.../TSQLiteTaskManagerSchema.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSQLiteTaskManagerSchema.cpp (.../TSQLiteTaskManagerSchema.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,68 +1,68 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteTaskManagerSchema.h" -#include "TSQLiteTransaction.h" -#include "TSerializerVersion.h" -#include "TSQLiteStatement.h" - -namespace chcore -{ - using namespace sqlite; - - TSQLiteTaskManagerSchema::TSQLiteTaskManagerSchema() - { - } - - TSQLiteTaskManagerSchema::~TSQLiteTaskManagerSchema() - { - } - - void TSQLiteTaskManagerSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) - { - TSQLiteTransaction tTransaction(spDatabase); - - // check version of the database - TSerializerVersion tVersion(spDatabase); - - // if version is 0, then this is the fresh database with (almost) no tables inside - if (tVersion.GetVersion() == 0) - { - TSQLiteStatement tStatement(spDatabase); - - tStatement.Prepare(_T("CREATE TABLE tasks(id BIGINT UNIQUE PRIMARY KEY, task_order INT NOT NULL, path VARCHAR(32768) NOT NULL)")); - tStatement.Step(); - - // and finally set the database version to current one - tVersion.SetVersion(1); - } - if (tVersion.GetVersion() == 1) - { - TSQLiteStatement tStatement(spDatabase); - - tStatement.Prepare(_T("CREATE TABLE obsolete_tasks(id BIGINT UNIQUE PRIMARY KEY, path VARCHAR(32768) NOT NULL)")); - tStatement.Step(); - - // and finally set the database version to current one - tVersion.SetVersion(2); - } - - tTransaction.Commit(); - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteTaskManagerSchema.h" +#include "TSQLiteTransaction.h" +#include "TSerializerVersion.h" +#include "TSQLiteStatement.h" + +namespace chcore +{ + using namespace sqlite; + + TSQLiteTaskManagerSchema::TSQLiteTaskManagerSchema() + { + } + + TSQLiteTaskManagerSchema::~TSQLiteTaskManagerSchema() + { + } + + void TSQLiteTaskManagerSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) + { + TSQLiteTransaction tTransaction(spDatabase); + + // check version of the database + TSerializerVersion tVersion(spDatabase); + + // if version is 0, then this is the fresh database with (almost) no tables inside + if (tVersion.GetVersion() == 0) + { + TSQLiteStatement tStatement(spDatabase); + + tStatement.Prepare(_T("CREATE TABLE tasks(id BIGINT UNIQUE PRIMARY KEY, task_order INT NOT NULL, path VARCHAR(32768) NOT NULL)")); + tStatement.Step(); + + // and finally set the database version to current one + tVersion.SetVersion(1); + } + if (tVersion.GetVersion() == 1) + { + TSQLiteStatement tStatement(spDatabase); + + tStatement.Prepare(_T("CREATE TABLE obsolete_tasks(id BIGINT UNIQUE PRIMARY KEY, path VARCHAR(32768) NOT NULL)")); + tStatement.Step(); + + // and finally set the database version to current one + tVersion.SetVersion(2); + } + + tTransaction.Commit(); + } +} Index: src/libchcore/TSQLiteTaskManagerSchema.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTaskManagerSchema.h (.../TSQLiteTaskManagerSchema.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteTaskManagerSchema.h (.../TSQLiteTaskManagerSchema.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,40 +1,40 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TTASKMANAGERSCHEMA_H__ -#define __TTASKMANAGERSCHEMA_H__ - -#include "libchcore.h" -#include "TSQLiteDatabase.h" -#include "ISQLiteSerializerSchema.h" - -namespace chcore -{ - class LIBCHCORE_API TSQLiteTaskManagerSchema : public ISQLiteSerializerSchema - { - public: - TSQLiteTaskManagerSchema(); - virtual ~TSQLiteTaskManagerSchema(); - - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); - }; - - typedef std::shared_ptr TTaskManagerSchemaPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TTASKMANAGERSCHEMA_H__ +#define __TTASKMANAGERSCHEMA_H__ + +#include "libchcore.h" +#include "TSQLiteDatabase.h" +#include "ISQLiteSerializerSchema.h" + +namespace chcore +{ + class LIBCHCORE_API TSQLiteTaskManagerSchema : public ISQLiteSerializerSchema + { + public: + TSQLiteTaskManagerSchema(); + virtual ~TSQLiteTaskManagerSchema(); + + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); + }; + + typedef std::shared_ptr TTaskManagerSchemaPtr; +} + +#endif Index: src/libchcore/TSQLiteTaskSchema.cpp =================================================================== diff -u -r410f8f7b06e7639102eff1021e523b3cfdc185a2 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTaskSchema.cpp (.../TSQLiteTaskSchema.cpp) (revision 410f8f7b06e7639102eff1021e523b3cfdc185a2) +++ src/libchcore/TSQLiteTaskSchema.cpp (.../TSQLiteTaskSchema.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,238 +1,238 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteTaskSchema.h" -#include "TSQLiteTransaction.h" -#include "TSerializerVersion.h" -#include "TSQLiteStatement.h" -#include - -namespace chcore -{ - TSQLiteTaskSchema::TSQLiteTaskSchema() - { - } - - TSQLiteTaskSchema::~TSQLiteTaskSchema() - { - } - - void TSQLiteTaskSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) - { - sqlite::TSQLiteTransaction tTransaction(spDatabase); - - // check version of the database - TSerializerVersion tVersion(spDatabase); - - // if version is 0, then this is the fresh database with (almost) no tables inside - // that's why the initialization always creates the latest version of database, whithout going - // through all the intermediate migrations - if (tVersion.GetVersion() == 0) - CreateNewDatabase(spDatabase, tVersion); - else - { - // migrate current database to the newest version - if (tVersion.GetVersion() == 1) - Migrate_001_002(spDatabase, tVersion); - - if (tVersion.GetVersion() == 2) - Migrate_002_003(spDatabase, tVersion); - - if (tVersion.GetVersion() == 3) - Migrate_003_004(spDatabase, tVersion); - - if(tVersion.GetVersion() == 4) - Migrate_004_005(spDatabase, tVersion); - } - - tTransaction.Commit(); - } - - void TSQLiteTaskSchema::CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) - { - sqlite::TSQLiteStatement tStatement(spDatabase); - tStatement.Prepare(_T("CREATE TABLE task(id BIGINT UNIQUE, name varchar(256) NOT NULL, log_path VARCHAR(32768), current_state INT NOT NULL, destination_path varchar(32768) NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE base_paths(id BIGINT UNIQUE, src_path varchar(32768) NOT NULL, skip_processing boolean NOT NULL, dst_path varchar(32768) NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE scanned_files(id BIGINT UNIQUE, rel_path varchar(32768) NOT NULL, base_path_id BIGINT NOT NULL, attr INT NOT NULL, size BIGINT NOT NULL, time_created BIGINT NOT NULL, time_last_write BIGINT NOT NULL, time_last_access BIGINT NOT NULL, flags INT NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE task_config(id BIGINT UNIQUE, name varchar(256) NOT NULL, node_order INT NOT NULL, value varchar(32768) NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE filters(id BIGINT UNIQUE, use_mask INT NOT NULL, mask varchar(32768) NOT NULL, ") - _T("use_exclude_mask INT NOT NULL, exclude_mask varchar(32768) NOT NULL, ") - _T("use_size_1 INT NOT NULL, compare_type_1 INT NOT NULL, size_1 BIGINT NOT NULL, ") - _T("use_size_2 INT NOT NULL, compare_type_2 INT NOT NULL, size_2 BIGINT NOT NULL, ") - _T("date_type INT NOT NULL,") - _T("use_date_time_1 INT NOT NULL, date_compare_type_1 INT NOT NULL, use_date_1 INT NOT NULL, use_time_1 INT NOT NULL, datetime_1 varchar(64) NOT NULL, ") - _T("use_date_time_2 INT NOT NULL, date_compare_type_2 INT NOT NULL, use_date_2 INT NOT NULL, use_time_2 INT NOT NULL, datetime_2 varchar(64) NOT NULL, ") - _T("use_attributes INT NOT NULL, attr_archive INT NOT NULL, attr_ro INT NOT NULL, attr_hidden INT NOT NULL, attr_system INT NOT NULL, attr_directory INT NOT NULL") - _T(")")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE local_stats(id BIGINT UNIQUE, elapsed_time BIGINT NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtasks(id BIGINT UNIQUE, type INT NOT NULL, is_current boolean NOT NULL, is_estimation boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtasks_info(id BIGINT UNIQUE, operation INT NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtask_fastmove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtask_scan(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtask_delete(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE subtask_copymove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); - tStatement.Step(); - - // and finally set the database version to current one - tVersion.SetVersion(5); - } - - void TSQLiteTaskSchema::Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) - { - sqlite::TSQLiteStatement tStatement(spDatabase); - - tStatement.Prepare(_T("ALTER TABLE subtask_fastmove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_delete ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); - tStatement.Prepare(_T("ALTER TABLE subtask_copymove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); - tStatement.Step(); - - tVersion.SetVersion(2); - } - - void TSQLiteTaskSchema::Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) - { - sqlite::TSQLiteStatement tStatement(spDatabase); - - // drop column from fastmove - tStatement.Prepare(_T("CREATE TABLE subtask_fastmove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("INSERT INTO subtask_fastmove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") - _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") - _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_fastmove")); - tStatement.Step(); - - tStatement.Prepare(_T("DROP TABLE subtask_fastmove")); - tStatement.Step(); - - tStatement.Prepare(_T("ALTER TABLE subtask_fastmove_new RENAME TO subtask_fastmove")); - tStatement.Step(); - - // drop column from subtask delete - tStatement.Prepare(_T("CREATE TABLE subtask_delete_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume - tStatement.Prepare(_T("INSERT INTO subtask_delete_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_delete")); - tStatement.Step(); - - tStatement.Prepare(_T("DROP TABLE subtask_delete")); - tStatement.Step(); - - tStatement.Prepare(_T("ALTER TABLE subtask_delete_new RENAME TO subtask_delete")); - tStatement.Step(); - - // drop column from subtask copymove - tStatement.Prepare(_T("CREATE TABLE subtask_copymove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume - tStatement.Prepare(_T("INSERT INTO subtask_copymove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") - _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") - _T("FROM subtask_copymove")); - tStatement.Step(); - - tStatement.Prepare(_T("DROP TABLE subtask_copymove")); - tStatement.Step(); - - tStatement.Prepare(_T("ALTER TABLE subtask_copymove_new RENAME TO subtask_copymove")); - tStatement.Step(); - - tVersion.SetVersion(3); - } - - void TSQLiteTaskSchema::Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) - { - sqlite::TSQLiteStatement tStatement(spDatabase); - - tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); - tStatement.Step(); - - // for tasks being migrated we have to insert some defaults for feedback - tStatement.Prepare(_T("INSERT INTO feedback(id, file_error, file_already_exists, not_enough_space, operation_finished, operation_error) VALUES(?1, ?2, ?3, ?4, ?5, ?6)")); - tStatement.BindValue(1, 0); - tStatement.BindValue(2, 0); - tStatement.BindValue(3, 0); - tStatement.BindValue(4, 0); - tStatement.BindValue(5, 0); - tStatement.BindValue(6, 0); - - tStatement.Step(); - - tVersion.SetVersion(4); - } - - void TSQLiteTaskSchema::Migrate_004_005(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) - { - sqlite::TSQLiteStatement tStatement(spDatabase); - - // new table for scan stats - tStatement.Prepare(_T("CREATE TABLE subtask_scan(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") - _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") - _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); - tStatement.Step(); - - tVersion.SetVersion(5); - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteTaskSchema.h" +#include "TSQLiteTransaction.h" +#include "TSerializerVersion.h" +#include "TSQLiteStatement.h" +#include + +namespace chcore +{ + TSQLiteTaskSchema::TSQLiteTaskSchema() + { + } + + TSQLiteTaskSchema::~TSQLiteTaskSchema() + { + } + + void TSQLiteTaskSchema::Setup(const sqlite::TSQLiteDatabasePtr& spDatabase) + { + sqlite::TSQLiteTransaction tTransaction(spDatabase); + + // check version of the database + TSerializerVersion tVersion(spDatabase); + + // if version is 0, then this is the fresh database with (almost) no tables inside + // that's why the initialization always creates the latest version of database, whithout going + // through all the intermediate migrations + if (tVersion.GetVersion() == 0) + CreateNewDatabase(spDatabase, tVersion); + else + { + // migrate current database to the newest version + if (tVersion.GetVersion() == 1) + Migrate_001_002(spDatabase, tVersion); + + if (tVersion.GetVersion() == 2) + Migrate_002_003(spDatabase, tVersion); + + if (tVersion.GetVersion() == 3) + Migrate_003_004(spDatabase, tVersion); + + if(tVersion.GetVersion() == 4) + Migrate_004_005(spDatabase, tVersion); + } + + tTransaction.Commit(); + } + + void TSQLiteTaskSchema::CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + tStatement.Prepare(_T("CREATE TABLE task(id BIGINT UNIQUE, name varchar(256) NOT NULL, log_path VARCHAR(32768), current_state INT NOT NULL, destination_path varchar(32768) NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE base_paths(id BIGINT UNIQUE, src_path varchar(32768) NOT NULL, skip_processing boolean NOT NULL, dst_path varchar(32768) NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE scanned_files(id BIGINT UNIQUE, rel_path varchar(32768) NOT NULL, base_path_id BIGINT NOT NULL, attr INT NOT NULL, size BIGINT NOT NULL, time_created BIGINT NOT NULL, time_last_write BIGINT NOT NULL, time_last_access BIGINT NOT NULL, flags INT NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE task_config(id BIGINT UNIQUE, name varchar(256) NOT NULL, node_order INT NOT NULL, value varchar(32768) NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE filters(id BIGINT UNIQUE, use_mask INT NOT NULL, mask varchar(32768) NOT NULL, ") + _T("use_exclude_mask INT NOT NULL, exclude_mask varchar(32768) NOT NULL, ") + _T("use_size_1 INT NOT NULL, compare_type_1 INT NOT NULL, size_1 BIGINT NOT NULL, ") + _T("use_size_2 INT NOT NULL, compare_type_2 INT NOT NULL, size_2 BIGINT NOT NULL, ") + _T("date_type INT NOT NULL,") + _T("use_date_time_1 INT NOT NULL, date_compare_type_1 INT NOT NULL, use_date_1 INT NOT NULL, use_time_1 INT NOT NULL, datetime_1 varchar(64) NOT NULL, ") + _T("use_date_time_2 INT NOT NULL, date_compare_type_2 INT NOT NULL, use_date_2 INT NOT NULL, use_time_2 INT NOT NULL, datetime_2 varchar(64) NOT NULL, ") + _T("use_attributes INT NOT NULL, attr_archive INT NOT NULL, attr_ro INT NOT NULL, attr_hidden INT NOT NULL, attr_system INT NOT NULL, attr_directory INT NOT NULL") + _T(")")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE local_stats(id BIGINT UNIQUE, elapsed_time BIGINT NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtasks(id BIGINT UNIQUE, type INT NOT NULL, is_current boolean NOT NULL, is_estimation boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtasks_info(id BIGINT UNIQUE, operation INT NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtask_fastmove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtask_scan(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtask_delete(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE subtask_copymove(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); + tStatement.Step(); + + // and finally set the database version to current one + tVersion.SetVersion(5); + } + + void TSQLiteTaskSchema::Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + + tStatement.Prepare(_T("ALTER TABLE subtask_fastmove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_delete ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); + tStatement.Prepare(_T("ALTER TABLE subtask_copymove ADD COLUMN ci_silent_resume boolean NOT NULL DEFAULT false")); + tStatement.Step(); + + tVersion.SetVersion(2); + } + + void TSQLiteTaskSchema::Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + + // drop column from fastmove + tStatement.Prepare(_T("CREATE TABLE subtask_fastmove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("INSERT INTO subtask_fastmove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") + _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, ") + _T("total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_fastmove")); + tStatement.Step(); + + tStatement.Prepare(_T("DROP TABLE subtask_fastmove")); + tStatement.Step(); + + tStatement.Prepare(_T("ALTER TABLE subtask_fastmove_new RENAME TO subtask_fastmove")); + tStatement.Step(); + + // drop column from subtask delete + tStatement.Prepare(_T("CREATE TABLE subtask_delete_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume + tStatement.Prepare(_T("INSERT INTO subtask_delete_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_delete")); + tStatement.Step(); + + tStatement.Prepare(_T("DROP TABLE subtask_delete")); + tStatement.Step(); + + tStatement.Prepare(_T("ALTER TABLE subtask_delete_new RENAME TO subtask_delete")); + tStatement.Step(); + + // drop column from subtask copymove + tStatement.Prepare(_T("CREATE TABLE subtask_copymove_new(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + //id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume + tStatement.Prepare(_T("INSERT INTO subtask_copymove_new(id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume)") + _T("SELECT id, current_index, is_running, is_initialized, total_size, processed_size, size_speed, total_count, processed_count, count_speed, ci_processed_size, ci_total_size, timer, buffer_index, current_path, ci_silent_resume ") + _T("FROM subtask_copymove")); + tStatement.Step(); + + tStatement.Prepare(_T("DROP TABLE subtask_copymove")); + tStatement.Step(); + + tStatement.Prepare(_T("ALTER TABLE subtask_copymove_new RENAME TO subtask_copymove")); + tStatement.Step(); + + tVersion.SetVersion(3); + } + + void TSQLiteTaskSchema::Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + + tStatement.Prepare(_T("CREATE TABLE feedback(id BIGINT UNIQUE, file_error INT NOT NULL, file_already_exists INT NOT NULL, not_enough_space INT NOT NULL, operation_finished INT NOT NULL, operation_error INT NOT NULL)")); + tStatement.Step(); + + // for tasks being migrated we have to insert some defaults for feedback + tStatement.Prepare(_T("INSERT INTO feedback(id, file_error, file_already_exists, not_enough_space, operation_finished, operation_error) VALUES(?1, ?2, ?3, ?4, ?5, ?6)")); + tStatement.BindValue(1, 0); + tStatement.BindValue(2, 0); + tStatement.BindValue(3, 0); + tStatement.BindValue(4, 0); + tStatement.BindValue(5, 0); + tStatement.BindValue(6, 0); + + tStatement.Step(); + + tVersion.SetVersion(4); + } + + void TSQLiteTaskSchema::Migrate_004_005(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion) + { + sqlite::TSQLiteStatement tStatement(spDatabase); + + // new table for scan stats + tStatement.Prepare(_T("CREATE TABLE subtask_scan(id BIGINT UNIQUE, current_index INT NOT NULL, is_running boolean NOT NULL, is_initialized boolean NOT NULL, total_size BIGINT NOT NULL, processed_size BIGINT NOT NULL, size_speed varchar(1024) NOT NULL, ") + _T("total_count BIGINT NOT NULL, processed_count BIGINT NOT NULL, count_speed varchar(1024) NOT NULL, ci_processed_size BIGINT NOT NULL, ci_total_size BIGINT NOT NULL, timer BIGINT NOT NULL, ") + _T("buffer_index INT NOT NULL, current_path varchar(32768) NOT NULL, ci_silent_resume boolean NOT NULL)")); + tStatement.Step(); + + tVersion.SetVersion(5); + } +} Index: src/libchcore/TSQLiteTaskSchema.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTaskSchema.h (.../TSQLiteTaskSchema.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteTaskSchema.h (.../TSQLiteTaskSchema.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,49 +1,49 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITETASKSCHEMA_H__ -#define __TSQLITETASKSCHEMA_H__ - -#include "libchcore.h" -#include "ISQLiteSerializerSchema.h" - -namespace chcore -{ - class TSerializerVersion; - - class LIBCHCORE_API TSQLiteTaskSchema : public ISQLiteSerializerSchema - { - public: - TSQLiteTaskSchema(); - virtual ~TSQLiteTaskSchema(); - - virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); - - private: - void CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - - void Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - void Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - void Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - void Migrate_004_005(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); - }; - - typedef std::shared_ptr TSQLiteTaskSchemaPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITETASKSCHEMA_H__ +#define __TSQLITETASKSCHEMA_H__ + +#include "libchcore.h" +#include "ISQLiteSerializerSchema.h" + +namespace chcore +{ + class TSerializerVersion; + + class LIBCHCORE_API TSQLiteTaskSchema : public ISQLiteSerializerSchema + { + public: + TSQLiteTaskSchema(); + virtual ~TSQLiteTaskSchema(); + + virtual void Setup(const sqlite::TSQLiteDatabasePtr& spDatabase); + + private: + void CreateNewDatabase(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + + void Migrate_001_002(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + void Migrate_002_003(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + void Migrate_003_004(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + void Migrate_004_005(const sqlite::TSQLiteDatabasePtr& spDatabase, TSerializerVersion &tVersion); + }; + + typedef std::shared_ptr TSQLiteTaskSchemaPtr; +} + +#endif Index: src/libchcore/TSQLiteTransaction.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTransaction.cpp (.../TSQLiteTransaction.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/TSQLiteTransaction.cpp (.../TSQLiteTransaction.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,100 +1,100 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSQLiteTransaction.h" -#include "TSQLiteException.h" -#include "ErrorCodes.h" -#include "sqlite3/sqlite3.h" - -namespace chcore -{ - namespace sqlite - { - TSQLiteTransaction::TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase) : - m_spDatabase(spDatabase), - m_bTransactionStarted(false) - { - if (!m_spDatabase) - throw TSQLiteException(eErr_InvalidArgument, 0, _T("Invalid database provided"), LOCATION); - Begin(); - } - - TSQLiteTransaction::~TSQLiteTransaction() - { - // try to rollback the transaction; this is the last resort - if (m_bTransactionStarted && m_spDatabase->GetInTransaction()) - { - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", nullptr, nullptr, nullptr); - iResult; - _ASSERTE(iResult == SQLITE_OK); - m_spDatabase->SetInTransaction(false); - } - } - - void TSQLiteTransaction::Begin() - { - if (m_spDatabase->GetInTransaction()) - return; - - if (m_bTransactionStarted) - throw TSQLiteException(eErr_SQLiteCannotBeginTransaction, 0, _T("Transaction already started"), LOCATION); - - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "BEGIN TRANSACTION", nullptr, nullptr, nullptr); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteCannotBeginTransaction, iResult, _T("Cannot begin transaction"), LOCATION); - - m_spDatabase->SetInTransaction(true); - m_bTransactionStarted = true; - } - - void TSQLiteTransaction::Rollback() - { - // no transactions whatsoever (even on database) - if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) - throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started"), LOCATION); - - // database has transaction started, but not by this object - if (!m_bTransactionStarted) - return; - - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", nullptr, nullptr, nullptr); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, iResult, _T("Cannot rollback transaction"), LOCATION); - m_spDatabase->SetInTransaction(false); - m_bTransactionStarted = false; - } - - void TSQLiteTransaction::Commit() - { - // no transactions whatsoever (even on database) - if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) - throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started"), LOCATION); - - // database has transaction started, but not by this object - if (!m_bTransactionStarted) - return; - - int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "COMMIT TRANSACTION;", nullptr, nullptr, nullptr); - if (iResult != SQLITE_OK) - throw TSQLiteException(eErr_SQLiteCannotCommitTransaction, iResult, _T("Cannot commit transaction"), LOCATION); - m_spDatabase->SetInTransaction(false); - m_bTransactionStarted = false; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSQLiteTransaction.h" +#include "TSQLiteException.h" +#include "ErrorCodes.h" +#include "sqlite3/sqlite3.h" + +namespace chcore +{ + namespace sqlite + { + TSQLiteTransaction::TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase) : + m_spDatabase(spDatabase), + m_bTransactionStarted(false) + { + if (!m_spDatabase) + throw TSQLiteException(eErr_InvalidArgument, 0, _T("Invalid database provided"), LOCATION); + Begin(); + } + + TSQLiteTransaction::~TSQLiteTransaction() + { + // try to rollback the transaction; this is the last resort + if (m_bTransactionStarted && m_spDatabase->GetInTransaction()) + { + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", nullptr, nullptr, nullptr); + iResult; + _ASSERTE(iResult == SQLITE_OK); + m_spDatabase->SetInTransaction(false); + } + } + + void TSQLiteTransaction::Begin() + { + if (m_spDatabase->GetInTransaction()) + return; + + if (m_bTransactionStarted) + throw TSQLiteException(eErr_SQLiteCannotBeginTransaction, 0, _T("Transaction already started"), LOCATION); + + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "BEGIN TRANSACTION", nullptr, nullptr, nullptr); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteCannotBeginTransaction, iResult, _T("Cannot begin transaction"), LOCATION); + + m_spDatabase->SetInTransaction(true); + m_bTransactionStarted = true; + } + + void TSQLiteTransaction::Rollback() + { + // no transactions whatsoever (even on database) + if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) + throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started"), LOCATION); + + // database has transaction started, but not by this object + if (!m_bTransactionStarted) + return; + + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "ROLLBACK TRANSACTION;", nullptr, nullptr, nullptr); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, iResult, _T("Cannot rollback transaction"), LOCATION); + m_spDatabase->SetInTransaction(false); + m_bTransactionStarted = false; + } + + void TSQLiteTransaction::Commit() + { + // no transactions whatsoever (even on database) + if (!m_bTransactionStarted && !m_spDatabase->GetInTransaction()) + throw TSQLiteException(eErr_SQLiteCannotRollbackTransaction, 0, _T("Transaction not started"), LOCATION); + + // database has transaction started, but not by this object + if (!m_bTransactionStarted) + return; + + int iResult = sqlite3_exec((sqlite3*)m_spDatabase->GetHandle(), "COMMIT TRANSACTION;", nullptr, nullptr, nullptr); + if (iResult != SQLITE_OK) + throw TSQLiteException(eErr_SQLiteCannotCommitTransaction, iResult, _T("Cannot commit transaction"), LOCATION); + m_spDatabase->SetInTransaction(false); + m_bTransactionStarted = false; + } + } +} Index: src/libchcore/TSQLiteTransaction.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSQLiteTransaction.h (.../TSQLiteTransaction.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSQLiteTransaction.h (.../TSQLiteTransaction.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,45 +1,45 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSQLITETRANSACTION_H__ -#define __TSQLITETRANSACTION_H__ - -#include "TSQLiteDatabase.h" - -namespace chcore -{ - namespace sqlite - { - class TSQLiteTransaction - { - public: - explicit TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase); - ~TSQLiteTransaction(); - - void Begin(); - void Rollback(); - void Commit(); - - private: - TSQLiteDatabasePtr m_spDatabase; - bool m_bTransactionStarted; // states if transaction was started by this object - }; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSQLITETRANSACTION_H__ +#define __TSQLITETRANSACTION_H__ + +#include "TSQLiteDatabase.h" + +namespace chcore +{ + namespace sqlite + { + class TSQLiteTransaction + { + public: + explicit TSQLiteTransaction(const TSQLiteDatabasePtr& spDatabase); + ~TSQLiteTransaction(); + + void Begin(); + void Rollback(); + void Commit(); + + private: + TSQLiteDatabasePtr m_spDatabase; + bool m_bTransactionStarted; // states if transaction was started by this object + }; + } +} + +#endif Index: src/libchcore/TScopedRunningTimeTracker.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TScopedRunningTimeTracker.cpp (.../TScopedRunningTimeTracker.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TScopedRunningTimeTracker.cpp (.../TScopedRunningTimeTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,74 +1,74 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TScopedRunningTimeTracker.h" - -namespace chcore -{ - TScopedRunningTimeTracker::TScopedRunningTimeTracker(IRunningTimeControl& rLocalStats) : - m_rLocalStats(rLocalStats), - m_bTimeTrackingPaused(false), - m_bRunningStatePaused(false) - { - rLocalStats.EnableTimeTracking(); - rLocalStats.MarkAsRunning(); - } - - TScopedRunningTimeTracker::~TScopedRunningTimeTracker() - { - m_rLocalStats.MarkAsNotRunning(); - m_rLocalStats.DisableTimeTracking(); - } - - void TScopedRunningTimeTracker::PauseTimeTracking() - { - if (!m_bTimeTrackingPaused) - { - m_rLocalStats.DisableTimeTracking(); - m_bTimeTrackingPaused = true; - } - } - - void TScopedRunningTimeTracker::UnPauseTimeTracking() - { - if (m_bTimeTrackingPaused) - { - m_rLocalStats.EnableTimeTracking(); - m_bTimeTrackingPaused = false; - } - } - - void TScopedRunningTimeTracker::PauseRunningState() - { - if (!m_bRunningStatePaused) - { - m_rLocalStats.MarkAsNotRunning(); - m_bRunningStatePaused = true; - } - } - - void TScopedRunningTimeTracker::UnPauseRunningState() - { - if (m_bRunningStatePaused) - { - m_rLocalStats.MarkAsRunning(); - m_bRunningStatePaused = false; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TScopedRunningTimeTracker.h" + +namespace chcore +{ + TScopedRunningTimeTracker::TScopedRunningTimeTracker(IRunningTimeControl& rLocalStats) : + m_rLocalStats(rLocalStats), + m_bTimeTrackingPaused(false), + m_bRunningStatePaused(false) + { + rLocalStats.EnableTimeTracking(); + rLocalStats.MarkAsRunning(); + } + + TScopedRunningTimeTracker::~TScopedRunningTimeTracker() + { + m_rLocalStats.MarkAsNotRunning(); + m_rLocalStats.DisableTimeTracking(); + } + + void TScopedRunningTimeTracker::PauseTimeTracking() + { + if (!m_bTimeTrackingPaused) + { + m_rLocalStats.DisableTimeTracking(); + m_bTimeTrackingPaused = true; + } + } + + void TScopedRunningTimeTracker::UnPauseTimeTracking() + { + if (m_bTimeTrackingPaused) + { + m_rLocalStats.EnableTimeTracking(); + m_bTimeTrackingPaused = false; + } + } + + void TScopedRunningTimeTracker::PauseRunningState() + { + if (!m_bRunningStatePaused) + { + m_rLocalStats.MarkAsNotRunning(); + m_bRunningStatePaused = true; + } + } + + void TScopedRunningTimeTracker::UnPauseRunningState() + { + if (m_bRunningStatePaused) + { + m_rLocalStats.MarkAsRunning(); + m_bRunningStatePaused = false; + } + } +} Index: src/libchcore/TScopedRunningTimeTracker.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TScopedRunningTimeTracker.h (.../TScopedRunningTimeTracker.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TScopedRunningTimeTracker.h (.../TScopedRunningTimeTracker.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,49 +1,49 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSCOPEDRUNNINGTIME_H__ -#define __TSCOPEDRUNNINGTIME_H__ - -#include "IRunningTimeControl.h" - -namespace chcore -{ - class TScopedRunningTimeTracker - { - public: - explicit TScopedRunningTimeTracker(IRunningTimeControl& rStats); - ~TScopedRunningTimeTracker(); - - void PauseTimeTracking(); - void UnPauseTimeTracking(); - - void PauseRunningState(); - void UnPauseRunningState(); - - private: - TScopedRunningTimeTracker(const TScopedRunningTimeTracker& rLocalStats) = delete; - TScopedRunningTimeTracker& operator=(const TScopedRunningTimeTracker& rLocalStats) = delete; - - private: - IRunningTimeControl& m_rLocalStats; - bool m_bTimeTrackingPaused; - bool m_bRunningStatePaused; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSCOPEDRUNNINGTIME_H__ +#define __TSCOPEDRUNNINGTIME_H__ + +#include "IRunningTimeControl.h" + +namespace chcore +{ + class TScopedRunningTimeTracker + { + public: + explicit TScopedRunningTimeTracker(IRunningTimeControl& rStats); + ~TScopedRunningTimeTracker(); + + void PauseTimeTracking(); + void UnPauseTimeTracking(); + + void PauseRunningState(); + void UnPauseRunningState(); + + private: + TScopedRunningTimeTracker(const TScopedRunningTimeTracker& rLocalStats) = delete; + TScopedRunningTimeTracker& operator=(const TScopedRunningTimeTracker& rLocalStats) = delete; + + private: + IRunningTimeControl& m_rLocalStats; + bool m_bTimeTrackingPaused; + bool m_bRunningStatePaused; + }; +} + +#endif Index: src/libchcore/TScopedRunningTimeTrackerPause.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TScopedRunningTimeTrackerPause.cpp (.../TScopedRunningTimeTrackerPause.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TScopedRunningTimeTrackerPause.cpp (.../TScopedRunningTimeTrackerPause.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,35 +1,35 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TScopedRunningTimeTrackerPause.h" -#include "TScopedRunningTimeTracker.h" - -namespace chcore -{ - TScopedRunningTimeTrackerPause::TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker) : - m_rRunningTimeTracker(rRunningTimeTracker) - { - m_rRunningTimeTracker.PauseTimeTracking(); - } - - TScopedRunningTimeTrackerPause::~TScopedRunningTimeTrackerPause() - { - m_rRunningTimeTracker.UnPauseTimeTracking(); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TScopedRunningTimeTrackerPause.h" +#include "TScopedRunningTimeTracker.h" + +namespace chcore +{ + TScopedRunningTimeTrackerPause::TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker) : + m_rRunningTimeTracker(rRunningTimeTracker) + { + m_rRunningTimeTracker.PauseTimeTracking(); + } + + TScopedRunningTimeTrackerPause::~TScopedRunningTimeTrackerPause() + { + m_rRunningTimeTracker.UnPauseTimeTracking(); + } +} Index: src/libchcore/TScopedRunningTimeTrackerPause.h =================================================================== diff -u -rcb4e9d4b60d62b25ae2cf556c0642601af56c787 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TScopedRunningTimeTrackerPause.h (.../TScopedRunningTimeTrackerPause.h) (revision cb4e9d4b60d62b25ae2cf556c0642601af56c787) +++ src/libchcore/TScopedRunningTimeTrackerPause.h (.../TScopedRunningTimeTrackerPause.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,40 +1,40 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ -#define __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ - -namespace chcore -{ - class TScopedRunningTimeTracker; - - class TScopedRunningTimeTrackerPause - { - public: - explicit TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker); - ~TScopedRunningTimeTrackerPause(); - - TScopedRunningTimeTrackerPause(const TScopedRunningTimeTrackerPause&) = delete; - TScopedRunningTimeTrackerPause& operator=(const TScopedRunningTimeTrackerPause&) = delete; - - private: - TScopedRunningTimeTracker& m_rRunningTimeTracker; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ +#define __TSCOPEDRUNNINGTIMETRACKERPAUSE_H__ + +namespace chcore +{ + class TScopedRunningTimeTracker; + + class TScopedRunningTimeTrackerPause + { + public: + explicit TScopedRunningTimeTrackerPause(TScopedRunningTimeTracker& rRunningTimeTracker); + ~TScopedRunningTimeTrackerPause(); + + TScopedRunningTimeTrackerPause(const TScopedRunningTimeTrackerPause&) = delete; + TScopedRunningTimeTrackerPause& operator=(const TScopedRunningTimeTrackerPause&) = delete; + + private: + TScopedRunningTimeTracker& m_rRunningTimeTracker; + }; +} + +#endif Index: src/libchcore/TSerializerException.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSerializerException.cpp (.../TSerializerException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSerializerException.cpp (.../TSerializerException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,33 +1,33 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSerializerException.h" - -namespace chcore -{ - TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } - - TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSerializerException.h" + +namespace chcore +{ + TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } + + TSerializerException::TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } +} Index: src/libchcore/TSerializerException.h =================================================================== diff -u -r8d3154738b885f2e01997071e6180da0c4b8cc7c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSerializerException.h (.../TSerializerException.h) (revision 8d3154738b885f2e01997071e6180da0c4b8cc7c) +++ src/libchcore/TSerializerException.h (.../TSerializerException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,35 +1,35 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSERIALIZEREXCEPTION_H__ -#define __TSERIALIZEREXCEPTION_H__ - -#include "libchcore.h" -#include "TBaseException.h" - -namespace chcore -{ - class LIBCHCORE_API TSerializerException : public TBaseException - { - public: - TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSERIALIZEREXCEPTION_H__ +#define __TSERIALIZEREXCEPTION_H__ + +#include "libchcore.h" +#include "TBaseException.h" + +namespace chcore +{ + class LIBCHCORE_API TSerializerException : public TBaseException + { + public: + TSerializerException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TSerializerException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + }; +} + +#endif Index: src/libchcore/TSerializerVersion.cpp =================================================================== diff -u -r8d3154738b885f2e01997071e6180da0c4b8cc7c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSerializerVersion.cpp (.../TSerializerVersion.cpp) (revision 8d3154738b885f2e01997071e6180da0c4b8cc7c) +++ src/libchcore/TSerializerVersion.cpp (.../TSerializerVersion.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,108 +1,108 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSerializerVersion.h" -#include "TSQLiteTransaction.h" -#include "ErrorCodes.h" -#include "TSerializerException.h" -#include "TSQLiteStatement.h" -#include "TSQLiteException.h" -#include "sqlite3\sqlite3.h" - -namespace chcore -{ - using namespace sqlite; - - TSerializerVersion::TSerializerVersion(const TSQLiteDatabasePtr& spDatabase) : - m_spDatabase(spDatabase), - m_bSetupExecuted(false) - { - if (!spDatabase) - throw TSerializerException(eErr_InvalidArgument, _T("No database provided"), LOCATION); - } - - TSerializerVersion::~TSerializerVersion() - { - } - - void TSerializerVersion::Setup() - { - if (m_bSetupExecuted) - return; - - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); - - tStatement.Prepare(_T("SELECT count(*) FROM sqlite_master WHERE type=?1 AND name=?2")); - tStatement.BindValue(1, _T("table")); - tStatement.BindValue(2, _T("version")); - if (tStatement.Step() != TSQLiteStatement::eStep_HasRow) - throw TSQLiteException(eErr_InternalProblem, SQLITE_ERROR, _T("Problem accessing sqlite_master table"), LOCATION); - - int iVersionCount = tStatement.GetInt(0); - if (iVersionCount == 0) - { - // create table - tStatement.Prepare(_T("CREATE TABLE IF NOT EXISTS version(db_version INT NOT NULL)")); - tStatement.Step(); - - tStatement.Prepare(_T("INSERT INTO version(db_version) VALUES(?1)")); - tStatement.BindValue(1, 0); - tStatement.Step(); - } - - tTransaction.Commit(); - - m_bSetupExecuted = true; - } - - int TSerializerVersion::GetVersion() - { - Setup(); - - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); - - // when table does not exist the sqlite error is just SQLITE_ERROR when preparing statement - tStatement.Prepare(_T("SELECT db_version FROM version")); - if (tStatement.Step() == TSQLiteStatement::eStep_HasRow) - { - tTransaction.Commit(); - return tStatement.GetInt(0); - } - - tTransaction.Commit(); - return 0; - } - - void TSerializerVersion::SetVersion(int iNewVersion) - { - Setup(); - - TSQLiteTransaction tTransaction(m_spDatabase); - TSQLiteStatement tStatement(m_spDatabase); - - // create table - tStatement.Prepare(_T("UPDATE version SET db_version=?1")); - tStatement.BindValue(1, iNewVersion); - tStatement.Step(); - - tTransaction.Commit(); - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSerializerVersion.h" +#include "TSQLiteTransaction.h" +#include "ErrorCodes.h" +#include "TSerializerException.h" +#include "TSQLiteStatement.h" +#include "TSQLiteException.h" +#include "sqlite3\sqlite3.h" + +namespace chcore +{ + using namespace sqlite; + + TSerializerVersion::TSerializerVersion(const TSQLiteDatabasePtr& spDatabase) : + m_spDatabase(spDatabase), + m_bSetupExecuted(false) + { + if (!spDatabase) + throw TSerializerException(eErr_InvalidArgument, _T("No database provided"), LOCATION); + } + + TSerializerVersion::~TSerializerVersion() + { + } + + void TSerializerVersion::Setup() + { + if (m_bSetupExecuted) + return; + + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); + + tStatement.Prepare(_T("SELECT count(*) FROM sqlite_master WHERE type=?1 AND name=?2")); + tStatement.BindValue(1, _T("table")); + tStatement.BindValue(2, _T("version")); + if (tStatement.Step() != TSQLiteStatement::eStep_HasRow) + throw TSQLiteException(eErr_InternalProblem, SQLITE_ERROR, _T("Problem accessing sqlite_master table"), LOCATION); + + int iVersionCount = tStatement.GetInt(0); + if (iVersionCount == 0) + { + // create table + tStatement.Prepare(_T("CREATE TABLE IF NOT EXISTS version(db_version INT NOT NULL)")); + tStatement.Step(); + + tStatement.Prepare(_T("INSERT INTO version(db_version) VALUES(?1)")); + tStatement.BindValue(1, 0); + tStatement.Step(); + } + + tTransaction.Commit(); + + m_bSetupExecuted = true; + } + + int TSerializerVersion::GetVersion() + { + Setup(); + + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); + + // when table does not exist the sqlite error is just SQLITE_ERROR when preparing statement + tStatement.Prepare(_T("SELECT db_version FROM version")); + if (tStatement.Step() == TSQLiteStatement::eStep_HasRow) + { + tTransaction.Commit(); + return tStatement.GetInt(0); + } + + tTransaction.Commit(); + return 0; + } + + void TSerializerVersion::SetVersion(int iNewVersion) + { + Setup(); + + TSQLiteTransaction tTransaction(m_spDatabase); + TSQLiteStatement tStatement(m_spDatabase); + + // create table + tStatement.Prepare(_T("UPDATE version SET db_version=?1")); + tStatement.BindValue(1, iNewVersion); + tStatement.Step(); + + tTransaction.Commit(); + } +} Index: src/libchcore/TSerializerVersion.h =================================================================== diff -u -rcb4e9d4b60d62b25ae2cf556c0642601af56c787 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSerializerVersion.h (.../TSerializerVersion.h) (revision cb4e9d4b60d62b25ae2cf556c0642601af56c787) +++ src/libchcore/TSerializerVersion.h (.../TSerializerVersion.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,48 +1,48 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSERIALIZERVERSION_H__ -#define __TSERIALIZERVERSION_H__ - -#include "libchcore.h" -#include "TSQLiteDatabase.h" - -namespace chcore -{ - class LIBCHCORE_API TSerializerVersion - { - public: - explicit TSerializerVersion(const sqlite::TSQLiteDatabasePtr& spDatabase); - ~TSerializerVersion(); - - int GetVersion(); - void SetVersion(int iNewVersion); - - protected: - void Setup(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - sqlite::TSQLiteDatabasePtr m_spDatabase; -#pragma warning(pop) - bool m_bSetupExecuted; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSERIALIZERVERSION_H__ +#define __TSERIALIZERVERSION_H__ + +#include "libchcore.h" +#include "TSQLiteDatabase.h" + +namespace chcore +{ + class LIBCHCORE_API TSerializerVersion + { + public: + explicit TSerializerVersion(const sqlite::TSQLiteDatabasePtr& spDatabase); + ~TSerializerVersion(); + + int GetVersion(); + void SetVersion(int iNewVersion); + + protected: + void Setup(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + sqlite::TSQLiteDatabasePtr m_spDatabase; +#pragma warning(pop) + bool m_bSetupExecuted; + }; +} + +#endif Index: src/libchcore/TSharedMemory.cpp =================================================================== diff -u -r306fbe693c70290af9de9a5779084a697de22d75 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSharedMemory.cpp (.../TSharedMemory.cpp) (revision 306fbe693c70290af9de9a5779084a697de22d75) +++ src/libchcore/TSharedMemory.cpp (.../TSharedMemory.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,220 +1,220 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSharedMemory.cpp -/// @date 2011/05/03 -/// @brief Contains implementation of shared memory handling classes. -// ============================================================================ -#include "stdafx.h" -#include "TSharedMemory.h" -#include -#include "ErrorCodes.h" -#include "TCoreException.h" -#include "TIpcMutexLock.h" - -namespace chcore -{ - #define MUTEX_SUFFIX _T("_Mutex") - - /////////////////////////////////////////////////////////////////////////////////////// - // TSharedMemory class - - TSharedMemory::TSharedMemory() : - m_hFileMapping(nullptr), - m_pMappedMemory(nullptr), - m_mutex(nullptr), - m_stSize(0) - { - } - - TSharedMemory::~TSharedMemory() - { - Close(); - } - - void TSharedMemory::Create(const wchar_t* pszName, shm_size_t stSize) - { - if(!pszName || pszName[ 0 ] == _T('\0')) - throw TCoreException(eErr_InvalidArgument, L"pszName", LOCATION); - if(stSize == 0) - throw TCoreException(eErr_InvalidArgument, L"stSize", LOCATION); - - Close(); - - try - { - std::wstring wstrMutexName = pszName; - wstrMutexName += MUTEX_SUFFIX; - - m_mutex.CreateMutex(wstrMutexName.c_str()); - - m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, boost::numeric_cast(stSize + sizeof(size_t)), pszName); - if (!m_hFileMapping) - throw TCoreException(eErr_CannotOpenSharedMemory, L"Failed to create file mapping", LOCATION); - if(GetLastError() == ERROR_ALREADY_EXISTS) - throw TCoreException(eErr_SharedMemoryAlreadyExists, L"File mapping already exists", LOCATION); // shared memory already exists - cannot guarantee that the size is correct - - // Get a pointer to the file-mapped shared memory. - m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_WRITE, 0, 0, 0); - if (!m_pMappedMemory) - throw TCoreException(eErr_CannotOpenSharedMemory, L"Cannot map view of file", LOCATION); - } - catch (...) - { - Close(); - throw; - } - - TIpcMutexLock lock(m_mutex); - - m_stSize = stSize + sizeof(shm_size_t); - *(shm_size_t*)m_pMappedMemory = sizeof(shm_size_t); // no data inside (set just in case) - } - - void TSharedMemory::Create(const wchar_t* pszName, const TString& wstrData) - { - Create(pszName, (const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); - } - - void TSharedMemory::Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize) - { - Create(pszName, stSize); - - TIpcMutexLock lock(m_mutex); - - *(shm_size_t*)m_pMappedMemory = stSize; - memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); - } - - void TSharedMemory::Open(const wchar_t* pszName) - { - Close(); - - try - { - m_hFileMapping = OpenFileMapping(FILE_MAP_READ, FALSE, pszName); - if (!m_hFileMapping) - throw TCoreException(eErr_CannotOpenSharedMemory, L"Failed to open file mapping", LOCATION); - - // Get a pointer to the file-mapped shared memory. - m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, 0, 0); - if (!m_pMappedMemory) - throw TCoreException(eErr_CannotOpenSharedMemory, L"Mapping view of file failed", LOCATION); - } - catch (...) - { - Close(); - throw; - } - - TIpcMutexLock lock(m_mutex); - - m_stSize = *(shm_size_t*)m_pMappedMemory + sizeof(shm_size_t); - } - - void TSharedMemory::Close() throw() - { - try - { - if (m_pMappedMemory) - { - UnmapViewOfFile(m_pMappedMemory); - m_pMappedMemory = nullptr; - } - - // Close the process's handle to the file-mapping object. - if (m_hFileMapping) - { - CloseHandle(m_hFileMapping); - m_hFileMapping = nullptr; - } - } - catch (...) - { - } - } - - void TSharedMemory::Read(TString& wstrData) const - { - if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - throw TCoreException(eErr_SharedMemoryNotOpen, L"Invalid shared memory state", LOCATION); - - TIpcMutexLock lock(m_mutex); - - shm_size_t stByteSize = *(shm_size_t*)m_pMappedMemory; - if ((stByteSize % 2) != 0) - throw TCoreException(eErr_SharedMemoryInvalidFormat, L"Size of shared memory data is odd", LOCATION); - - const wchar_t* pszRealData = (const wchar_t*)(m_pMappedMemory + sizeof(shm_size_t)); - shm_size_t stCharCount = stByteSize / 2; - - if (pszRealData[stCharCount - 1] != _T('\0')) - throw TCoreException(eErr_SharedMemoryInvalidFormat, L"Shared memory data does not end with \\0", LOCATION); - - wstrData = pszRealData; - } - - void TSharedMemory::Write(const TString& wstrData) - { - Write((const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); - } - - void TSharedMemory::Write(const BYTE* pbyData, shm_size_t stSize) - { - if (stSize + sizeof(shm_size_t) > m_stSize) - throw TCoreException(eErr_BoundsExceeded, L"stSize", LOCATION); - - TIpcMutexLock lock(m_mutex); - - *(shm_size_t*)m_pMappedMemory = stSize; - memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); - } - - const BYTE* TSharedMemory::GetData() const - { - if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return nullptr; - - return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); - } - - BYTE* TSharedMemory::GetData() - { - if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return nullptr; - - return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); - } - - TSharedMemory::shm_size_t TSharedMemory::GetSharedMemorySize() const - { - if (!m_hFileMapping || !m_pMappedMemory) - return 0; - return m_stSize; - } - - TSharedMemory::shm_size_t TSharedMemory::GetDataSize() const - { - if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) - return 0; - - TIpcMutexLock lock(m_mutex); - - return *(shm_size_t*)m_pMappedMemory; - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSharedMemory.cpp +/// @date 2011/05/03 +/// @brief Contains implementation of shared memory handling classes. +// ============================================================================ +#include "stdafx.h" +#include "TSharedMemory.h" +#include +#include "ErrorCodes.h" +#include "TCoreException.h" +#include "TIpcMutexLock.h" + +namespace chcore +{ + #define MUTEX_SUFFIX _T("_Mutex") + + /////////////////////////////////////////////////////////////////////////////////////// + // TSharedMemory class + + TSharedMemory::TSharedMemory() : + m_hFileMapping(nullptr), + m_pMappedMemory(nullptr), + m_mutex(nullptr), + m_stSize(0) + { + } + + TSharedMemory::~TSharedMemory() + { + Close(); + } + + void TSharedMemory::Create(const wchar_t* pszName, shm_size_t stSize) + { + if(!pszName || pszName[ 0 ] == _T('\0')) + throw TCoreException(eErr_InvalidArgument, L"pszName", LOCATION); + if(stSize == 0) + throw TCoreException(eErr_InvalidArgument, L"stSize", LOCATION); + + Close(); + + try + { + std::wstring wstrMutexName = pszName; + wstrMutexName += MUTEX_SUFFIX; + + m_mutex.CreateMutex(wstrMutexName.c_str()); + + m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, boost::numeric_cast(stSize + sizeof(size_t)), pszName); + if (!m_hFileMapping) + throw TCoreException(eErr_CannotOpenSharedMemory, L"Failed to create file mapping", LOCATION); + if(GetLastError() == ERROR_ALREADY_EXISTS) + throw TCoreException(eErr_SharedMemoryAlreadyExists, L"File mapping already exists", LOCATION); // shared memory already exists - cannot guarantee that the size is correct + + // Get a pointer to the file-mapped shared memory. + m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_WRITE, 0, 0, 0); + if (!m_pMappedMemory) + throw TCoreException(eErr_CannotOpenSharedMemory, L"Cannot map view of file", LOCATION); + } + catch (...) + { + Close(); + throw; + } + + TIpcMutexLock lock(m_mutex); + + m_stSize = stSize + sizeof(shm_size_t); + *(shm_size_t*)m_pMappedMemory = sizeof(shm_size_t); // no data inside (set just in case) + } + + void TSharedMemory::Create(const wchar_t* pszName, const TString& wstrData) + { + Create(pszName, (const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); + } + + void TSharedMemory::Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize) + { + Create(pszName, stSize); + + TIpcMutexLock lock(m_mutex); + + *(shm_size_t*)m_pMappedMemory = stSize; + memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); + } + + void TSharedMemory::Open(const wchar_t* pszName) + { + Close(); + + try + { + m_hFileMapping = OpenFileMapping(FILE_MAP_READ, FALSE, pszName); + if (!m_hFileMapping) + throw TCoreException(eErr_CannotOpenSharedMemory, L"Failed to open file mapping", LOCATION); + + // Get a pointer to the file-mapped shared memory. + m_pMappedMemory = (BYTE*)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, 0, 0); + if (!m_pMappedMemory) + throw TCoreException(eErr_CannotOpenSharedMemory, L"Mapping view of file failed", LOCATION); + } + catch (...) + { + Close(); + throw; + } + + TIpcMutexLock lock(m_mutex); + + m_stSize = *(shm_size_t*)m_pMappedMemory + sizeof(shm_size_t); + } + + void TSharedMemory::Close() throw() + { + try + { + if (m_pMappedMemory) + { + UnmapViewOfFile(m_pMappedMemory); + m_pMappedMemory = nullptr; + } + + // Close the process's handle to the file-mapping object. + if (m_hFileMapping) + { + CloseHandle(m_hFileMapping); + m_hFileMapping = nullptr; + } + } + catch (...) + { + } + } + + void TSharedMemory::Read(TString& wstrData) const + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + throw TCoreException(eErr_SharedMemoryNotOpen, L"Invalid shared memory state", LOCATION); + + TIpcMutexLock lock(m_mutex); + + shm_size_t stByteSize = *(shm_size_t*)m_pMappedMemory; + if ((stByteSize % 2) != 0) + throw TCoreException(eErr_SharedMemoryInvalidFormat, L"Size of shared memory data is odd", LOCATION); + + const wchar_t* pszRealData = (const wchar_t*)(m_pMappedMemory + sizeof(shm_size_t)); + shm_size_t stCharCount = stByteSize / 2; + + if (pszRealData[stCharCount - 1] != _T('\0')) + throw TCoreException(eErr_SharedMemoryInvalidFormat, L"Shared memory data does not end with \\0", LOCATION); + + wstrData = pszRealData; + } + + void TSharedMemory::Write(const TString& wstrData) + { + Write((const BYTE*)wstrData.c_str(), boost::numeric_cast((wstrData.GetLength() + 1) * sizeof(wchar_t))); + } + + void TSharedMemory::Write(const BYTE* pbyData, shm_size_t stSize) + { + if (stSize + sizeof(shm_size_t) > m_stSize) + throw TCoreException(eErr_BoundsExceeded, L"stSize", LOCATION); + + TIpcMutexLock lock(m_mutex); + + *(shm_size_t*)m_pMappedMemory = stSize; + memcpy(m_pMappedMemory + sizeof(shm_size_t), pbyData, stSize); + } + + const BYTE* TSharedMemory::GetData() const + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return nullptr; + + return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); + } + + BYTE* TSharedMemory::GetData() + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return nullptr; + + return (BYTE*)m_pMappedMemory + sizeof(shm_size_t); + } + + TSharedMemory::shm_size_t TSharedMemory::GetSharedMemorySize() const + { + if (!m_hFileMapping || !m_pMappedMemory) + return 0; + return m_stSize; + } + + TSharedMemory::shm_size_t TSharedMemory::GetDataSize() const + { + if (!m_hFileMapping || !m_pMappedMemory || m_stSize <= sizeof(shm_size_t)) + return 0; + + TIpcMutexLock lock(m_mutex); + + return *(shm_size_t*)m_pMappedMemory; + } +} Index: src/libchcore/TSharedMemory.h =================================================================== diff -u -r306fbe693c70290af9de9a5779084a697de22d75 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSharedMemory.h (.../TSharedMemory.h) (revision 306fbe693c70290af9de9a5779084a697de22d75) +++ src/libchcore/TSharedMemory.h (.../TSharedMemory.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,67 +1,67 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSharedMemory.h -/// @date 2011/05/03 -/// @brief Contains shared memory support classes. -// ============================================================================ -#ifndef __TSHAREDMEMORY_H__ -#define __TSHAREDMEMORY_H__ - -#include "TString.h" -#include "TIpcMutex.h" - -namespace chcore -{ - class LIBCHCORE_API TSharedMemory - { - public: - typedef unsigned int shm_size_t; - - public: - TSharedMemory(); - ~TSharedMemory(); - - void Create(const wchar_t* pszName, shm_size_t stSize); - void Create(const wchar_t* pszName, const TString& wstrData); - void Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize); - - void Open(const wchar_t* pszName); - void Close() throw(); - - void Read(TString& wstrData) const; - void Write(const TString& wstrData); - void Write(const BYTE* pbyData, shm_size_t stSize); - - // below are the unsafe functions (i.e. not protected with mutex) - const BYTE* GetData() const; - BYTE* GetData(); - - shm_size_t GetSharedMemorySize() const; - shm_size_t GetDataSize() const; - - private: - HANDLE m_hFileMapping; - BYTE* m_pMappedMemory; - shm_size_t m_stSize; // contains full size of the allocated shared memory (in case we created the memory), size of occupied memory in case we opened the memory. - - mutable TIpcMutex m_mutex; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSharedMemory.h +/// @date 2011/05/03 +/// @brief Contains shared memory support classes. +// ============================================================================ +#ifndef __TSHAREDMEMORY_H__ +#define __TSHAREDMEMORY_H__ + +#include "TString.h" +#include "TIpcMutex.h" + +namespace chcore +{ + class LIBCHCORE_API TSharedMemory + { + public: + typedef unsigned int shm_size_t; + + public: + TSharedMemory(); + ~TSharedMemory(); + + void Create(const wchar_t* pszName, shm_size_t stSize); + void Create(const wchar_t* pszName, const TString& wstrData); + void Create(const wchar_t* pszName, const BYTE* pbyData, shm_size_t stSize); + + void Open(const wchar_t* pszName); + void Close() throw(); + + void Read(TString& wstrData) const; + void Write(const TString& wstrData); + void Write(const BYTE* pbyData, shm_size_t stSize); + + // below are the unsafe functions (i.e. not protected with mutex) + const BYTE* GetData() const; + BYTE* GetData(); + + shm_size_t GetSharedMemorySize() const; + shm_size_t GetDataSize() const; + + private: + HANDLE m_hFileMapping; + BYTE* m_pMappedMemory; + shm_size_t m_stSize; // contains full size of the allocated shared memory (in case we created the memory), size of occupied memory in case we opened the memory. + + mutable TIpcMutex m_mutex; + }; +} + +#endif Index: src/libchcore/TSharedModificationTracker.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSharedModificationTracker.h (.../TSharedModificationTracker.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSharedModificationTracker.h (.../TSharedModificationTracker.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,115 +1,115 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSHAREDMODIFICATIONTRACKER_H__ -#define __TSHAREDMODIFICATIONTRACKER_H__ - -namespace chcore -{ - template - class TSharedModificationTracker - { - public: - typedef T value_type; - - public: - explicit TSharedModificationTracker(Bitset& rBitset) : - m_tValue(), - m_rBitset(rBitset) - { - MarkAsModified(); - } - - TSharedModificationTracker(const TSharedModificationTracker& rSrc) = delete; - - TSharedModificationTracker(const TSharedModificationTracker& rSrc, Bitset& rBitset) : - m_tValue(rSrc.m_tValue), - m_rBitset(rBitset) - { - m_rBitset[ChangeBit] = rSrc.m_rBitset[ChangeBit]; - } - - template - TSharedModificationTracker(Bitset& rBitset, const V&... rValues) : - m_tValue(rValues...), - m_rBitset(rBitset) - { - MarkAsModified(); - } - - TSharedModificationTracker& operator=(const TSharedModificationTracker& rValue) - { - if (this != &rValue) - { - m_tValue = rValue.m_tValue; - m_rBitset[ChangeBit] = rValue.m_rBitset[ChangeBit]; - } - - return *this; - } - - template - TSharedModificationTracker& operator=(const V& rValue) - { - if (m_tValue != rValue) - { - m_tValue = rValue; - MarkAsModified(); - } - - return *this; - } - - operator const T&() const - { - return m_tValue; - } - - const T& Get() const - { - return m_tValue; - } - - T& Modify() - { - MarkAsModified(); - return m_tValue; - } - - bool IsModified() const - { - return m_rBitset[ChangeBit]; - } - - void MarkAsModified() - { - m_rBitset[ChangeBit] = true; - } - - void MarkAsUnmodified() - { - m_rBitset[ChangeBit] = false; - } - - private: - T m_tValue; - Bitset& m_rBitset; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSHAREDMODIFICATIONTRACKER_H__ +#define __TSHAREDMODIFICATIONTRACKER_H__ + +namespace chcore +{ + template + class TSharedModificationTracker + { + public: + typedef T value_type; + + public: + explicit TSharedModificationTracker(Bitset& rBitset) : + m_tValue(), + m_rBitset(rBitset) + { + MarkAsModified(); + } + + TSharedModificationTracker(const TSharedModificationTracker& rSrc) = delete; + + TSharedModificationTracker(const TSharedModificationTracker& rSrc, Bitset& rBitset) : + m_tValue(rSrc.m_tValue), + m_rBitset(rBitset) + { + m_rBitset[ChangeBit] = rSrc.m_rBitset[ChangeBit]; + } + + template + TSharedModificationTracker(Bitset& rBitset, const V&... rValues) : + m_tValue(rValues...), + m_rBitset(rBitset) + { + MarkAsModified(); + } + + TSharedModificationTracker& operator=(const TSharedModificationTracker& rValue) + { + if (this != &rValue) + { + m_tValue = rValue.m_tValue; + m_rBitset[ChangeBit] = rValue.m_rBitset[ChangeBit]; + } + + return *this; + } + + template + TSharedModificationTracker& operator=(const V& rValue) + { + if (m_tValue != rValue) + { + m_tValue = rValue; + MarkAsModified(); + } + + return *this; + } + + operator const T&() const + { + return m_tValue; + } + + const T& Get() const + { + return m_tValue; + } + + T& Modify() + { + MarkAsModified(); + return m_tValue; + } + + bool IsModified() const + { + return m_rBitset[ChangeBit]; + } + + void MarkAsModified() + { + m_rBitset[ChangeBit] = true; + } + + void MarkAsUnmodified() + { + m_rBitset[ChangeBit] = false; + } + + private: + T m_tValue; + Bitset& m_rBitset; + }; +} + +#endif Index: src/libchcore/TSimpleTimer.cpp =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSimpleTimer.cpp (.../TSimpleTimer.cpp) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSimpleTimer.cpp (.../TSimpleTimer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,104 +1,104 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSimpleTimer.h" -#include "TTimestampProviderTickCount.h" - -namespace chcore -{ - TSimpleTimer::TSimpleTimer(bool bAutostart, const ITimestampProviderPtr& spTimestampProvider) : - m_spTimestampProvider(spTimestampProvider), - m_bStarted(false), - m_ullLastTime(0), - m_ullTotalTime(0) - { - if (!spTimestampProvider) - m_spTimestampProvider = std::make_shared(); - - if (bAutostart) - Start(); - } - - TSimpleTimer::~TSimpleTimer() - { - } - - void TSimpleTimer::Start() - { - if (!m_bStarted) - { - m_bStarted = true; - m_ullLastTime = m_spTimestampProvider->GetCurrentTimestamp(); - } - } - - unsigned long long TSimpleTimer::Stop() - { - if (m_bStarted) - { - Tick(); - m_bStarted = false; - } - - return m_ullTotalTime; - } - - unsigned long long TSimpleTimer::Tick() - { - unsigned long long ullCurrent = m_spTimestampProvider->GetCurrentTimestamp(); - if (m_bStarted) - m_ullTotalTime += ullCurrent - m_ullLastTime; - m_ullLastTime = ullCurrent; - - return ullCurrent; - } - - unsigned long long TSimpleTimer::Checkpoint() - { - if (m_bStarted) - { - Tick(); - unsigned long long ullCurrentTotal = m_ullTotalTime; - m_ullTotalTime = 0; - - return ullCurrentTotal; - } - else - return 0; - } - - void TSimpleTimer::Reset() - { - m_bStarted = false; - m_ullLastTime = 0; - m_ullTotalTime = 0; - } - - void TSimpleTimer::Init(unsigned long long ullTotalTime) - { - Stop(); - m_ullTotalTime = ullTotalTime; - m_ullLastTime = 0; - } - - bool TSimpleTimer::IsRunning() const - { - return m_bStarted; - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSimpleTimer.h" +#include "TTimestampProviderTickCount.h" + +namespace chcore +{ + TSimpleTimer::TSimpleTimer(bool bAutostart, const ITimestampProviderPtr& spTimestampProvider) : + m_spTimestampProvider(spTimestampProvider), + m_bStarted(false), + m_ullLastTime(0), + m_ullTotalTime(0) + { + if (!spTimestampProvider) + m_spTimestampProvider = std::make_shared(); + + if (bAutostart) + Start(); + } + + TSimpleTimer::~TSimpleTimer() + { + } + + void TSimpleTimer::Start() + { + if (!m_bStarted) + { + m_bStarted = true; + m_ullLastTime = m_spTimestampProvider->GetCurrentTimestamp(); + } + } + + unsigned long long TSimpleTimer::Stop() + { + if (m_bStarted) + { + Tick(); + m_bStarted = false; + } + + return m_ullTotalTime; + } + + unsigned long long TSimpleTimer::Tick() + { + unsigned long long ullCurrent = m_spTimestampProvider->GetCurrentTimestamp(); + if (m_bStarted) + m_ullTotalTime += ullCurrent - m_ullLastTime; + m_ullLastTime = ullCurrent; + + return ullCurrent; + } + + unsigned long long TSimpleTimer::Checkpoint() + { + if (m_bStarted) + { + Tick(); + unsigned long long ullCurrentTotal = m_ullTotalTime; + m_ullTotalTime = 0; + + return ullCurrentTotal; + } + else + return 0; + } + + void TSimpleTimer::Reset() + { + m_bStarted = false; + m_ullLastTime = 0; + m_ullTotalTime = 0; + } + + void TSimpleTimer::Init(unsigned long long ullTotalTime) + { + Stop(); + m_ullTotalTime = ullTotalTime; + m_ullLastTime = 0; + } + + bool TSimpleTimer::IsRunning() const + { + return m_bStarted; + } +} Index: src/libchcore/TSimpleTimer.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSimpleTimer.h (.../TSimpleTimer.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSimpleTimer.h (.../TSimpleTimer.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,59 +1,59 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSIMPLETIMER_H__ -#define __TSIMPLETIMER_H__ - -#include "libchcore.h" -#include "ITimestampProvider.h" - -namespace chcore -{ - class LIBCHCORE_API TSimpleTimer - { - public: - TSimpleTimer(bool bAutostart = false, const ITimestampProviderPtr& spTimestampProvider = ITimestampProviderPtr()); - ~TSimpleTimer(); - - void Init(unsigned long long ullTotalTime); - - void Start(); - unsigned long long Stop(); // returns total time - unsigned long long Tick(); // returns current timestamp - - unsigned long long Checkpoint(); // returns current total time and restarts the timer - - void Reset(); - - bool IsRunning() const; - unsigned long long GetTotalTime() const { return m_ullTotalTime; } - unsigned long long GetLastTimestamp() const { return m_ullLastTime; } - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - ITimestampProviderPtr m_spTimestampProvider; -#pragma warning(pop) - - bool m_bStarted; - unsigned long long m_ullTotalTime; // total time measured - unsigned long long m_ullLastTime; // last processed time - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSIMPLETIMER_H__ +#define __TSIMPLETIMER_H__ + +#include "libchcore.h" +#include "ITimestampProvider.h" + +namespace chcore +{ + class LIBCHCORE_API TSimpleTimer + { + public: + TSimpleTimer(bool bAutostart = false, const ITimestampProviderPtr& spTimestampProvider = ITimestampProviderPtr()); + ~TSimpleTimer(); + + void Init(unsigned long long ullTotalTime); + + void Start(); + unsigned long long Stop(); // returns total time + unsigned long long Tick(); // returns current timestamp + + unsigned long long Checkpoint(); // returns current total time and restarts the timer + + void Reset(); + + bool IsRunning() const; + unsigned long long GetTotalTime() const { return m_ullTotalTime; } + unsigned long long GetLastTimestamp() const { return m_ullLastTime; } + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + ITimestampProviderPtr m_spTimestampProvider; +#pragma warning(pop) + + bool m_bStarted; + unsigned long long m_ullTotalTime; // total time measured + unsigned long long m_ullLastTime; // last processed time + }; +} + +#endif Index: src/libchcore/TSparseRangeMap.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSparseRangeMap.cpp (.../TSparseRangeMap.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TSparseRangeMap.cpp (.../TSparseRangeMap.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,113 +1,113 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSparseRangeMap.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TSparseRangeMap::TSparseRangeMap() - { - } - - TSparseRangeMap::~TSparseRangeMap() - { - } - - void TSparseRangeMap::Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd) - { - if (fsRangeEnd < fsRangeStart) - std::swap(fsRangeStart, fsRangeEnd); - - std::pair pairInsert = m_mapRanges.emplace(std::make_pair(fsRangeStart, fsRangeEnd)); - RangeMap::iterator iterInsertedRange = pairInsert.first; - if (!pairInsert.second) - { - // range with fsRangeStart already exists; update it with the increased range (if bigger than the existing one) - if (fsRangeEnd > iterInsertedRange->second) - iterInsertedRange->second = fsRangeEnd; - else - return; // new range overlaps with old one and is smaller; does not change the state of internal map and no reorganization is needed - } - else - { - // element inserted successfully; since it can overlap the previous range in the map, we need to start merging ranges from this previous element - if (iterInsertedRange != m_mapRanges.begin()) - iterInsertedRange = std::prev(iterInsertedRange); - else if (m_mapRanges.size() == 1) - return; // this is the only element currently in the map; no need to process further. - } - - // merge subsequent ranges - file_size_t fsCurrentRangeEnd = iterInsertedRange->second; - - RangeMap::iterator iterRange = std::next(iterInsertedRange); - - while (iterRange != m_mapRanges.end()) - { - if (iterRange->first <= fsCurrentRangeEnd + 1) - { - // next range overlaps with the inserted one - merge them - if (iterRange->second > iterInsertedRange->second) - iterInsertedRange->second = iterRange->second; - iterRange = m_mapRanges.erase(iterRange); - } - else - break; - } - } - - size_t TSparseRangeMap::GetRangeCount() const - { - return m_mapRanges.size(); - } - - void TSparseRangeMap::GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const - { - if (stIndex >= m_mapRanges.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - RangeMap::const_iterator iterMap = m_mapRanges.begin(); - std::advance(iterMap, stIndex); - - rfsRangeStart = iterMap->first; - rfsRangeEnd = iterMap->second; - } - - bool TSparseRangeMap::OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const - { - if (fsRangeEnd < fsRangeStart) - std::swap(fsRangeStart, fsRangeEnd); - - RangeMap::const_iterator iterStart = m_mapRanges.lower_bound(fsRangeStart); - if (iterStart != m_mapRanges.begin()) - iterStart = std::prev(iterStart); - - RangeMap::const_iterator iterEnd = m_mapRanges.upper_bound(fsRangeEnd); - while (iterStart != iterEnd) - { - if (fsRangeStart <= iterStart->second && iterStart->first <= fsRangeEnd) - return true; - ++iterStart; - } - - return false; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSparseRangeMap.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TSparseRangeMap::TSparseRangeMap() + { + } + + TSparseRangeMap::~TSparseRangeMap() + { + } + + void TSparseRangeMap::Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd) + { + if (fsRangeEnd < fsRangeStart) + std::swap(fsRangeStart, fsRangeEnd); + + std::pair pairInsert = m_mapRanges.emplace(std::make_pair(fsRangeStart, fsRangeEnd)); + RangeMap::iterator iterInsertedRange = pairInsert.first; + if (!pairInsert.second) + { + // range with fsRangeStart already exists; update it with the increased range (if bigger than the existing one) + if (fsRangeEnd > iterInsertedRange->second) + iterInsertedRange->second = fsRangeEnd; + else + return; // new range overlaps with old one and is smaller; does not change the state of internal map and no reorganization is needed + } + else + { + // element inserted successfully; since it can overlap the previous range in the map, we need to start merging ranges from this previous element + if (iterInsertedRange != m_mapRanges.begin()) + iterInsertedRange = std::prev(iterInsertedRange); + else if (m_mapRanges.size() == 1) + return; // this is the only element currently in the map; no need to process further. + } + + // merge subsequent ranges + file_size_t fsCurrentRangeEnd = iterInsertedRange->second; + + RangeMap::iterator iterRange = std::next(iterInsertedRange); + + while (iterRange != m_mapRanges.end()) + { + if (iterRange->first <= fsCurrentRangeEnd + 1) + { + // next range overlaps with the inserted one - merge them + if (iterRange->second > iterInsertedRange->second) + iterInsertedRange->second = iterRange->second; + iterRange = m_mapRanges.erase(iterRange); + } + else + break; + } + } + + size_t TSparseRangeMap::GetRangeCount() const + { + return m_mapRanges.size(); + } + + void TSparseRangeMap::GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const + { + if (stIndex >= m_mapRanges.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + RangeMap::const_iterator iterMap = m_mapRanges.begin(); + std::advance(iterMap, stIndex); + + rfsRangeStart = iterMap->first; + rfsRangeEnd = iterMap->second; + } + + bool TSparseRangeMap::OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const + { + if (fsRangeEnd < fsRangeStart) + std::swap(fsRangeStart, fsRangeEnd); + + RangeMap::const_iterator iterStart = m_mapRanges.lower_bound(fsRangeStart); + if (iterStart != m_mapRanges.begin()) + iterStart = std::prev(iterStart); + + RangeMap::const_iterator iterEnd = m_mapRanges.upper_bound(fsRangeEnd); + while (iterStart != iterEnd) + { + if (fsRangeStart <= iterStart->second && iterStart->first <= fsRangeEnd) + return true; + ++iterStart; + } + + return false; + } +} Index: src/libchcore/TSparseRangeMap.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSparseRangeMap.h (.../TSparseRangeMap.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSparseRangeMap.h (.../TSparseRangeMap.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,51 +1,51 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSparseRangeMap_H__ -#define __TSparseRangeMap_H__ - -#include "libchcore.h" -#include "CommonDataTypes.h" - -namespace chcore -{ - class LIBCHCORE_API TSparseRangeMap - { - public: - TSparseRangeMap(); - ~TSparseRangeMap(); - - void Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd); - - size_t GetRangeCount() const; - void GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const; - - bool OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const; - - private: - using RangePair = std::pair; - using RangeMap = std::map; - -#pragma warning(push) -#pragma warning(disable: 4251) - RangeMap m_mapRanges; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSparseRangeMap_H__ +#define __TSparseRangeMap_H__ + +#include "libchcore.h" +#include "CommonDataTypes.h" + +namespace chcore +{ + class LIBCHCORE_API TSparseRangeMap + { + public: + TSparseRangeMap(); + ~TSparseRangeMap(); + + void Insert(file_size_t fsRangeStart, file_size_t fsRangeEnd); + + size_t GetRangeCount() const; + void GetRangeAt(size_t stIndex, file_size_t& rfsRangeStart, file_size_t& rfsRangeEnd) const; + + bool OverlapsRange(file_size_t fsRangeStart, file_size_t fsRangeEnd) const; + + private: + using RangePair = std::pair; + using RangeMap = std::map; + +#pragma warning(push) +#pragma warning(disable: 4251) + RangeMap m_mapRanges; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSpeedTracker.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSpeedTracker.cpp (.../TSpeedTracker.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSpeedTracker.cpp (.../TSpeedTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,232 +1,232 @@ -#include "stdafx.h" -#include "TSpeedTracker.h" -#include -#include -#include "ErrorCodes.h" -#include "TCoreException.h" -#include "MathFunctions.h" -#include -#include "TStringArray.h" - -namespace chcore -{ - TSpeedTracker::TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime) : - m_stRequiredSamples(ullSampleTime ? boost::numeric_cast(ullTrackTime / ullSampleTime) : 0), - m_ullSampleTime(ullSampleTime), - m_dSamplesPerSecond(ullSampleTime != 0 ? 1000.0 / ullSampleTime : 0.0), - m_dPartialSpeedNotInSamples(0), - m_ullTimeIntervalNotInSamples(0), - m_stNextSamplePos(0), - m_ullLastTimestamp(std::numeric_limits::max()), - m_ullZeroIntervalData(0) - { - if(ullSampleTime == 0) - throw TCoreException(eErr_InvalidArgument, L"ullSampleTime", LOCATION); - if(m_stRequiredSamples == 0) - throw TCoreException(eErr_InvalidArgument, L"m_stRequiredSamples", LOCATION); - std::fill_n(std::inserter(m_vSamples, m_vSamples.end()), m_stRequiredSamples, 0.0); - } - - void TSpeedTracker::Clear() - { - m_dPartialSpeedNotInSamples = 0; - m_ullTimeIntervalNotInSamples = 0; - m_stNextSamplePos = 0; - m_ullLastTimestamp = std::numeric_limits::max(); - m_ullZeroIntervalData = 0; - std::fill(m_vSamples.begin(), m_vSamples.end(), 0.0); - } - - void TSpeedTracker::AddSample(unsigned long long ullValue, unsigned long long ullTimestamp) - { - // if this is the first sample ever added (after construction or after clear) then - // we don't have time interval yet - just remember the timestamp and ignore value - if (m_ullLastTimestamp == std::numeric_limits::max()) - { - m_ullLastTimestamp = ullTimestamp; - return; - } - - // sanity check - make sure the data is valid - if (ullTimestamp < m_ullLastTimestamp) - throw TCoreException(eErr_InvalidArgument, L"ullTimestamp", LOCATION); - - // calculate the interval since the time last sample was added - unsigned long long ullInterval = ullTimestamp - m_ullLastTimestamp; - m_ullLastTimestamp = ullTimestamp; - - if (ullInterval == 0) // special case 0: if interval is 0 - put the data sample somewhere for future use - { - m_ullZeroIntervalData += ullValue; - return; - } - else if (ullInterval >= m_ullSampleTime * m_stRequiredSamples) // special case 1: interval is bigger than what we track - { - m_stNextSamplePos = 0; - m_dPartialSpeedNotInSamples = 0.0; - m_ullTimeIntervalNotInSamples = 0; - m_ullZeroIntervalData = 0; - - double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); - std::fill(m_vSamples.begin(), m_vSamples.end(), dSpeed); - return; - } - else - { - // append the data from previous zero-interval samples - ullValue += m_ullZeroIntervalData; - m_ullZeroIntervalData = 0; - } - - // calculate speed - double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); - - // finalize the incomplete sample and adjust the input data - FinalizeIncompleteSample(dSpeed, ullInterval); - - // deal with the full samples - AddCompleteSamples(dSpeed, ullInterval); - - // and finally prepare the incomplete sample data for future use - PrepareIncompleteSample(ullInterval, dSpeed); - } - - double TSpeedTracker::GetSpeed() const - { - double dResult = 0.0; - - if (m_ullTimeIntervalNotInSamples != 0) - { - dResult = CalculateIncompleteSampleNormalizedSpeed(); - - for (size_t stIndex = 0; stIndex < m_vSamples.size(); ++stIndex) - { - if (stIndex != m_stNextSamplePos) - dResult += m_vSamples[stIndex]; - } - } - else - dResult = std::accumulate(m_vSamples.begin(), m_vSamples.end(), 0.0); - - return dResult / m_vSamples.size() * m_dSamplesPerSecond; - } - - size_t TSpeedTracker::GetNextSampleIndexAndIncrease() - { - size_t stResult = m_stNextSamplePos++; - if (m_stNextSamplePos >= m_vSamples.size()) - m_stNextSamplePos = 0; - return stResult; - } - - double TSpeedTracker::NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime) - { - return Math::Div64(ullNormalizeTime, ullTime) * ullValue; - } - - void TSpeedTracker::FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval) - { - if (m_ullTimeIntervalNotInSamples == 0 || m_dPartialSpeedNotInSamples == 0.0 || ullInterval == 0) - return; - - // how much data do we need? - unsigned long long ullIntervalStillNeeded = m_ullSampleTime - m_ullTimeIntervalNotInSamples; - if (ullInterval < ullIntervalStillNeeded) - { - // we can only add the next partial sample, but cannot finalize - m_ullTimeIntervalNotInSamples += ullInterval; - m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullInterval, m_ullSampleTime); - ullInterval = 0; - } - else - { - // going to finalize sample - m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullIntervalStillNeeded, m_ullSampleTime); - - m_vSamples[GetNextSampleIndexAndIncrease()] = m_dPartialSpeedNotInSamples; - ullInterval -= ullIntervalStillNeeded; - - m_dPartialSpeedNotInSamples = 0.0; - m_ullTimeIntervalNotInSamples = 0; - } - } - - void TSpeedTracker::AddCompleteSamples(double dSpeed, unsigned long long& ullInterval) - { - size_t stSamplesCount = boost::numeric_cast(std::min(ullInterval / m_ullSampleTime, (unsigned long long)m_stRequiredSamples)); - - // fill the container with full samples - while (stSamplesCount--) - { - m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; - } - - ullInterval = ullInterval % m_ullSampleTime; - } - - double TSpeedTracker::CalculateIncompleteSampleNormalizedSpeed() const - { - // get the speed for incomplete sample - double dIncompleteSamplePercentage = Math::Div64(m_ullTimeIntervalNotInSamples, m_ullSampleTime); - double dResult = m_dPartialSpeedNotInSamples + (1.0 - dIncompleteSamplePercentage) * m_vSamples[m_stNextSamplePos]; - - return dResult; - } - - void TSpeedTracker::PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed) - { - if (ullInterval > 0) - { - // we can only add the next partial sample, but cannot finalize - m_ullTimeIntervalNotInSamples = ullInterval; - m_dPartialSpeedNotInSamples = dSpeed * Math::Div64(ullInterval, m_ullSampleTime); - } - } - - TString TSpeedTracker::ToString() const - { - TString strData; - - strData += boost::lexical_cast(m_stNextSamplePos).c_str(); - strData += _T(";"); - - strData += boost::lexical_cast(m_dPartialSpeedNotInSamples).c_str(); - strData += _T(";"); - strData += boost::lexical_cast(m_ullTimeIntervalNotInSamples).c_str(); - strData += _T(";"); - strData += boost::lexical_cast(m_ullZeroIntervalData).c_str(); - strData += _T(";"); - - for(double dVal : m_vSamples) - { - strData += boost::lexical_cast(dVal).c_str(); - strData += _T(";"); - } - - strData.TrimRightSelf(_T(";")); - - return strData; - } - - void TSpeedTracker::FromString(const TString& strData) - { - TStringArray arrStrings; - strData.Split(_T(";"), arrStrings); - - const size_t SerializedMembers = 4; - if (arrStrings.GetCount() != m_stRequiredSamples + SerializedMembers) - throw TCoreException(eErr_InvalidArgument, L"strData", LOCATION); - - Clear(); - - m_stNextSamplePos = boost::lexical_cast(arrStrings.GetAt(0).c_str()); - m_dPartialSpeedNotInSamples = boost::lexical_cast(arrStrings.GetAt(1).c_str()); - m_ullTimeIntervalNotInSamples = boost::lexical_cast(arrStrings.GetAt(2).c_str()); - m_ullZeroIntervalData = boost::lexical_cast((PCTSTR)arrStrings.GetAt(3).c_str()); - - for (size_t stIndex = 4; stIndex < arrStrings.GetCount(); ++stIndex) - { - m_vSamples[stIndex - 4] = boost::lexical_cast(arrStrings.GetAt(stIndex).c_str()); - } - } -} +#include "stdafx.h" +#include "TSpeedTracker.h" +#include +#include +#include "ErrorCodes.h" +#include "TCoreException.h" +#include "MathFunctions.h" +#include +#include "TStringArray.h" + +namespace chcore +{ + TSpeedTracker::TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime) : + m_stRequiredSamples(ullSampleTime ? boost::numeric_cast(ullTrackTime / ullSampleTime) : 0), + m_ullSampleTime(ullSampleTime), + m_dSamplesPerSecond(ullSampleTime != 0 ? 1000.0 / ullSampleTime : 0.0), + m_dPartialSpeedNotInSamples(0), + m_ullTimeIntervalNotInSamples(0), + m_stNextSamplePos(0), + m_ullLastTimestamp(std::numeric_limits::max()), + m_ullZeroIntervalData(0) + { + if(ullSampleTime == 0) + throw TCoreException(eErr_InvalidArgument, L"ullSampleTime", LOCATION); + if(m_stRequiredSamples == 0) + throw TCoreException(eErr_InvalidArgument, L"m_stRequiredSamples", LOCATION); + std::fill_n(std::inserter(m_vSamples, m_vSamples.end()), m_stRequiredSamples, 0.0); + } + + void TSpeedTracker::Clear() + { + m_dPartialSpeedNotInSamples = 0; + m_ullTimeIntervalNotInSamples = 0; + m_stNextSamplePos = 0; + m_ullLastTimestamp = std::numeric_limits::max(); + m_ullZeroIntervalData = 0; + std::fill(m_vSamples.begin(), m_vSamples.end(), 0.0); + } + + void TSpeedTracker::AddSample(unsigned long long ullValue, unsigned long long ullTimestamp) + { + // if this is the first sample ever added (after construction or after clear) then + // we don't have time interval yet - just remember the timestamp and ignore value + if (m_ullLastTimestamp == std::numeric_limits::max()) + { + m_ullLastTimestamp = ullTimestamp; + return; + } + + // sanity check - make sure the data is valid + if (ullTimestamp < m_ullLastTimestamp) + throw TCoreException(eErr_InvalidArgument, L"ullTimestamp", LOCATION); + + // calculate the interval since the time last sample was added + unsigned long long ullInterval = ullTimestamp - m_ullLastTimestamp; + m_ullLastTimestamp = ullTimestamp; + + if (ullInterval == 0) // special case 0: if interval is 0 - put the data sample somewhere for future use + { + m_ullZeroIntervalData += ullValue; + return; + } + else if (ullInterval >= m_ullSampleTime * m_stRequiredSamples) // special case 1: interval is bigger than what we track + { + m_stNextSamplePos = 0; + m_dPartialSpeedNotInSamples = 0.0; + m_ullTimeIntervalNotInSamples = 0; + m_ullZeroIntervalData = 0; + + double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); + std::fill(m_vSamples.begin(), m_vSamples.end(), dSpeed); + return; + } + else + { + // append the data from previous zero-interval samples + ullValue += m_ullZeroIntervalData; + m_ullZeroIntervalData = 0; + } + + // calculate speed + double dSpeed = NormalizeValueByTime(ullValue, ullInterval, m_ullSampleTime); + + // finalize the incomplete sample and adjust the input data + FinalizeIncompleteSample(dSpeed, ullInterval); + + // deal with the full samples + AddCompleteSamples(dSpeed, ullInterval); + + // and finally prepare the incomplete sample data for future use + PrepareIncompleteSample(ullInterval, dSpeed); + } + + double TSpeedTracker::GetSpeed() const + { + double dResult = 0.0; + + if (m_ullTimeIntervalNotInSamples != 0) + { + dResult = CalculateIncompleteSampleNormalizedSpeed(); + + for (size_t stIndex = 0; stIndex < m_vSamples.size(); ++stIndex) + { + if (stIndex != m_stNextSamplePos) + dResult += m_vSamples[stIndex]; + } + } + else + dResult = std::accumulate(m_vSamples.begin(), m_vSamples.end(), 0.0); + + return dResult / m_vSamples.size() * m_dSamplesPerSecond; + } + + size_t TSpeedTracker::GetNextSampleIndexAndIncrease() + { + size_t stResult = m_stNextSamplePos++; + if (m_stNextSamplePos >= m_vSamples.size()) + m_stNextSamplePos = 0; + return stResult; + } + + double TSpeedTracker::NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime) + { + return Math::Div64(ullNormalizeTime, ullTime) * ullValue; + } + + void TSpeedTracker::FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval) + { + if (m_ullTimeIntervalNotInSamples == 0 || m_dPartialSpeedNotInSamples == 0.0 || ullInterval == 0) + return; + + // how much data do we need? + unsigned long long ullIntervalStillNeeded = m_ullSampleTime - m_ullTimeIntervalNotInSamples; + if (ullInterval < ullIntervalStillNeeded) + { + // we can only add the next partial sample, but cannot finalize + m_ullTimeIntervalNotInSamples += ullInterval; + m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullInterval, m_ullSampleTime); + ullInterval = 0; + } + else + { + // going to finalize sample + m_dPartialSpeedNotInSamples += dSpeed * Math::Div64(ullIntervalStillNeeded, m_ullSampleTime); + + m_vSamples[GetNextSampleIndexAndIncrease()] = m_dPartialSpeedNotInSamples; + ullInterval -= ullIntervalStillNeeded; + + m_dPartialSpeedNotInSamples = 0.0; + m_ullTimeIntervalNotInSamples = 0; + } + } + + void TSpeedTracker::AddCompleteSamples(double dSpeed, unsigned long long& ullInterval) + { + size_t stSamplesCount = boost::numeric_cast(std::min(ullInterval / m_ullSampleTime, (unsigned long long)m_stRequiredSamples)); + + // fill the container with full samples + while (stSamplesCount--) + { + m_vSamples[GetNextSampleIndexAndIncrease()] = dSpeed; + } + + ullInterval = ullInterval % m_ullSampleTime; + } + + double TSpeedTracker::CalculateIncompleteSampleNormalizedSpeed() const + { + // get the speed for incomplete sample + double dIncompleteSamplePercentage = Math::Div64(m_ullTimeIntervalNotInSamples, m_ullSampleTime); + double dResult = m_dPartialSpeedNotInSamples + (1.0 - dIncompleteSamplePercentage) * m_vSamples[m_stNextSamplePos]; + + return dResult; + } + + void TSpeedTracker::PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed) + { + if (ullInterval > 0) + { + // we can only add the next partial sample, but cannot finalize + m_ullTimeIntervalNotInSamples = ullInterval; + m_dPartialSpeedNotInSamples = dSpeed * Math::Div64(ullInterval, m_ullSampleTime); + } + } + + TString TSpeedTracker::ToString() const + { + TString strData; + + strData += boost::lexical_cast(m_stNextSamplePos).c_str(); + strData += _T(";"); + + strData += boost::lexical_cast(m_dPartialSpeedNotInSamples).c_str(); + strData += _T(";"); + strData += boost::lexical_cast(m_ullTimeIntervalNotInSamples).c_str(); + strData += _T(";"); + strData += boost::lexical_cast(m_ullZeroIntervalData).c_str(); + strData += _T(";"); + + for(double dVal : m_vSamples) + { + strData += boost::lexical_cast(dVal).c_str(); + strData += _T(";"); + } + + strData.TrimRightSelf(_T(";")); + + return strData; + } + + void TSpeedTracker::FromString(const TString& strData) + { + TStringArray arrStrings; + strData.Split(_T(";"), arrStrings); + + const size_t SerializedMembers = 4; + if (arrStrings.GetCount() != m_stRequiredSamples + SerializedMembers) + throw TCoreException(eErr_InvalidArgument, L"strData", LOCATION); + + Clear(); + + m_stNextSamplePos = boost::lexical_cast(arrStrings.GetAt(0).c_str()); + m_dPartialSpeedNotInSamples = boost::lexical_cast(arrStrings.GetAt(1).c_str()); + m_ullTimeIntervalNotInSamples = boost::lexical_cast(arrStrings.GetAt(2).c_str()); + m_ullZeroIntervalData = boost::lexical_cast((PCTSTR)arrStrings.GetAt(3).c_str()); + + for (size_t stIndex = 4; stIndex < arrStrings.GetCount(); ++stIndex) + { + m_vSamples[stIndex - 4] = boost::lexical_cast(arrStrings.GetAt(stIndex).c_str()); + } + } +} Index: src/libchcore/TSpeedTracker.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSpeedTracker.h (.../TSpeedTracker.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TSpeedTracker.h (.../TSpeedTracker.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -#ifndef __TSPEEDTRACKER_H__ -#define __TSPEEDTRACKER_H__ - -#include "TString.h" - -namespace chcore -{ - class TSpeedTracker - { - public: - TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime); - - void AddSample(unsigned long long ullValue, unsigned long long ullTimestamp); - void Clear(); - - // retrieves speed per second - double GetSpeed() const; - - TString ToString() const; - void FromString(const TString& strData); - - private: - TSpeedTracker(const TSpeedTracker&); - TSpeedTracker& operator=(const TSpeedTracker&); - - static double NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime = 1000); - - size_t GetNextSampleIndexAndIncrease(); - void FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval); - void AddCompleteSamples(double dSpeed, unsigned long long& ullInterval); - void PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed); - double CalculateIncompleteSampleNormalizedSpeed() const; - - private: - // initialized in constructor (does not change throughout the whole lifetime) - const size_t m_stRequiredSamples; // how many samples of m_ullSampleTime do we want to keep? - const unsigned long long m_ullSampleTime; // interval covered by a single sample - const double m_dSamplesPerSecond; // how many samples fit in one second - - // vector of samples with pointer to the next element to be filled - std::vector m_vSamples; // speed per sample - size_t m_stNextSamplePos; // points to the element with the oldest sample - - unsigned long long m_ullLastTimestamp; // last time some sample was processed - - double m_dPartialSpeedNotInSamples; // specifies count of data processed in the m_ullTimeIntervalNotInSamples interval - unsigned long long m_ullTimeIntervalNotInSamples; // interval that was not enough to add m_ullDataNotInSamples to samples - unsigned long long m_ullZeroIntervalData; - }; -} - -#endif +#ifndef __TSPEEDTRACKER_H__ +#define __TSPEEDTRACKER_H__ + +#include "TString.h" + +namespace chcore +{ + class TSpeedTracker + { + public: + TSpeedTracker(unsigned long long ullTrackTime, unsigned long long ullSampleTime); + + void AddSample(unsigned long long ullValue, unsigned long long ullTimestamp); + void Clear(); + + // retrieves speed per second + double GetSpeed() const; + + TString ToString() const; + void FromString(const TString& strData); + + private: + TSpeedTracker(const TSpeedTracker&); + TSpeedTracker& operator=(const TSpeedTracker&); + + static double NormalizeValueByTime(unsigned long long ullValue, unsigned long long ullTime, unsigned long long ullNormalizeTime = 1000); + + size_t GetNextSampleIndexAndIncrease(); + void FinalizeIncompleteSample(double dSpeed, unsigned long long& ullInterval); + void AddCompleteSamples(double dSpeed, unsigned long long& ullInterval); + void PrepareIncompleteSample(unsigned long long ullInterval, double dSpeed); + double CalculateIncompleteSampleNormalizedSpeed() const; + + private: + // initialized in constructor (does not change throughout the whole lifetime) + const size_t m_stRequiredSamples; // how many samples of m_ullSampleTime do we want to keep? + const unsigned long long m_ullSampleTime; // interval covered by a single sample + const double m_dSamplesPerSecond; // how many samples fit in one second + + // vector of samples with pointer to the next element to be filled + std::vector m_vSamples; // speed per sample + size_t m_stNextSamplePos; // points to the element with the oldest sample + + unsigned long long m_ullLastTimestamp; // last time some sample was processed + + double m_dPartialSpeedNotInSamples; // specifies count of data processed in the m_ullTimeIntervalNotInSamples interval + unsigned long long m_ullTimeIntervalNotInSamples; // interval that was not enough to add m_ullDataNotInSamples to samples + unsigned long long m_ullZeroIntervalData; + }; +} + +#endif Index: src/libchcore/TString.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TString.cpp (.../TString.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TString.cpp (.../TString.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,717 +1,717 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TString.cpp -/// @date 2011/06/05 -/// @brief Contains implementation of TString class. -// ============================================================================ -#include "stdafx.h" -#include "TString.h" -#include -#pragma warning(push) -#pragma warning(disable: 4996) // boost::split uses unsafe std::copy - #include -#pragma warning(pop) -#include "TStringArray.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TStringException.h" - -/// Rounding up value to the nearest chunk multiplicity -#define ROUNDUP(val,chunk) ((val + chunk - 1) & ~(chunk-1)) - -///< Increment value for internal TString buffer -#define CHUNK_INCSIZE 64 - -namespace chcore -{ - /** Standard constructor - allocates the underlying data object - */ - TString::TString() : - m_pszData(nullptr), - m_stBufferSize(0) - { - } - - /** Constructor allocates the underlying data object and initializes it with - * a given unicode TString. - * \param[in] pszStr - source unicode TString - */ - TString::TString(const wchar_t* pszStr) : - m_pszData(nullptr), - m_stBufferSize(0) - { - SetString(pszStr); - } - - TString::TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize) : - m_pszData(nullptr), - m_stBufferSize(0) - { - // we support either both arguments != nullptr or both == nullptr - if (pszEnd != nullptr && pszStart == nullptr || pszEnd == nullptr && pszStart != nullptr) - throw TStringException(eErr_InvalidArgument, _T("End of string specified while start is nullptr"), LOCATION); - - // sanity check - if (pszEnd < pszStart) - throw TStringException(eErr_InvalidArgument, _T("Paradox: string begins after its end"), LOCATION); - - size_t stCount = pszEnd - pszStart; - if (stCount > stMaxStringSize) - throw TStringException(eErr_InvalidArgument, _T("Exceeded maximum expected string size"), LOCATION); - - SetString(pszStart, stCount); - } - - TString::TString(const wchar_t* pszStart, size_t stCount) : - m_pszData(nullptr), - m_stBufferSize(0) - { - if (!pszStart) - throw TStringException(eErr_InvalidArgument, _T("String not specified"), LOCATION); - - if (stCount == 0) - return; - - SetString(pszStart, stCount); - } - - /** Constructor increases the reference count in the parameter's data object - * and copies only the data object address. - * \param[in] rSrc - source TString object - */ - TString::TString(const TString& rSrc) : - m_pszData(nullptr), - m_stBufferSize(0) - { - SetString(rSrc.m_pszData); - } - - /** Destructor releases the underlying data object. - */ - TString::~TString() - { - delete[] m_pszData; - m_pszData = nullptr; - m_stBufferSize = 0; - } - - /** Operator releases the current data object, stores a pointer to - * the data object from the given TString object and increases a reference - * count. - * \param[in] src - source TString object - * \return A reference to the current TString. - */ - TString& TString::operator=(const TString& rSrc) - { - if (this != &rSrc) - SetString(rSrc.m_pszData); - - return *this; - } - - /** Operator makes an own copy of underlying data object (if needed) and copy - * there the given unicode TString. - * \param[in] pszSrc - source unicode TString - * \return A reference to the current TString object. - */ - const TString& TString::operator=(const wchar_t* pszSrc) - { - if (pszSrc != m_pszData) - SetString(pszSrc); - - return *this; - } - - /** Operator concatenates a given TString object with the current content of - * this TString and returns a new TString object. - * \param[in] src - TString object that will be appended - * \return A new TString object with concatenated strings. - */ - TString TString::operator+(const TString& src) const - { - TString str(*this); - str.Append(src); - - return str; - } - - /** Operator concatenates a given unicode TString with the current content of - * this TString and returns a new TString object. - * \param[in] pszSrc - unicode TString that will be appended - * \return A new TString object with concatenated strings. - */ - TString TString::operator+(const wchar_t* pszSrc) const - { - TString str(*this); - str.Append(pszSrc); - - return str; - } - - /** Operator appends a given TString object to own internal buffer. - * \param[in] src - TString object that will be appended - * \return A reference to this. - */ - const TString& TString::operator+=(const TString& src) - { - Append(src); - return *this; - } - - /** Operator appends a given unicode TString to own internal buffer. - * \param[in] pszSrc - unicode TString that will be appended - * \return A reference to this. - */ - const TString& TString::operator+=(const wchar_t* pszSrc) - { - Append(pszSrc); - return *this; - } - - /** Function counts the GetLength of a TString in characters (doesn't matter if the TString - * is unicode or ansi). - * \note All GetLength checks should be done through this function, because of possible future - * update that will store the TString GetLength in the internal member. - * \return The TString GetLength in characters, not including the terminating '\\0' - */ - size_t TString::GetLength() const - { - return m_pszData ? _tcslen(m_pszData) : 0; - } - - /** Function makes own data object writable and clears it. Does not delete the - * internal buffer - only sets the content to '\\0'. - */ - void TString::Clear() - { - if (m_pszData) - m_pszData[0] = L'\0'; - } - - /** Function checks if the TString is empty. - * \return True if this TString is empty, false otherwise. - */ - bool TString::IsEmpty() const - { - return !m_pszData || m_pszData[0] == L'\0'; - } - - /** Function merges the given unicode TString with the current content of an internal buffer. - * \param[in] pszSrc - unicode TString to append - */ - void TString::Append(const wchar_t* pszSrc) - { - if (!pszSrc) - return; - - size_t stAddLen = wcslen(pszSrc); - size_t stThisLen = GetLength(); - - Reserve(stThisLen + stAddLen + 1); - - wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, pszSrc, stAddLen + 1); - } - - /** Function merges the given TString object with the current content of an internal buffer. - * \param[in] src - TString object to append - */ - void TString::Append(const TString& rSrc) - { - if (rSrc.IsEmpty()) - return; - - size_t stAddLen = rSrc.GetLength(); - size_t stThisLen = GetLength(); - - Reserve(stThisLen + stAddLen + 1); - - wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, rSrc.m_pszData, stAddLen + 1); - } - - /** Returns a new TString object with the Left part of this TString object. - * \param[in] tLen - count of characters to copy to the new TString object - * \return The TString with the Left part of the current TString. - */ - TString TString::Left(size_t tLen) const - { - size_t stThisLen = GetLength(); - - if (stThisLen == 0 || tLen == 0) - return TString(); - - if (tLen >= stThisLen) - return *this; - else - return TString(m_pszData, tLen); - } - - /** Returns a new TString object with the Right part of this TString object. - * \param[in] tLen - count of characters to copy to the new TString object - * \return The TString with the Right part of the current TString. - */ - TString TString::Right(size_t tLen) const - { - size_t stThisLen = GetLength(); - - if (stThisLen == 0 || tLen == 0) - return TString(); - - if (tLen >= stThisLen) - return *this; - else - return TString(m_pszData + stThisLen - tLen, tLen); - } - - /** Returns a new TString object with the middle part of this TString object. - * \param[in] tStart - position of the first character to copy - * \param[in] tLen - count of chars to copy - * \return The TString with the middle part of the current TString. - */ - TString TString::Mid(size_t tStart, size_t tLen) const - { - size_t stThisLen = GetLength(); - - if (stThisLen == 0 || tLen == 0) - return TString(); - - if (tStart >= stThisLen) - return TString(); - - size_t stRealLength = std::min(tLen, stThisLen - tStart); - - TString strNew(m_pszData + tStart, stRealLength); - return strNew; - } - - TString TString::MidRange(size_t tStart, size_t stAfterEndPos) const - { - if (stAfterEndPos < tStart) - return TString(); - return Mid(tStart, stAfterEndPos - tStart); - } - - /** Makes this TString it's Left part. Much faster than using standard - * Left() function. - * \param[in] tLen - count of characters at the beginning of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Left() - */ - void TString::LeftSelf(size_t tLen) - { - size_t stThisLen = GetLength(); - - // nothing to do if nothing inside - if (stThisLen == 0) - return; - - if (tLen < stThisLen) // otherwise there is nothing to do - m_pszData[tLen] = _T('\0'); - } - - /** Makes this TString it's Right part. Much faster than using standard - * Right() function. - * \param[in] tLen - count of characters at the end of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Right() - */ - void TString::RightSelf(size_t tLen) - { - size_t stThisLen = GetLength(); - - // nothing to do if nothing inside - if (stThisLen == 0) - return; - - if (tLen < stThisLen) // otherwise there is nothing to do - wmemmove(m_pszData, m_pszData + stThisLen - tLen, tLen + 1); - } - - /** Makes this TString it's middle part. Much faster than using standard - * Mid() function. - * \param[in] tStart - starting position of a text to be Left in a TString - * \param[in] tLen - count of characters at the middle of the TString to be Left in a TString. - * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds - * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). - * \see Mid() - */ - void TString::MidSelf(size_t tStart, size_t tLen) - { - size_t stThisLen = GetLength(); - - if (stThisLen == 0) - return; - - if (tStart >= stThisLen) - Clear(); - else - { - size_t stRealNewLength = std::min(tLen, stThisLen - tStart); - - wmemmove(m_pszData, m_pszData + tStart, stRealNewLength); - m_pszData[stRealNewLength] = _T('\0'); - } - } - - void TString::TrimRightSelf(const wchar_t* pszElements) - { - if (!pszElements || pszElements[0] == L'\0') - return; - - size_t stThisLen = GetLength(); - if (stThisLen == 0) - return; - - size_t stLen = stThisLen; - - const wchar_t* pszElementsEnd = pszElements + wcslen(pszElements); - while (stLen-- > 0) - { - if (std::find(pszElements, pszElementsEnd, m_pszData[stLen]) != pszElementsEnd) - m_pszData[stLen] = _T('\0'); - else - break; - } - } - - bool TString::Delete(size_t stIndex, size_t stCount) - { - size_t stThisLen = GetLength(); - - if (stIndex >= stThisLen || stCount == 0) - return false; - - bool bResult = true; - if (stIndex + stCount > stThisLen) // in case there is not enough data to delete, then we want to delete what we can, but return false - bResult = false; - - size_t stCountToDelete = std::min(stThisLen - stIndex, stCount); - - // should also copy the terminating null character - errno_t err = wmemmove_s(m_pszData + stIndex, stThisLen - stIndex + 1, m_pszData + stIndex + stCountToDelete, stThisLen - stIndex - stCountToDelete + 1); - if (err != 0) - throw TCoreException(eErr_InternalProblem, L"Failed to move memory", LOCATION); - - return bResult; - } - - void TString::Split(const wchar_t* pszSeparators, TStringArray& rStrings) const - { - rStrings.Clear(); - - size_t stThisLen = GetLength(); - if (stThisLen == 0 || !pszSeparators) - return; - - // ugly version - many reallocations due to the usage of stl wstrings - std::vector vStrings; - boost::split(vStrings, m_pszData, boost::is_any_of(pszSeparators)); - - for(const std::wstring& strPart : vStrings) - { - rStrings.Add(strPart.c_str()); - } - } - - /** Compares a TString with the given unicode TString. Comparison is case sensitive. - * \param[in] psz - unicode TString to which the TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ - int TString::Compare(const wchar_t* psz) const - { - return wcscmp(m_pszData ? m_pszData : L"", psz ? psz : L""); - } - - /** Compares a TString with the given TString object. Comparison is case sensitive. - * \param[in] str - TString object to which internal TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ - int TString::Compare(const TString& str) const - { - return Compare(str.m_pszData); - } - - /** Compares a TString with the given unicode TString. Comparison is case insensitive. - * \param[in] psz - unicode TString to which internal TString object will be compared - * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. - */ - int TString::CompareNoCase(const wchar_t* psz) const - { - return _wcsicmp(m_pszData ? m_pszData : L"", psz ? psz : L""); - } - - /** Compares a TString with the given TString object. Comparison is case insensitive. - * \param[in] str - TString object to which internal TString object will be compared - * \return <0 if this TString object is "less" than str, 0 if they are equal and >0 otherwise. - */ - int TString::CompareNoCase(const TString& str) const - { - return CompareNoCase(str.m_pszData); - } - - bool TString::StartsWith(const wchar_t* pszText) const - { - if (!m_pszData || !pszText) - return false; - - return boost::starts_with(m_pszData, pszText); - } - - bool TString::StartsWithNoCase(const wchar_t* pszText) const - { - if (!m_pszData || !pszText) - return false; - - return boost::istarts_with(m_pszData, pszText); - } - - bool TString::EndsWith(const wchar_t* pszText) const - { - if (!m_pszData || !pszText) - return false; - - return boost::ends_with(m_pszData, pszText); - } - - bool TString::EndsWithNoCase(const wchar_t* pszText) const - { - if (!m_pszData || !pszText) - return false; - - return boost::iends_with(m_pszData, pszText); - } - - size_t TString::FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos) const - { - if (!m_pszData || !pszChars) - return npos; - - size_t stCurrentLength = GetLength(); - for (size_t stIndex = stStartFromPos; stIndex < stCurrentLength; ++stIndex) - { - if (wcschr(pszChars, m_pszData[stIndex])) - return stIndex; - } - - return npos; - } - - size_t TString::FindLastOf(const wchar_t* pszChars) const - { - if (!m_pszData || !pszChars) - return npos; - - for (size_t stIndex = GetLength(); stIndex != 0; --stIndex) - { - if (wcschr(pszChars, m_pszData[stIndex - 1])) - return stIndex - 1; - } - - return npos; - } - - size_t TString::Find(const wchar_t* pszFindText, size_t stStartPos) - { - size_t stThisLen = GetLength(); - if (!pszFindText || stThisLen == 0) - return npos; - - size_t stFindTextLen = _tcslen(pszFindText); - if (stFindTextLen > stThisLen) - return TString::npos; - - if (stStartPos > stThisLen - stFindTextLen) - return TString::npos; - - boost::iterator_range rangeText = boost::make_iterator_range(m_pszData + stStartPos, m_pszData + stThisLen); - boost::iterator_range rangeFind = boost::find_first(rangeText, pszFindText); - - if (rangeFind.begin() != rangeText.end()) - return rangeFind.begin() - rangeText.begin() + stStartPos; - else - return TString::npos; - } - - void TString::Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat) - { - size_t stThisLen = GetLength(); - if (stThisLen == 0) - return; - - if (!pszWhat || !pszWithWhat) - return; - - // find all occurrences of pszWhat in this string, so we can calculate new required size of the string - size_t stWhatLen = _tcslen(pszWhat); - size_t stWithWhatLen = _tcslen(pszWithWhat); - - size_t stNewLen = stThisLen; - - // resize internal string if needed - if (stWithWhatLen > stWhatLen) - { - size_t stStartPos = 0; - size_t stFindPos = 0; - size_t stSizeDiff = 0; - while ((stFindPos = Find(pszWhat, stStartPos)) != npos) - { - stSizeDiff += stWithWhatLen - stWhatLen; - stStartPos = stFindPos + stWhatLen; // offset by what_len because we don't replace anything at this point - } - - if (stSizeDiff > 0) - stNewLen = stThisLen + stSizeDiff + 1; - } - - Reserve(stNewLen); - - // replace - size_t stStartPos = 0; - size_t stFindPos = 0; - while ((stFindPos = Find(pszWhat, stStartPos)) != npos) - { - // Sample string "ABCdddb" (len:6), searching for "dd" (len 2) to replace with "x" (len 1) - // found string pos is: [stFindPos, stFindPos + stWhatLen) -- sample ref: [3, 3 + 2) - // we need to - // - move string from position [stFindPos + stWhatLen, stCurrentLength) to position [stFindPos + stWithWhatLen, stCurrentLength + stWithWhatLen - stWhatLen] -- sample ref: [3+2, 6) to [3+1, 5) - size_t stCountToCopy = stThisLen - stFindPos - stWhatLen + 1; - - memmove_s((void*)(m_pszData + stFindPos + stWithWhatLen), stCountToCopy * sizeof(wchar_t), (void*)(m_pszData + stFindPos + stWhatLen), stCountToCopy * sizeof(wchar_t)); - - // - copy pszWithWhat to position (stFindPos + stWhatLen) - memcpy_s((void*)(m_pszData + stFindPos), stWithWhatLen * sizeof(wchar_t), pszWithWhat, stWithWhatLen * sizeof(wchar_t)); - - stStartPos = stFindPos + stWithWhatLen; // offset by stWithWhatLen because we replaced text - } - } - - /** Returns a character at a given position. Function is very slow (needs to recalc the size of the TString - * and make a few comparisons), but quite safe - if the index is out of range then -1 is returned. - * Make sure to interpret the returned character according to unicode flag. If the TString is unicode, then the - * character returned is also unicode (and vice versa). - * \param[in] tPos - index of the character to return. - * \return Character code of character on a specified position, or -1 if out of range. - */ - bool TString::GetAt(size_t tPos, wchar_t& wch) const - { - if (tPos < GetLength()) - { - wch = m_pszData[tPos]; - return true; - } - else - { - wch = L'\0'; - return false; - } - } - - wchar_t TString::GetAt(size_t tPos) const - { - if (tPos < GetLength()) - return m_pszData[tPos]; - else - return L'\0'; - } - - /** Returns a pointer to the unicode internal buffer. If the buffer is in ansi format - * then nullptr value is returned. Internal buffer is resized to the specified value - * if currently smaller than requested (if -1 is specified as tMinSize then the buffer - * is not resized, and the return value could be nullptr). - * \param[in] tMinSize - requested minimal size of the internal buffer (-1 if the size of the TString should not be changed) - * \return Pointer to the internal unicode buffer. - */ - wchar_t* TString::GetBuffer(size_t tMinSize) - { - Reserve(tMinSize + 1); - - return m_pszData; - } - - /** Releases buffer got by user by calling get_bufferx functions. The current - * job of this function is to make sure the TString will terminate with null - * character at the end of the buffer. - */ - void TString::ReleaseBuffer() - { - m_pszData[m_stBufferSize - 1] = L'\0'; - } - - void TString::ReleaseBufferSetLength(size_t tSize) - { - Reserve(tSize + 1); - - m_pszData[tSize] = L'\0'; - } - - void TString::SetString(const wchar_t* pszStart, size_t stCount) - { - if (!pszStart || stCount == 0) - Clear(); - else - { - Reserve(stCount + 1); - - wcsncpy_s(m_pszData, m_stBufferSize, pszStart, stCount); - m_pszData[stCount] = _T('\0'); - } - } - - void TString::SetString(const wchar_t* pszString) - { - if (!pszString) - Clear(); - else - { - size_t stLen = _tcslen(pszString); - SetString(pszString, stLen); - } - } - - void TString::Reserve(size_t stLen) - { - if (!m_pszData || m_stBufferSize < stLen) - { - size_t stNewLen = stLen;//ROUNDUP(stLen, CHUNK_INCSIZE); - - wchar_t* pszNewBuffer = new wchar_t[stNewLen]; - if (m_pszData && m_pszData[0] != L'\0') - _tcsncpy_s(pszNewBuffer, stNewLen, m_pszData, GetLength() + 1); - else - pszNewBuffer[0] = _T('\0'); - - delete[] m_pszData; - m_pszData = pszNewBuffer; - m_stBufferSize = stNewLen; - } - } - - const wchar_t* TString::c_str() const - { - return m_pszData ? m_pszData : L""; - } -} - -chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str) -{ - chcore::TString strNew(pszString); - strNew += str; - return strNew; -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TString.cpp +/// @date 2011/06/05 +/// @brief Contains implementation of TString class. +// ============================================================================ +#include "stdafx.h" +#include "TString.h" +#include +#pragma warning(push) +#pragma warning(disable: 4996) // boost::split uses unsafe std::copy + #include +#pragma warning(pop) +#include "TStringArray.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TStringException.h" + +/// Rounding up value to the nearest chunk multiplicity +#define ROUNDUP(val,chunk) ((val + chunk - 1) & ~(chunk-1)) + +///< Increment value for internal TString buffer +#define CHUNK_INCSIZE 64 + +namespace chcore +{ + /** Standard constructor - allocates the underlying data object + */ + TString::TString() : + m_pszData(nullptr), + m_stBufferSize(0) + { + } + + /** Constructor allocates the underlying data object and initializes it with + * a given unicode TString. + * \param[in] pszStr - source unicode TString + */ + TString::TString(const wchar_t* pszStr) : + m_pszData(nullptr), + m_stBufferSize(0) + { + SetString(pszStr); + } + + TString::TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize) : + m_pszData(nullptr), + m_stBufferSize(0) + { + // we support either both arguments != nullptr or both == nullptr + if (pszEnd != nullptr && pszStart == nullptr || pszEnd == nullptr && pszStart != nullptr) + throw TStringException(eErr_InvalidArgument, _T("End of string specified while start is nullptr"), LOCATION); + + // sanity check + if (pszEnd < pszStart) + throw TStringException(eErr_InvalidArgument, _T("Paradox: string begins after its end"), LOCATION); + + size_t stCount = pszEnd - pszStart; + if (stCount > stMaxStringSize) + throw TStringException(eErr_InvalidArgument, _T("Exceeded maximum expected string size"), LOCATION); + + SetString(pszStart, stCount); + } + + TString::TString(const wchar_t* pszStart, size_t stCount) : + m_pszData(nullptr), + m_stBufferSize(0) + { + if (!pszStart) + throw TStringException(eErr_InvalidArgument, _T("String not specified"), LOCATION); + + if (stCount == 0) + return; + + SetString(pszStart, stCount); + } + + /** Constructor increases the reference count in the parameter's data object + * and copies only the data object address. + * \param[in] rSrc - source TString object + */ + TString::TString(const TString& rSrc) : + m_pszData(nullptr), + m_stBufferSize(0) + { + SetString(rSrc.m_pszData); + } + + /** Destructor releases the underlying data object. + */ + TString::~TString() + { + delete[] m_pszData; + m_pszData = nullptr; + m_stBufferSize = 0; + } + + /** Operator releases the current data object, stores a pointer to + * the data object from the given TString object and increases a reference + * count. + * \param[in] src - source TString object + * \return A reference to the current TString. + */ + TString& TString::operator=(const TString& rSrc) + { + if (this != &rSrc) + SetString(rSrc.m_pszData); + + return *this; + } + + /** Operator makes an own copy of underlying data object (if needed) and copy + * there the given unicode TString. + * \param[in] pszSrc - source unicode TString + * \return A reference to the current TString object. + */ + const TString& TString::operator=(const wchar_t* pszSrc) + { + if (pszSrc != m_pszData) + SetString(pszSrc); + + return *this; + } + + /** Operator concatenates a given TString object with the current content of + * this TString and returns a new TString object. + * \param[in] src - TString object that will be appended + * \return A new TString object with concatenated strings. + */ + TString TString::operator+(const TString& src) const + { + TString str(*this); + str.Append(src); + + return str; + } + + /** Operator concatenates a given unicode TString with the current content of + * this TString and returns a new TString object. + * \param[in] pszSrc - unicode TString that will be appended + * \return A new TString object with concatenated strings. + */ + TString TString::operator+(const wchar_t* pszSrc) const + { + TString str(*this); + str.Append(pszSrc); + + return str; + } + + /** Operator appends a given TString object to own internal buffer. + * \param[in] src - TString object that will be appended + * \return A reference to this. + */ + const TString& TString::operator+=(const TString& src) + { + Append(src); + return *this; + } + + /** Operator appends a given unicode TString to own internal buffer. + * \param[in] pszSrc - unicode TString that will be appended + * \return A reference to this. + */ + const TString& TString::operator+=(const wchar_t* pszSrc) + { + Append(pszSrc); + return *this; + } + + /** Function counts the GetLength of a TString in characters (doesn't matter if the TString + * is unicode or ansi). + * \note All GetLength checks should be done through this function, because of possible future + * update that will store the TString GetLength in the internal member. + * \return The TString GetLength in characters, not including the terminating '\\0' + */ + size_t TString::GetLength() const + { + return m_pszData ? _tcslen(m_pszData) : 0; + } + + /** Function makes own data object writable and clears it. Does not delete the + * internal buffer - only sets the content to '\\0'. + */ + void TString::Clear() + { + if (m_pszData) + m_pszData[0] = L'\0'; + } + + /** Function checks if the TString is empty. + * \return True if this TString is empty, false otherwise. + */ + bool TString::IsEmpty() const + { + return !m_pszData || m_pszData[0] == L'\0'; + } + + /** Function merges the given unicode TString with the current content of an internal buffer. + * \param[in] pszSrc - unicode TString to append + */ + void TString::Append(const wchar_t* pszSrc) + { + if (!pszSrc) + return; + + size_t stAddLen = wcslen(pszSrc); + size_t stThisLen = GetLength(); + + Reserve(stThisLen + stAddLen + 1); + + wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, pszSrc, stAddLen + 1); + } + + /** Function merges the given TString object with the current content of an internal buffer. + * \param[in] src - TString object to append + */ + void TString::Append(const TString& rSrc) + { + if (rSrc.IsEmpty()) + return; + + size_t stAddLen = rSrc.GetLength(); + size_t stThisLen = GetLength(); + + Reserve(stThisLen + stAddLen + 1); + + wcsncpy_s(m_pszData + stThisLen, m_stBufferSize - stThisLen, rSrc.m_pszData, stAddLen + 1); + } + + /** Returns a new TString object with the Left part of this TString object. + * \param[in] tLen - count of characters to copy to the new TString object + * \return The TString with the Left part of the current TString. + */ + TString TString::Left(size_t tLen) const + { + size_t stThisLen = GetLength(); + + if (stThisLen == 0 || tLen == 0) + return TString(); + + if (tLen >= stThisLen) + return *this; + else + return TString(m_pszData, tLen); + } + + /** Returns a new TString object with the Right part of this TString object. + * \param[in] tLen - count of characters to copy to the new TString object + * \return The TString with the Right part of the current TString. + */ + TString TString::Right(size_t tLen) const + { + size_t stThisLen = GetLength(); + + if (stThisLen == 0 || tLen == 0) + return TString(); + + if (tLen >= stThisLen) + return *this; + else + return TString(m_pszData + stThisLen - tLen, tLen); + } + + /** Returns a new TString object with the middle part of this TString object. + * \param[in] tStart - position of the first character to copy + * \param[in] tLen - count of chars to copy + * \return The TString with the middle part of the current TString. + */ + TString TString::Mid(size_t tStart, size_t tLen) const + { + size_t stThisLen = GetLength(); + + if (stThisLen == 0 || tLen == 0) + return TString(); + + if (tStart >= stThisLen) + return TString(); + + size_t stRealLength = std::min(tLen, stThisLen - tStart); + + TString strNew(m_pszData + tStart, stRealLength); + return strNew; + } + + TString TString::MidRange(size_t tStart, size_t stAfterEndPos) const + { + if (stAfterEndPos < tStart) + return TString(); + return Mid(tStart, stAfterEndPos - tStart); + } + + /** Makes this TString it's Left part. Much faster than using standard + * Left() function. + * \param[in] tLen - count of characters at the beginning of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Left() + */ + void TString::LeftSelf(size_t tLen) + { + size_t stThisLen = GetLength(); + + // nothing to do if nothing inside + if (stThisLen == 0) + return; + + if (tLen < stThisLen) // otherwise there is nothing to do + m_pszData[tLen] = _T('\0'); + } + + /** Makes this TString it's Right part. Much faster than using standard + * Right() function. + * \param[in] tLen - count of characters at the end of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Right() + */ + void TString::RightSelf(size_t tLen) + { + size_t stThisLen = GetLength(); + + // nothing to do if nothing inside + if (stThisLen == 0) + return; + + if (tLen < stThisLen) // otherwise there is nothing to do + wmemmove(m_pszData, m_pszData + stThisLen - tLen, tLen + 1); + } + + /** Makes this TString it's middle part. Much faster than using standard + * Mid() function. + * \param[in] tStart - starting position of a text to be Left in a TString + * \param[in] tLen - count of characters at the middle of the TString to be Left in a TString. + * \param[in] bReallocBuffer - if the internal TString buffer is to be reallocated if exceeds + * the allowable range size (CHUNK_INCSIZE, CHUNK_DECSIZE). + * \see Mid() + */ + void TString::MidSelf(size_t tStart, size_t tLen) + { + size_t stThisLen = GetLength(); + + if (stThisLen == 0) + return; + + if (tStart >= stThisLen) + Clear(); + else + { + size_t stRealNewLength = std::min(tLen, stThisLen - tStart); + + wmemmove(m_pszData, m_pszData + tStart, stRealNewLength); + m_pszData[stRealNewLength] = _T('\0'); + } + } + + void TString::TrimRightSelf(const wchar_t* pszElements) + { + if (!pszElements || pszElements[0] == L'\0') + return; + + size_t stThisLen = GetLength(); + if (stThisLen == 0) + return; + + size_t stLen = stThisLen; + + const wchar_t* pszElementsEnd = pszElements + wcslen(pszElements); + while (stLen-- > 0) + { + if (std::find(pszElements, pszElementsEnd, m_pszData[stLen]) != pszElementsEnd) + m_pszData[stLen] = _T('\0'); + else + break; + } + } + + bool TString::Delete(size_t stIndex, size_t stCount) + { + size_t stThisLen = GetLength(); + + if (stIndex >= stThisLen || stCount == 0) + return false; + + bool bResult = true; + if (stIndex + stCount > stThisLen) // in case there is not enough data to delete, then we want to delete what we can, but return false + bResult = false; + + size_t stCountToDelete = std::min(stThisLen - stIndex, stCount); + + // should also copy the terminating null character + errno_t err = wmemmove_s(m_pszData + stIndex, stThisLen - stIndex + 1, m_pszData + stIndex + stCountToDelete, stThisLen - stIndex - stCountToDelete + 1); + if (err != 0) + throw TCoreException(eErr_InternalProblem, L"Failed to move memory", LOCATION); + + return bResult; + } + + void TString::Split(const wchar_t* pszSeparators, TStringArray& rStrings) const + { + rStrings.Clear(); + + size_t stThisLen = GetLength(); + if (stThisLen == 0 || !pszSeparators) + return; + + // ugly version - many reallocations due to the usage of stl wstrings + std::vector vStrings; + boost::split(vStrings, m_pszData, boost::is_any_of(pszSeparators)); + + for(const std::wstring& strPart : vStrings) + { + rStrings.Add(strPart.c_str()); + } + } + + /** Compares a TString with the given unicode TString. Comparison is case sensitive. + * \param[in] psz - unicode TString to which the TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int TString::Compare(const wchar_t* psz) const + { + return wcscmp(m_pszData ? m_pszData : L"", psz ? psz : L""); + } + + /** Compares a TString with the given TString object. Comparison is case sensitive. + * \param[in] str - TString object to which internal TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int TString::Compare(const TString& str) const + { + return Compare(str.m_pszData); + } + + /** Compares a TString with the given unicode TString. Comparison is case insensitive. + * \param[in] psz - unicode TString to which internal TString object will be compared + * \return <0 if this TString object is "less" than psz, 0 if they are equal and >0 otherwise. + */ + int TString::CompareNoCase(const wchar_t* psz) const + { + return _wcsicmp(m_pszData ? m_pszData : L"", psz ? psz : L""); + } + + /** Compares a TString with the given TString object. Comparison is case insensitive. + * \param[in] str - TString object to which internal TString object will be compared + * \return <0 if this TString object is "less" than str, 0 if they are equal and >0 otherwise. + */ + int TString::CompareNoCase(const TString& str) const + { + return CompareNoCase(str.m_pszData); + } + + bool TString::StartsWith(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; + + return boost::starts_with(m_pszData, pszText); + } + + bool TString::StartsWithNoCase(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; + + return boost::istarts_with(m_pszData, pszText); + } + + bool TString::EndsWith(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; + + return boost::ends_with(m_pszData, pszText); + } + + bool TString::EndsWithNoCase(const wchar_t* pszText) const + { + if (!m_pszData || !pszText) + return false; + + return boost::iends_with(m_pszData, pszText); + } + + size_t TString::FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos) const + { + if (!m_pszData || !pszChars) + return npos; + + size_t stCurrentLength = GetLength(); + for (size_t stIndex = stStartFromPos; stIndex < stCurrentLength; ++stIndex) + { + if (wcschr(pszChars, m_pszData[stIndex])) + return stIndex; + } + + return npos; + } + + size_t TString::FindLastOf(const wchar_t* pszChars) const + { + if (!m_pszData || !pszChars) + return npos; + + for (size_t stIndex = GetLength(); stIndex != 0; --stIndex) + { + if (wcschr(pszChars, m_pszData[stIndex - 1])) + return stIndex - 1; + } + + return npos; + } + + size_t TString::Find(const wchar_t* pszFindText, size_t stStartPos) + { + size_t stThisLen = GetLength(); + if (!pszFindText || stThisLen == 0) + return npos; + + size_t stFindTextLen = _tcslen(pszFindText); + if (stFindTextLen > stThisLen) + return TString::npos; + + if (stStartPos > stThisLen - stFindTextLen) + return TString::npos; + + boost::iterator_range rangeText = boost::make_iterator_range(m_pszData + stStartPos, m_pszData + stThisLen); + boost::iterator_range rangeFind = boost::find_first(rangeText, pszFindText); + + if (rangeFind.begin() != rangeText.end()) + return rangeFind.begin() - rangeText.begin() + stStartPos; + else + return TString::npos; + } + + void TString::Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat) + { + size_t stThisLen = GetLength(); + if (stThisLen == 0) + return; + + if (!pszWhat || !pszWithWhat) + return; + + // find all occurrences of pszWhat in this string, so we can calculate new required size of the string + size_t stWhatLen = _tcslen(pszWhat); + size_t stWithWhatLen = _tcslen(pszWithWhat); + + size_t stNewLen = stThisLen; + + // resize internal string if needed + if (stWithWhatLen > stWhatLen) + { + size_t stStartPos = 0; + size_t stFindPos = 0; + size_t stSizeDiff = 0; + while ((stFindPos = Find(pszWhat, stStartPos)) != npos) + { + stSizeDiff += stWithWhatLen - stWhatLen; + stStartPos = stFindPos + stWhatLen; // offset by what_len because we don't replace anything at this point + } + + if (stSizeDiff > 0) + stNewLen = stThisLen + stSizeDiff + 1; + } + + Reserve(stNewLen); + + // replace + size_t stStartPos = 0; + size_t stFindPos = 0; + while ((stFindPos = Find(pszWhat, stStartPos)) != npos) + { + // Sample string "ABCdddb" (len:6), searching for "dd" (len 2) to replace with "x" (len 1) + // found string pos is: [stFindPos, stFindPos + stWhatLen) -- sample ref: [3, 3 + 2) + // we need to + // - move string from position [stFindPos + stWhatLen, stCurrentLength) to position [stFindPos + stWithWhatLen, stCurrentLength + stWithWhatLen - stWhatLen] -- sample ref: [3+2, 6) to [3+1, 5) + size_t stCountToCopy = stThisLen - stFindPos - stWhatLen + 1; + + memmove_s((void*)(m_pszData + stFindPos + stWithWhatLen), stCountToCopy * sizeof(wchar_t), (void*)(m_pszData + stFindPos + stWhatLen), stCountToCopy * sizeof(wchar_t)); + + // - copy pszWithWhat to position (stFindPos + stWhatLen) + memcpy_s((void*)(m_pszData + stFindPos), stWithWhatLen * sizeof(wchar_t), pszWithWhat, stWithWhatLen * sizeof(wchar_t)); + + stStartPos = stFindPos + stWithWhatLen; // offset by stWithWhatLen because we replaced text + } + } + + /** Returns a character at a given position. Function is very slow (needs to recalc the size of the TString + * and make a few comparisons), but quite safe - if the index is out of range then -1 is returned. + * Make sure to interpret the returned character according to unicode flag. If the TString is unicode, then the + * character returned is also unicode (and vice versa). + * \param[in] tPos - index of the character to return. + * \return Character code of character on a specified position, or -1 if out of range. + */ + bool TString::GetAt(size_t tPos, wchar_t& wch) const + { + if (tPos < GetLength()) + { + wch = m_pszData[tPos]; + return true; + } + else + { + wch = L'\0'; + return false; + } + } + + wchar_t TString::GetAt(size_t tPos) const + { + if (tPos < GetLength()) + return m_pszData[tPos]; + else + return L'\0'; + } + + /** Returns a pointer to the unicode internal buffer. If the buffer is in ansi format + * then nullptr value is returned. Internal buffer is resized to the specified value + * if currently smaller than requested (if -1 is specified as tMinSize then the buffer + * is not resized, and the return value could be nullptr). + * \param[in] tMinSize - requested minimal size of the internal buffer (-1 if the size of the TString should not be changed) + * \return Pointer to the internal unicode buffer. + */ + wchar_t* TString::GetBuffer(size_t tMinSize) + { + Reserve(tMinSize + 1); + + return m_pszData; + } + + /** Releases buffer got by user by calling get_bufferx functions. The current + * job of this function is to make sure the TString will terminate with null + * character at the end of the buffer. + */ + void TString::ReleaseBuffer() + { + m_pszData[m_stBufferSize - 1] = L'\0'; + } + + void TString::ReleaseBufferSetLength(size_t tSize) + { + Reserve(tSize + 1); + + m_pszData[tSize] = L'\0'; + } + + void TString::SetString(const wchar_t* pszStart, size_t stCount) + { + if (!pszStart || stCount == 0) + Clear(); + else + { + Reserve(stCount + 1); + + wcsncpy_s(m_pszData, m_stBufferSize, pszStart, stCount); + m_pszData[stCount] = _T('\0'); + } + } + + void TString::SetString(const wchar_t* pszString) + { + if (!pszString) + Clear(); + else + { + size_t stLen = _tcslen(pszString); + SetString(pszString, stLen); + } + } + + void TString::Reserve(size_t stLen) + { + if (!m_pszData || m_stBufferSize < stLen) + { + size_t stNewLen = stLen;//ROUNDUP(stLen, CHUNK_INCSIZE); + + wchar_t* pszNewBuffer = new wchar_t[stNewLen]; + if (m_pszData && m_pszData[0] != L'\0') + _tcsncpy_s(pszNewBuffer, stNewLen, m_pszData, GetLength() + 1); + else + pszNewBuffer[0] = _T('\0'); + + delete[] m_pszData; + m_pszData = pszNewBuffer; + m_stBufferSize = stNewLen; + } + } + + const wchar_t* TString::c_str() const + { + return m_pszData ? m_pszData : L""; + } +} + +chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str) +{ + chcore::TString strNew(pszString); + strNew += str; + return strNew; +} Index: src/libchcore/TString.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TString.h (.../TString.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TString.h (.../TString.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,172 +1,172 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TString.h -/// @date 2011/06/05 -/// @brief Contains declaration of TString class. -// ============================================================================ -#ifndef __TSTRING_H__ -#define __TSTRING_H__ - -#include "libchcore.h" -#include - -namespace chcore -{ - class TStringArray; - - /////////////////////////////////////////////////////////////// - // TString manipulation class - /** \brief String manipulation class - * - * Class allows user to manipulate TString objects (either standard ANSI char_t* - * based strings or UNICODE ones - wchar_t related) with simple functions and - * operators. - */ - class LIBCHCORE_API TString - { - public: - /** \name Construction/destruction */ - /*@{*/ - TString(); ///< Standard constructor - // cppcheck-suppress noExplicitConstructor - TString(const wchar_t* pszStr); ///< Constructor that takes const wchar_t* as an initial TString - TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize = DefaultMaxStringSize); - TString(const wchar_t* pszStart, size_t stCount); - TString(const TString& str); ///< Standard copy constructor - - ~TString(); ///< Standard destructor - /*@}*/ - - /** \name Operators */ - /**@{*/ - // assignment - TString& operator=(const TString& src); ///< Assign operator for TString objects - TString operator+(const TString& src) const; ///< Concatenate operator for TString objects - const TString& operator+=(const TString& src); ///< Merge operator for TString objects - - const TString& operator=(const wchar_t* pszSrc); ///< Assign operator from unicode strings - TString operator+(const wchar_t* pszSrc) const; ///< Concatenate operator for unicode strings - const TString& operator+=(const wchar_t* pszSrc); ///< Merge operator for unicode strings - - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator<(const wchar_t* psz) const { return Compare(psz) < 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator<=(const wchar_t* psz) const { return Compare(psz) <= 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator==(const wchar_t* psz) const { return Compare(psz) == 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator>=(const wchar_t* psz) const { return Compare(psz) >= 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator>(const wchar_t* psz) const { return Compare(psz) > 0; }; - /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) - bool operator!=(const wchar_t* psz) const { return Compare(psz) != 0; }; - - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator<(const TString& str) const { return Compare(str) < 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator<=(const TString& str) const { return Compare(str) <= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator==(const TString& str) const { return Compare(str) == 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator>=(const TString& str) const { return Compare(str) >= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator>(const TString& str) const { return Compare(str) >= 0; }; - /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) - bool operator!=(const TString& str) const { return Compare(str) != 0; }; - /**@}*/ - - /** \name Standard operations */ - /**@{*/ - // appends the given TString to this - void Append(const wchar_t* pszSrc); ///< Appends an unicode TString to the TString object - void Append(const TString& src); ///< Appends a TString object to another TString object - - TString Left(size_t tLen) const; ///< Returns TString with the Left part of a source TString - TString Right(size_t tLen) const; ///< Returns TString with the Right part of a source TString - TString Mid(size_t tStart, size_t tLen = (size_t)-1) const; ///< Returns TString with the middle part of a source TString - TString MidRange(size_t tStart, size_t stAfterEndPos) const; ///< Returns TString with the middle part of a source TString - - void LeftSelf(size_t tLen); ///< Makes this TString it's Left part - void RightSelf(size_t tLen); ///< Makes this TString it's Right part - void MidSelf(size_t tStart, size_t tLen = (size_t)-1); ///< Makes this TString it's middle part - - void TrimRightSelf(const wchar_t* pszElements); - - bool Delete(size_t stIndex, size_t stCount); - - void Split(const wchar_t* pszSeparators, TStringArray& rStrings) const; - - // compare operations - int Compare(const wchar_t* psz) const; ///< Comparison of this TString object with a given unicode TString - int Compare(const TString& str) const; ///< Comparison of this TString object with another TString object - - int CompareNoCase(const wchar_t* psz) const; ///< Comparison (case insensitive) of this TString object with a given unicode TString - int CompareNoCase(const TString& str) const; ///< Comparison (case insensitive) of this TString object with another TString object - - bool StartsWith(const wchar_t* pszText) const; - bool StartsWithNoCase(const wchar_t* pszText) const; - - bool EndsWith(const wchar_t* pszText) const; - bool EndsWithNoCase(const wchar_t* pszText) const; - - size_t FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos = 0) const; - size_t FindLastOf(const wchar_t* pszChars) const; - - size_t Find(const wchar_t* pszText, size_t stStartPos = 0); - void Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat); - - bool GetAt(size_t tPos, wchar_t& wch) const; ///< Gets a character at a specified position - wchar_t GetAt(size_t tPos) const; - - const wchar_t* c_str() const; - - wchar_t* GetBuffer(size_t tMinSize); ///< Gives user access to the unicode internal buffer - void ReleaseBuffer(); ///< Releases the buffer get from get_bufferx functions - void ReleaseBufferSetLength(size_t tSize); - - size_t GetLength() const; ///< Returns the GetLength of this TString in chars - - void Clear(); ///< Clear the contents of the TString object - - bool IsEmpty() const; ///< Returns true if the TString is empty - /**@}*/ - - protected: - void SetString(const wchar_t* pszStart, size_t stCount); - void SetString(const wchar_t* pszString); - void Reserve(size_t stLen); - - protected: - wchar_t* m_pszData; // contains the real string inside - size_t m_stBufferSize; // allocated string buffer size - - public: - static const size_t npos = (size_t)-1; - static const size_t DefaultMaxStringSize = 65536; - }; - - inline std::wostream& operator<<(std::wostream& os, const TString& rString) - { - return os << std::wstring(rString.c_str()); - } -} - -LIBCHCORE_API chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str); - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TString.h +/// @date 2011/06/05 +/// @brief Contains declaration of TString class. +// ============================================================================ +#ifndef __TSTRING_H__ +#define __TSTRING_H__ + +#include "libchcore.h" +#include + +namespace chcore +{ + class TStringArray; + + /////////////////////////////////////////////////////////////// + // TString manipulation class + /** \brief String manipulation class + * + * Class allows user to manipulate TString objects (either standard ANSI char_t* + * based strings or UNICODE ones - wchar_t related) with simple functions and + * operators. + */ + class LIBCHCORE_API TString + { + public: + /** \name Construction/destruction */ + /*@{*/ + TString(); ///< Standard constructor + // cppcheck-suppress noExplicitConstructor + TString(const wchar_t* pszStr); ///< Constructor that takes const wchar_t* as an initial TString + TString(const wchar_t* pszStart, const wchar_t* pszEnd, size_t stMaxStringSize = DefaultMaxStringSize); + TString(const wchar_t* pszStart, size_t stCount); + TString(const TString& str); ///< Standard copy constructor + + ~TString(); ///< Standard destructor + /*@}*/ + + /** \name Operators */ + /**@{*/ + // assignment + TString& operator=(const TString& src); ///< Assign operator for TString objects + TString operator+(const TString& src) const; ///< Concatenate operator for TString objects + const TString& operator+=(const TString& src); ///< Merge operator for TString objects + + const TString& operator=(const wchar_t* pszSrc); ///< Assign operator from unicode strings + TString operator+(const wchar_t* pszSrc) const; ///< Concatenate operator for unicode strings + const TString& operator+=(const wchar_t* pszSrc); ///< Merge operator for unicode strings + + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator<(const wchar_t* psz) const { return Compare(psz) < 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator<=(const wchar_t* psz) const { return Compare(psz) <= 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator==(const wchar_t* psz) const { return Compare(psz) == 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator>=(const wchar_t* psz) const { return Compare(psz) >= 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator>(const wchar_t* psz) const { return Compare(psz) > 0; }; + /// Makes case sensitive comparison to the unicode TString ( see Compare(const wchar_t* psz) ) + bool operator!=(const wchar_t* psz) const { return Compare(psz) != 0; }; + + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator<(const TString& str) const { return Compare(str) < 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator<=(const TString& str) const { return Compare(str) <= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator==(const TString& str) const { return Compare(str) == 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator>=(const TString& str) const { return Compare(str) >= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator>(const TString& str) const { return Compare(str) >= 0; }; + /// Makes case sensitive comparison to the TString object ( see Compare(const TString& str) ) + bool operator!=(const TString& str) const { return Compare(str) != 0; }; + /**@}*/ + + /** \name Standard operations */ + /**@{*/ + // appends the given TString to this + void Append(const wchar_t* pszSrc); ///< Appends an unicode TString to the TString object + void Append(const TString& src); ///< Appends a TString object to another TString object + + TString Left(size_t tLen) const; ///< Returns TString with the Left part of a source TString + TString Right(size_t tLen) const; ///< Returns TString with the Right part of a source TString + TString Mid(size_t tStart, size_t tLen = (size_t)-1) const; ///< Returns TString with the middle part of a source TString + TString MidRange(size_t tStart, size_t stAfterEndPos) const; ///< Returns TString with the middle part of a source TString + + void LeftSelf(size_t tLen); ///< Makes this TString it's Left part + void RightSelf(size_t tLen); ///< Makes this TString it's Right part + void MidSelf(size_t tStart, size_t tLen = (size_t)-1); ///< Makes this TString it's middle part + + void TrimRightSelf(const wchar_t* pszElements); + + bool Delete(size_t stIndex, size_t stCount); + + void Split(const wchar_t* pszSeparators, TStringArray& rStrings) const; + + // compare operations + int Compare(const wchar_t* psz) const; ///< Comparison of this TString object with a given unicode TString + int Compare(const TString& str) const; ///< Comparison of this TString object with another TString object + + int CompareNoCase(const wchar_t* psz) const; ///< Comparison (case insensitive) of this TString object with a given unicode TString + int CompareNoCase(const TString& str) const; ///< Comparison (case insensitive) of this TString object with another TString object + + bool StartsWith(const wchar_t* pszText) const; + bool StartsWithNoCase(const wchar_t* pszText) const; + + bool EndsWith(const wchar_t* pszText) const; + bool EndsWithNoCase(const wchar_t* pszText) const; + + size_t FindFirstOf(const wchar_t* pszChars, size_t stStartFromPos = 0) const; + size_t FindLastOf(const wchar_t* pszChars) const; + + size_t Find(const wchar_t* pszText, size_t stStartPos = 0); + void Replace(const wchar_t* pszWhat, const wchar_t* pszWithWhat); + + bool GetAt(size_t tPos, wchar_t& wch) const; ///< Gets a character at a specified position + wchar_t GetAt(size_t tPos) const; + + const wchar_t* c_str() const; + + wchar_t* GetBuffer(size_t tMinSize); ///< Gives user access to the unicode internal buffer + void ReleaseBuffer(); ///< Releases the buffer get from get_bufferx functions + void ReleaseBufferSetLength(size_t tSize); + + size_t GetLength() const; ///< Returns the GetLength of this TString in chars + + void Clear(); ///< Clear the contents of the TString object + + bool IsEmpty() const; ///< Returns true if the TString is empty + /**@}*/ + + protected: + void SetString(const wchar_t* pszStart, size_t stCount); + void SetString(const wchar_t* pszString); + void Reserve(size_t stLen); + + protected: + wchar_t* m_pszData; // contains the real string inside + size_t m_stBufferSize; // allocated string buffer size + + public: + static const size_t npos = (size_t)-1; + static const size_t DefaultMaxStringSize = 65536; + }; + + inline std::wostream& operator<<(std::wostream& os, const TString& rString) + { + return os << std::wstring(rString.c_str()); + } +} + +LIBCHCORE_API chcore::TString operator+(const wchar_t* pszString, const chcore::TString& str); + +#endif Index: src/libchcore/TStringArray.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringArray.cpp (.../TStringArray.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TStringArray.cpp (.../TStringArray.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,234 +1,234 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TStringArray.cpp -/// @date 2011/06/05 -/// @brief Contains implementation of string array. -// ============================================================================ -#include "stdafx.h" -#include "TStringArray.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////////////////////////// - // class TStringArrayIterator - - TStringArrayIterator::TStringArrayIterator(std::vector::iterator iterArray) : - m_iterArray(iterArray) - { - } - - TStringArrayIterator::TStringArrayIterator() - { - } - - TStringArrayIterator::~TStringArrayIterator() - { - } - - TStringArrayIterator TStringArrayIterator::operator++(int) - { - TStringArrayIterator iterCurrent = *this; - ++m_iterArray; - return iterCurrent; - } - - TStringArrayIterator& TStringArrayIterator::operator++() - { - ++m_iterArray; - return *this; - } - - bool TStringArrayIterator::operator==(const TStringArrayIterator& rSrc) const - { - return m_iterArray == rSrc.m_iterArray; - } - - bool TStringArrayIterator::operator!=(const TStringArrayIterator& rSrc) const - { - return m_iterArray != rSrc.m_iterArray; - } - - TString& TStringArrayIterator::operator*() - { - return *m_iterArray; - } - - const TString& TStringArrayIterator::operator*() const - { - return *m_iterArray; - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////// - // class TStringArrayConstIterator - - TStringArrayConstIterator::TStringArrayConstIterator(std::vector::const_iterator iterArray) : - m_iterArray(iterArray) - { - } - - TStringArrayConstIterator::TStringArrayConstIterator() - { - } - - TStringArrayConstIterator::~TStringArrayConstIterator() - { - } - - TStringArrayConstIterator TStringArrayConstIterator::operator++(int) - { - TStringArrayConstIterator iterCurrent = *this; - ++m_iterArray; - return iterCurrent; - } - - TStringArrayConstIterator& TStringArrayConstIterator::operator++() - { - ++m_iterArray; - return *this; - } - - bool TStringArrayConstIterator::operator==(const TStringArrayConstIterator& rSrc) const - { - return m_iterArray == rSrc.m_iterArray; - } - - bool TStringArrayConstIterator::operator!=(const TStringArrayConstIterator& rSrc) const - { - return m_iterArray != rSrc.m_iterArray; - } - - const TString& TStringArrayConstIterator::operator*() - { - return *m_iterArray; - } - - const TString& TStringArrayConstIterator::operator*() const - { - return *m_iterArray; - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////// - // class TStringArray - TStringArray::TStringArray() - { - } - - TStringArray::~TStringArray() - { - } - - void TStringArray::Add(const TString& str) - { - m_vItems.push_back(str); - } - - void TStringArray::InsertAt(size_t stIndex, const TString& str) - { - if (stIndex >= m_vItems.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vItems.insert(m_vItems.begin() + stIndex, str); - } - - void TStringArray::SetAt(size_t stIndex, const TString& str) - { - if (stIndex >= m_vItems.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vItems[stIndex] = str; - } - - void TStringArray::RemoveAt(size_t stIndex) - { - if (stIndex >= m_vItems.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vItems.erase(m_vItems.begin() + stIndex); - } - - void TStringArray::Clear() - { - m_vItems.clear(); - } - - const TString& TStringArray::GetAt(size_t stIndex) const - { - if (stIndex >= m_vItems.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vItems.at(stIndex); - } - - size_t TStringArray::GetCount() const - { - return m_vItems.size(); - } - - TStringArrayIterator TStringArray::Begin() - { - return TStringArrayIterator(m_vItems.begin()); - } - - TStringArrayIterator TStringArray::End() - { - return TStringArrayIterator(m_vItems.end()); - } - - TStringArrayConstIterator TStringArray::Begin() const - { - return TStringArrayConstIterator(m_vItems.begin()); - } - - TStringArrayConstIterator TStringArray::End() const - { - return TStringArrayConstIterator(m_vItems.end()); - } - - bool TStringArray::operator==(const TStringArray& rSrc) const - { - if (rSrc.GetCount() != GetCount()) - return false; - - size_t stCount = GetCount(); - while (stCount-- > 0) - { - if (m_vItems[stCount] != rSrc.m_vItems[stCount]) - return false; - } - - return true; - } - - bool TStringArray::operator!=(const TStringArray& rSrc) const - { - if (rSrc.GetCount() != GetCount()) - return true; - - size_t stCount = GetCount(); - while (stCount-- > 0) - { - if (m_vItems[stCount] != rSrc.m_vItems[stCount]) - return true; - } - - return false; - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TStringArray.cpp +/// @date 2011/06/05 +/// @brief Contains implementation of string array. +// ============================================================================ +#include "stdafx.h" +#include "TStringArray.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArrayIterator + + TStringArrayIterator::TStringArrayIterator(std::vector::iterator iterArray) : + m_iterArray(iterArray) + { + } + + TStringArrayIterator::TStringArrayIterator() + { + } + + TStringArrayIterator::~TStringArrayIterator() + { + } + + TStringArrayIterator TStringArrayIterator::operator++(int) + { + TStringArrayIterator iterCurrent = *this; + ++m_iterArray; + return iterCurrent; + } + + TStringArrayIterator& TStringArrayIterator::operator++() + { + ++m_iterArray; + return *this; + } + + bool TStringArrayIterator::operator==(const TStringArrayIterator& rSrc) const + { + return m_iterArray == rSrc.m_iterArray; + } + + bool TStringArrayIterator::operator!=(const TStringArrayIterator& rSrc) const + { + return m_iterArray != rSrc.m_iterArray; + } + + TString& TStringArrayIterator::operator*() + { + return *m_iterArray; + } + + const TString& TStringArrayIterator::operator*() const + { + return *m_iterArray; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArrayConstIterator + + TStringArrayConstIterator::TStringArrayConstIterator(std::vector::const_iterator iterArray) : + m_iterArray(iterArray) + { + } + + TStringArrayConstIterator::TStringArrayConstIterator() + { + } + + TStringArrayConstIterator::~TStringArrayConstIterator() + { + } + + TStringArrayConstIterator TStringArrayConstIterator::operator++(int) + { + TStringArrayConstIterator iterCurrent = *this; + ++m_iterArray; + return iterCurrent; + } + + TStringArrayConstIterator& TStringArrayConstIterator::operator++() + { + ++m_iterArray; + return *this; + } + + bool TStringArrayConstIterator::operator==(const TStringArrayConstIterator& rSrc) const + { + return m_iterArray == rSrc.m_iterArray; + } + + bool TStringArrayConstIterator::operator!=(const TStringArrayConstIterator& rSrc) const + { + return m_iterArray != rSrc.m_iterArray; + } + + const TString& TStringArrayConstIterator::operator*() + { + return *m_iterArray; + } + + const TString& TStringArrayConstIterator::operator*() const + { + return *m_iterArray; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // class TStringArray + TStringArray::TStringArray() + { + } + + TStringArray::~TStringArray() + { + } + + void TStringArray::Add(const TString& str) + { + m_vItems.push_back(str); + } + + void TStringArray::InsertAt(size_t stIndex, const TString& str) + { + if (stIndex >= m_vItems.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vItems.insert(m_vItems.begin() + stIndex, str); + } + + void TStringArray::SetAt(size_t stIndex, const TString& str) + { + if (stIndex >= m_vItems.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vItems[stIndex] = str; + } + + void TStringArray::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vItems.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vItems.erase(m_vItems.begin() + stIndex); + } + + void TStringArray::Clear() + { + m_vItems.clear(); + } + + const TString& TStringArray::GetAt(size_t stIndex) const + { + if (stIndex >= m_vItems.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vItems.at(stIndex); + } + + size_t TStringArray::GetCount() const + { + return m_vItems.size(); + } + + TStringArrayIterator TStringArray::Begin() + { + return TStringArrayIterator(m_vItems.begin()); + } + + TStringArrayIterator TStringArray::End() + { + return TStringArrayIterator(m_vItems.end()); + } + + TStringArrayConstIterator TStringArray::Begin() const + { + return TStringArrayConstIterator(m_vItems.begin()); + } + + TStringArrayConstIterator TStringArray::End() const + { + return TStringArrayConstIterator(m_vItems.end()); + } + + bool TStringArray::operator==(const TStringArray& rSrc) const + { + if (rSrc.GetCount() != GetCount()) + return false; + + size_t stCount = GetCount(); + while (stCount-- > 0) + { + if (m_vItems[stCount] != rSrc.m_vItems[stCount]) + return false; + } + + return true; + } + + bool TStringArray::operator!=(const TStringArray& rSrc) const + { + if (rSrc.GetCount() != GetCount()) + return true; + + size_t stCount = GetCount(); + while (stCount-- > 0) + { + if (m_vItems[stCount] != rSrc.m_vItems[stCount]) + return true; + } + + return false; + } +} Index: src/libchcore/TStringArray.h =================================================================== diff -u -rcca174e74e108de1f5729e4cc6c46d2b9a5e25a7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringArray.h (.../TStringArray.h) (revision cca174e74e108de1f5729e4cc6c46d2b9a5e25a7) +++ src/libchcore/TStringArray.h (.../TStringArray.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,121 +1,121 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TStringArray.h -/// @date 2011/06/05 -/// @brief Contains string array definition. -// ============================================================================ -#ifndef __TSTRINGARRAY_H__ -#define __TSTRINGARRAY_H__ - -#include "TString.h" -#include "libchcore.h" -#include - -namespace chcore -{ - class LIBCHCORE_API TStringArrayIterator - { - protected: - explicit TStringArrayIterator(std::vector::iterator iterArray); - - public: - TStringArrayIterator(); - ~TStringArrayIterator(); - - TStringArrayIterator operator++(int); - TStringArrayIterator& operator++(); - - bool operator==(const TStringArrayIterator& rSrc) const; - bool operator!=(const TStringArrayIterator& rSrc) const; - - TString& operator*(); - const TString& operator*() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector::iterator m_iterArray; -#pragma warning(pop) - - friend class TStringArray; - }; - - class LIBCHCORE_API TStringArrayConstIterator - { - protected: - explicit TStringArrayConstIterator(std::vector::const_iterator iterArray); - - public: - TStringArrayConstIterator(); - ~TStringArrayConstIterator(); - - TStringArrayConstIterator operator++(int); - TStringArrayConstIterator& operator++(); - - bool operator==(const TStringArrayConstIterator& rSrc) const; - bool operator!=(const TStringArrayConstIterator& rSrc) const; - - const TString& operator*(); - const TString& operator*() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector::const_iterator m_iterArray; -#pragma warning(pop) - - friend class TStringArray; - }; - - class LIBCHCORE_API TStringArray - { - public: - typedef TStringArrayIterator iterator; - typedef TStringArrayConstIterator const_iterator; - - public: - TStringArray(); - ~TStringArray(); - - bool operator==(const TStringArray& rSrc) const; - bool operator!=(const TStringArray& rSrc) const; - - void Add(const TString& str); - void InsertAt(size_t stIndex, const TString& str); - void SetAt(size_t stIndex, const TString& str); - void RemoveAt(size_t stIndex); - void Clear(); - - const TString& GetAt(size_t stIndex) const; - size_t GetCount() const; - - TStringArrayIterator Begin(); - TStringArrayIterator End(); - TStringArrayConstIterator Begin() const; - TStringArrayConstIterator End() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vItems; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TStringArray.h +/// @date 2011/06/05 +/// @brief Contains string array definition. +// ============================================================================ +#ifndef __TSTRINGARRAY_H__ +#define __TSTRINGARRAY_H__ + +#include "TString.h" +#include "libchcore.h" +#include + +namespace chcore +{ + class LIBCHCORE_API TStringArrayIterator + { + protected: + explicit TStringArrayIterator(std::vector::iterator iterArray); + + public: + TStringArrayIterator(); + ~TStringArrayIterator(); + + TStringArrayIterator operator++(int); + TStringArrayIterator& operator++(); + + bool operator==(const TStringArrayIterator& rSrc) const; + bool operator!=(const TStringArrayIterator& rSrc) const; + + TString& operator*(); + const TString& operator*() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector::iterator m_iterArray; +#pragma warning(pop) + + friend class TStringArray; + }; + + class LIBCHCORE_API TStringArrayConstIterator + { + protected: + explicit TStringArrayConstIterator(std::vector::const_iterator iterArray); + + public: + TStringArrayConstIterator(); + ~TStringArrayConstIterator(); + + TStringArrayConstIterator operator++(int); + TStringArrayConstIterator& operator++(); + + bool operator==(const TStringArrayConstIterator& rSrc) const; + bool operator!=(const TStringArrayConstIterator& rSrc) const; + + const TString& operator*(); + const TString& operator*() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector::const_iterator m_iterArray; +#pragma warning(pop) + + friend class TStringArray; + }; + + class LIBCHCORE_API TStringArray + { + public: + typedef TStringArrayIterator iterator; + typedef TStringArrayConstIterator const_iterator; + + public: + TStringArray(); + ~TStringArray(); + + bool operator==(const TStringArray& rSrc) const; + bool operator!=(const TStringArray& rSrc) const; + + void Add(const TString& str); + void InsertAt(size_t stIndex, const TString& str); + void SetAt(size_t stIndex, const TString& str); + void RemoveAt(size_t stIndex); + void Clear(); + + const TString& GetAt(size_t stIndex) const; + size_t GetCount() const; + + TStringArrayIterator Begin(); + TStringArrayIterator End(); + TStringArrayConstIterator Begin() const; + TStringArrayConstIterator End() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vItems; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TStringException.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringException.cpp (.../TStringException.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TStringException.cpp (.../TStringException.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,15 +1,15 @@ -#include "stdafx.h" -#include "TStringException.h" - -namespace chcore -{ - TStringException::TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } - - TStringException::TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : - TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) - { - } -} +#include "stdafx.h" +#include "TStringException.h" + +namespace chcore +{ + TStringException::TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } + + TStringException::TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction) : + TBaseException(eErrorCode, pszMsg, pszFile, stLineNumber, pszFunction) + { + } +} Index: src/libchcore/TStringException.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringException.h (.../TStringException.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TStringException.h (.../TStringException.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,37 +1,37 @@ -/*************************************************************************** -* Copyright (C) 2001-2013 by J�zef Starosczyk * -* ixen@copyhandler.com * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License * -* (version 2) as published by the Free Software Foundation; * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ -#ifndef __TSTRINGEXCEPTION_H__ -#define __TSTRINGEXCEPTION_H__ - -#include "libchcore.h" -#include "ErrorCodes.h" -#include "TBaseException.h" - -namespace chcore -{ - class LIBCHCORE_API TStringException : public TBaseException - { - public: - TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); - TStringException() = delete; - }; -} - -#endif +/*************************************************************************** +* Copyright (C) 2001-2013 by J�zef Starosczyk * +* ixen@copyhandler.com * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU Library General Public License * +* (version 2) as published by the Free Software Foundation; * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU Library General Public * +* License along with this program; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef __TSTRINGEXCEPTION_H__ +#define __TSTRINGEXCEPTION_H__ + +#include "libchcore.h" +#include "ErrorCodes.h" +#include "TBaseException.h" + +namespace chcore +{ + class LIBCHCORE_API TStringException : public TBaseException + { + public: + TStringException(EGeneralErrors eErrorCode, const wchar_t* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TStringException(EGeneralErrors eErrorCode, const char* pszMsg, const wchar_t* pszFile, size_t stLineNumber, const wchar_t* pszFunction); + TStringException() = delete; + }; +} + +#endif Index: src/libchcore/TStringPattern.cpp =================================================================== diff -u -rd18db617f4727a237c94b59af9b4328f829eda16 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringPattern.cpp (.../TStringPattern.cpp) (revision d18db617f4727a237c94b59af9b4328f829eda16) +++ src/libchcore/TStringPattern.cpp (.../TStringPattern.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,132 +1,132 @@ -#include "stdafx.h" -#include "TStringPattern.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include - -namespace chcore -{ - namespace - { - bool _tcicmp(TCHAR c1, TCHAR c2) - { - TCHAR ch1[2] = { c1, 0 }, ch2[2] = { c2, 0 }; - return (_tcsicmp(ch1, ch2) == 0); - } - } - - TStringPattern::TStringPattern(EPatternType ePatternType) : - m_ePatternType(ePatternType) - { - } - - TStringPattern::TStringPattern(const TString& strPattern, EPatternType ePatternType) : - m_ePatternType(ePatternType), - m_strPattern(strPattern) - { - } - - TStringPattern TStringPattern::CreateFromString(const TString& strPattern, EPatternType eDefaultPatternType) - { - TStringPattern pattern; - pattern.FromString(strPattern, eDefaultPatternType); - return pattern; - } - - void TStringPattern::FromString(const TString& strPattern, EPatternType eDefaultPatternType) - { - m_ePatternType = eDefaultPatternType; - if (strPattern.StartsWith(L"WC;")) - { - m_strPattern = strPattern.Mid(3); - m_ePatternType = EPatternType::eType_Wildcard; - } - else - m_strPattern = strPattern; - } - - TString TStringPattern::ToString() const - { - TString strPrefix; - switch (m_ePatternType) - { - case EPatternType::eType_Wildcard: - break; // wildcard won't have any prefix (it's implicit) - - default: - throw TCoreException(eErr_UnhandledCase, L"Pattern type not supported", LOCATION); - } - - return TString(strPrefix + m_strPattern); - } - - bool TStringPattern::MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const - { - bool bMatch = true; - - //iterate and delete '?' and '*' one by one - while (*lpszMask != _T('\0') && bMatch && *lpszString != _T('\0')) - { - if (*lpszMask == _T('?')) lpszString++; - else if (*lpszMask == _T('*')) - { - bMatch = Scan(lpszMask, lpszString); - lpszMask--; - } - else - { - bMatch = _tcicmp(*lpszMask, *lpszString); - lpszString++; - } - lpszMask++; - } - while (*lpszMask == _T('*') && bMatch) lpszMask++; - - return bMatch && *lpszString == _T('\0') && *lpszMask == _T('\0'); - } - - // scan '?' and '*' - bool TStringPattern::Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const - { - // remove the '?' and '*' - for (lpszMask++; *lpszString != _T('\0') && (*lpszMask == _T('?') || *lpszMask == _T('*')); lpszMask++) - if (*lpszMask == _T('?')) lpszString++; - while (*lpszMask == _T('*')) lpszMask++; - - // if lpszString is empty and lpszMask has more characters or, - // lpszMask is empty, return - if (*lpszString == _T('\0') && *lpszMask != _T('\0')) return false; - if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; - // else search substring - else - { - LPCTSTR wdsCopy = lpszMask; - LPCTSTR lpszStringCopy = lpszString; - bool bMatch = true; - do - { - if (!MatchMask(lpszMask, lpszString)) lpszStringCopy++; - lpszMask = wdsCopy; - lpszString = lpszStringCopy; - while (!(_tcicmp(*lpszMask, *lpszString)) && (*lpszString != '\0')) lpszString++; - wdsCopy = lpszMask; - lpszStringCopy = lpszString; - } while ((*lpszString != _T('\0')) ? !MatchMask(lpszMask, lpszString) : (bMatch = false) != false); - - if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; - - return bMatch; - } - } - - bool TStringPattern::Matches(const TString& strTextToMatch) const - { - return MatchMask(m_strPattern.c_str(), strTextToMatch.c_str()); - } - - void TStringPattern::SetPattern(const TString& strPattern, EPatternType ePatternType) - { - m_ePatternType = ePatternType; - m_strPattern = strPattern; - } -} +#include "stdafx.h" +#include "TStringPattern.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include + +namespace chcore +{ + namespace + { + bool _tcicmp(TCHAR c1, TCHAR c2) + { + TCHAR ch1[2] = { c1, 0 }, ch2[2] = { c2, 0 }; + return (_tcsicmp(ch1, ch2) == 0); + } + } + + TStringPattern::TStringPattern(EPatternType ePatternType) : + m_ePatternType(ePatternType) + { + } + + TStringPattern::TStringPattern(const TString& strPattern, EPatternType ePatternType) : + m_ePatternType(ePatternType), + m_strPattern(strPattern) + { + } + + TStringPattern TStringPattern::CreateFromString(const TString& strPattern, EPatternType eDefaultPatternType) + { + TStringPattern pattern; + pattern.FromString(strPattern, eDefaultPatternType); + return pattern; + } + + void TStringPattern::FromString(const TString& strPattern, EPatternType eDefaultPatternType) + { + m_ePatternType = eDefaultPatternType; + if (strPattern.StartsWith(L"WC;")) + { + m_strPattern = strPattern.Mid(3); + m_ePatternType = EPatternType::eType_Wildcard; + } + else + m_strPattern = strPattern; + } + + TString TStringPattern::ToString() const + { + TString strPrefix; + switch (m_ePatternType) + { + case EPatternType::eType_Wildcard: + break; // wildcard won't have any prefix (it's implicit) + + default: + throw TCoreException(eErr_UnhandledCase, L"Pattern type not supported", LOCATION); + } + + return TString(strPrefix + m_strPattern); + } + + bool TStringPattern::MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const + { + bool bMatch = true; + + //iterate and delete '?' and '*' one by one + while (*lpszMask != _T('\0') && bMatch && *lpszString != _T('\0')) + { + if (*lpszMask == _T('?')) lpszString++; + else if (*lpszMask == _T('*')) + { + bMatch = Scan(lpszMask, lpszString); + lpszMask--; + } + else + { + bMatch = _tcicmp(*lpszMask, *lpszString); + lpszString++; + } + lpszMask++; + } + while (*lpszMask == _T('*') && bMatch) lpszMask++; + + return bMatch && *lpszString == _T('\0') && *lpszMask == _T('\0'); + } + + // scan '?' and '*' + bool TStringPattern::Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const + { + // remove the '?' and '*' + for (lpszMask++; *lpszString != _T('\0') && (*lpszMask == _T('?') || *lpszMask == _T('*')); lpszMask++) + if (*lpszMask == _T('?')) lpszString++; + while (*lpszMask == _T('*')) lpszMask++; + + // if lpszString is empty and lpszMask has more characters or, + // lpszMask is empty, return + if (*lpszString == _T('\0') && *lpszMask != _T('\0')) return false; + if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; + // else search substring + else + { + LPCTSTR wdsCopy = lpszMask; + LPCTSTR lpszStringCopy = lpszString; + bool bMatch = true; + do + { + if (!MatchMask(lpszMask, lpszString)) lpszStringCopy++; + lpszMask = wdsCopy; + lpszString = lpszStringCopy; + while (!(_tcicmp(*lpszMask, *lpszString)) && (*lpszString != '\0')) lpszString++; + wdsCopy = lpszMask; + lpszStringCopy = lpszString; + } while ((*lpszString != _T('\0')) ? !MatchMask(lpszMask, lpszString) : (bMatch = false) != false); + + if (*lpszString == _T('\0') && *lpszMask == _T('\0')) return true; + + return bMatch; + } + } + + bool TStringPattern::Matches(const TString& strTextToMatch) const + { + return MatchMask(m_strPattern.c_str(), strTextToMatch.c_str()); + } + + void TStringPattern::SetPattern(const TString& strPattern, EPatternType ePatternType) + { + m_ePatternType = ePatternType; + m_strPattern = strPattern; + } +} Index: src/libchcore/TStringPattern.h =================================================================== diff -u -rfcf6698a5e67445b1a68627fa94837b1ad97284e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringPattern.h (.../TStringPattern.h) (revision fcf6698a5e67445b1a68627fa94837b1ad97284e) +++ src/libchcore/TStringPattern.h (.../TStringPattern.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,61 +1,61 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSTRINGPATTERN_H__ -#define __TSTRINGPATTERN_H__ - -#include "libchcore.h" -#include "TString.h" - -namespace chcore -{ - class LIBCHCORE_API TStringPattern - { - public: - enum class EPatternType - { - eType_Wildcard - }; - - public: - explicit TStringPattern(EPatternType ePatternType = EPatternType::eType_Wildcard); - TStringPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); - - void SetPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); - bool Matches(const TString& strTextToMatch) const; - - EPatternType GetPatternType() const { return m_ePatternType; } - TString GetPattern() const { return m_strPattern; } - - // string parsing - static TStringPattern CreateFromString(const TString& strPattern, EPatternType eDefaultPatternType = EPatternType::eType_Wildcard); - - void FromString(const TString& strPattern, EPatternType eDefaultPatternType = EPatternType::eType_Wildcard); - TString ToString() const; - - private: - bool MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const; - bool Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const; - - private: - TString m_strPattern; - EPatternType m_ePatternType; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSTRINGPATTERN_H__ +#define __TSTRINGPATTERN_H__ + +#include "libchcore.h" +#include "TString.h" + +namespace chcore +{ + class LIBCHCORE_API TStringPattern + { + public: + enum class EPatternType + { + eType_Wildcard + }; + + public: + explicit TStringPattern(EPatternType ePatternType = EPatternType::eType_Wildcard); + TStringPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); + + void SetPattern(const TString& strPattern, EPatternType ePatternType = EPatternType::eType_Wildcard); + bool Matches(const TString& strTextToMatch) const; + + EPatternType GetPatternType() const { return m_ePatternType; } + TString GetPattern() const { return m_strPattern; } + + // string parsing + static TStringPattern CreateFromString(const TString& strPattern, EPatternType eDefaultPatternType = EPatternType::eType_Wildcard); + + void FromString(const TString& strPattern, EPatternType eDefaultPatternType = EPatternType::eType_Wildcard); + TString ToString() const; + + private: + bool MatchMask(LPCTSTR lpszMask, LPCTSTR lpszString) const; + bool Scan(LPCTSTR& lpszMask, LPCTSTR& lpszString) const; + + private: + TString m_strPattern; + EPatternType m_ePatternType; + }; +} + +#endif Index: src/libchcore/TStringPatternArray.cpp =================================================================== diff -u -rfcf6698a5e67445b1a68627fa94837b1ad97284e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringPatternArray.cpp (.../TStringPatternArray.cpp) (revision fcf6698a5e67445b1a68627fa94837b1ad97284e) +++ src/libchcore/TStringPatternArray.cpp (.../TStringPatternArray.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,155 +1,155 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TStringPatternArray.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TStringArray.h" - -namespace chcore -{ - TStringPatternArray::TStringPatternArray() - { - } - - TStringPatternArray::~TStringPatternArray() - { - } - - void TStringPatternArray::Add(const TStringPattern& strPattern) - { - m_vPatterns.push_back(strPattern); - } - - void TStringPatternArray::InsertAt(size_t stIndex, const TStringPattern& strPattern) - { - if (stIndex > m_vPatterns.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vPatterns.insert(m_vPatterns.begin() + stIndex, strPattern); - } - - void TStringPatternArray::SetAt(size_t stIndex, const TStringPattern& strPattern) - { - if (stIndex >= m_vPatterns.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vPatterns[stIndex] = strPattern; - } - - void TStringPatternArray::RemoveAt(size_t stIndex) - { - if (stIndex >= m_vPatterns.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - m_vPatterns.erase(m_vPatterns.begin() + stIndex); - } - - void TStringPatternArray::Clear() - { - m_vPatterns.clear(); - } - - const TStringPattern& TStringPatternArray::GetAt(size_t stIndex) const - { - if (stIndex >= m_vPatterns.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vPatterns[stIndex]; - } - - size_t TStringPatternArray::GetCount() const - { - return m_vPatterns.size(); - } - - bool TStringPatternArray::MatchesAny(const TString& strTextToMatch) const - { - for (const TStringPattern& pattern : m_vPatterns) - { - if (pattern.Matches(strTextToMatch)) - return true; - } - - return false; - } - - bool TStringPatternArray::MatchesAll(const TString& strTextToMatch) const - { - for (const TStringPattern& pattern : m_vPatterns) - { - if (!pattern.Matches(strTextToMatch)) - return false; - } - - return true; - } - - void TStringPatternArray::FromString(const TString& strPatterns, TStringPattern::EPatternType eDefaultPatternType) - { - TStringArray arrPatterns; - strPatterns.Split(_T("|"), arrPatterns); - FromStringArray(arrPatterns, eDefaultPatternType); - } - - void TStringPatternArray::FromSerializedStringArray(const TStringArray& arrSerializedPatterns) - { - m_vPatterns.clear(); - - for (size_t stIndex = 0; stIndex < arrSerializedPatterns.GetCount(); ++stIndex) - { - m_vPatterns.push_back(TStringPattern::CreateFromString(arrSerializedPatterns.GetAt(stIndex))); - } - } - - void TStringPatternArray::FromStringArray(const TStringArray& arrPatterns, TStringPattern::EPatternType eDefaultPatternType) - { - for (size_t stIndex = 0; stIndex < arrPatterns.GetCount(); ++stIndex) - { - Add(TStringPattern::CreateFromString(arrPatterns.GetAt(stIndex), eDefaultPatternType)); - } - } - - TString TStringPatternArray::ToString() const - { - TString strMask; - size_t stCount = GetCount(); - if (stCount > 0) - { - strMask = GetAt(0).ToString(); - for (size_t stIndex = 1; stIndex < stCount; stIndex++) - { - strMask += _T("|") + GetAt(stIndex).ToString(); - } - } - - return strMask; - } - - TStringArray TStringPatternArray::ToSerializedStringArray() const - { - TStringArray arrSerialized; - for (const TStringPattern& pattern : m_vPatterns) - { - arrSerialized.Add(pattern.ToString()); - } - - return arrSerialized; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TStringPatternArray.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TStringArray.h" + +namespace chcore +{ + TStringPatternArray::TStringPatternArray() + { + } + + TStringPatternArray::~TStringPatternArray() + { + } + + void TStringPatternArray::Add(const TStringPattern& strPattern) + { + m_vPatterns.push_back(strPattern); + } + + void TStringPatternArray::InsertAt(size_t stIndex, const TStringPattern& strPattern) + { + if (stIndex > m_vPatterns.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vPatterns.insert(m_vPatterns.begin() + stIndex, strPattern); + } + + void TStringPatternArray::SetAt(size_t stIndex, const TStringPattern& strPattern) + { + if (stIndex >= m_vPatterns.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vPatterns[stIndex] = strPattern; + } + + void TStringPatternArray::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vPatterns.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + m_vPatterns.erase(m_vPatterns.begin() + stIndex); + } + + void TStringPatternArray::Clear() + { + m_vPatterns.clear(); + } + + const TStringPattern& TStringPatternArray::GetAt(size_t stIndex) const + { + if (stIndex >= m_vPatterns.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vPatterns[stIndex]; + } + + size_t TStringPatternArray::GetCount() const + { + return m_vPatterns.size(); + } + + bool TStringPatternArray::MatchesAny(const TString& strTextToMatch) const + { + for (const TStringPattern& pattern : m_vPatterns) + { + if (pattern.Matches(strTextToMatch)) + return true; + } + + return false; + } + + bool TStringPatternArray::MatchesAll(const TString& strTextToMatch) const + { + for (const TStringPattern& pattern : m_vPatterns) + { + if (!pattern.Matches(strTextToMatch)) + return false; + } + + return true; + } + + void TStringPatternArray::FromString(const TString& strPatterns, TStringPattern::EPatternType eDefaultPatternType) + { + TStringArray arrPatterns; + strPatterns.Split(_T("|"), arrPatterns); + FromStringArray(arrPatterns, eDefaultPatternType); + } + + void TStringPatternArray::FromSerializedStringArray(const TStringArray& arrSerializedPatterns) + { + m_vPatterns.clear(); + + for (size_t stIndex = 0; stIndex < arrSerializedPatterns.GetCount(); ++stIndex) + { + m_vPatterns.push_back(TStringPattern::CreateFromString(arrSerializedPatterns.GetAt(stIndex))); + } + } + + void TStringPatternArray::FromStringArray(const TStringArray& arrPatterns, TStringPattern::EPatternType eDefaultPatternType) + { + for (size_t stIndex = 0; stIndex < arrPatterns.GetCount(); ++stIndex) + { + Add(TStringPattern::CreateFromString(arrPatterns.GetAt(stIndex), eDefaultPatternType)); + } + } + + TString TStringPatternArray::ToString() const + { + TString strMask; + size_t stCount = GetCount(); + if (stCount > 0) + { + strMask = GetAt(0).ToString(); + for (size_t stIndex = 1; stIndex < stCount; stIndex++) + { + strMask += _T("|") + GetAt(stIndex).ToString(); + } + } + + return strMask; + } + + TStringArray TStringPatternArray::ToSerializedStringArray() const + { + TStringArray arrSerialized; + for (const TStringPattern& pattern : m_vPatterns) + { + arrSerialized.Add(pattern.ToString()); + } + + return arrSerialized; + } +} Index: src/libchcore/TStringPatternArray.h =================================================================== diff -u -rfcf6698a5e67445b1a68627fa94837b1ad97284e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringPatternArray.h (.../TStringPatternArray.h) (revision fcf6698a5e67445b1a68627fa94837b1ad97284e) +++ src/libchcore/TStringPatternArray.h (.../TStringPatternArray.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,64 +1,64 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSTRINGPATTERNARRAY_H__ -#define __TSTRINGPATTERNARRAY_H__ - -#include "libchcore.h" -#include "TStringPattern.h" - -namespace chcore -{ - class LIBCHCORE_API TStringPatternArray - { - public: - TStringPatternArray(); - ~TStringPatternArray(); - - // general api - void Add(const TStringPattern& strPattern); - void InsertAt(size_t stIndex, const TStringPattern& strPattern); - void SetAt(size_t stIndex, const TStringPattern& strPattern); - void RemoveAt(size_t stIndex); - void Clear(); - - const TStringPattern& GetAt(size_t stIndex) const; - size_t GetCount() const; - - // pattern api - bool MatchesAny(const TString& strTextToMatch) const; - bool MatchesAll(const TString& strTextToMatch) const; - - // string parsing - void FromString(const TString& strPatterns, TStringPattern::EPatternType eDefaultPatternType = TStringPattern::EPatternType::eType_Wildcard); - void FromStringArray(const TStringArray& strPatterns, TStringPattern::EPatternType eDefaultPatternType = TStringPattern::EPatternType::eType_Wildcard); - TString ToString() const; - - // serialization - void FromSerializedStringArray(const TStringArray& arrSerializedPatterns); - TStringArray ToSerializedStringArray() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vPatterns; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSTRINGPATTERNARRAY_H__ +#define __TSTRINGPATTERNARRAY_H__ + +#include "libchcore.h" +#include "TStringPattern.h" + +namespace chcore +{ + class LIBCHCORE_API TStringPatternArray + { + public: + TStringPatternArray(); + ~TStringPatternArray(); + + // general api + void Add(const TStringPattern& strPattern); + void InsertAt(size_t stIndex, const TStringPattern& strPattern); + void SetAt(size_t stIndex, const TStringPattern& strPattern); + void RemoveAt(size_t stIndex); + void Clear(); + + const TStringPattern& GetAt(size_t stIndex) const; + size_t GetCount() const; + + // pattern api + bool MatchesAny(const TString& strTextToMatch) const; + bool MatchesAll(const TString& strTextToMatch) const; + + // string parsing + void FromString(const TString& strPatterns, TStringPattern::EPatternType eDefaultPatternType = TStringPattern::EPatternType::eType_Wildcard); + void FromStringArray(const TStringArray& strPatterns, TStringPattern::EPatternType eDefaultPatternType = TStringPattern::EPatternType::eType_Wildcard); + TString ToString() const; + + // serialization + void FromSerializedStringArray(const TStringArray& arrSerializedPatterns); + TStringArray ToSerializedStringArray() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vPatterns; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TStringSet.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringSet.cpp (.../TStringSet.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TStringSet.cpp (.../TStringSet.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,188 +1,188 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TStringSet.cpp -/// @date 2011/06/05 -/// @brief Contains implementation of string set. -// ============================================================================ -#include "stdafx.h" -#include "TStringSet.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////////////// - // class TStringSetIterator - - TStringSetIterator::TStringSetIterator(std::set::iterator iterSet) : - m_iterSet(iterSet) - { - } - - TStringSetIterator::TStringSetIterator() - { - - } - - TStringSetIterator::~TStringSetIterator() - { - - } - - TStringSetIterator TStringSetIterator::operator++(int) - { - TStringSetIterator iterCurrent(m_iterSet); - ++m_iterSet; - return iterCurrent; - } - - TStringSetIterator& TStringSetIterator::operator++() - { - ++m_iterSet; - return *this; - } - - bool TStringSetIterator::operator==(const TStringSetIterator& rSrc) const - { - return m_iterSet == rSrc.m_iterSet; - } - - bool TStringSetIterator::operator!=(const TStringSetIterator& rSrc) const - { - return m_iterSet != rSrc.m_iterSet; - } - - const TString& TStringSetIterator::operator*() const - { - return *m_iterSet; - } - - /////////////////////////////////////////////////////////////////////////////////////////// - // class TStringSetConstIterator - - TStringSetConstIterator::TStringSetConstIterator(std::set::const_iterator iterSet) : - m_iterSet(iterSet) - { - } - - TStringSetConstIterator::TStringSetConstIterator() - { - - } - - TStringSetConstIterator::~TStringSetConstIterator() - { - - } - - TStringSetConstIterator TStringSetConstIterator::operator++(int) - { - TStringSetConstIterator iterCurrent(m_iterSet); - ++m_iterSet; - return iterCurrent; - } - - TStringSetConstIterator& TStringSetConstIterator::operator++() - { - ++m_iterSet; - return *this; - } - - bool TStringSetConstIterator::operator==(const TStringSetConstIterator& rSrc) const - { - return m_iterSet == rSrc.m_iterSet; - } - - bool TStringSetConstIterator::operator!=(const TStringSetConstIterator& rSrc) const - { - return m_iterSet != rSrc.m_iterSet; - } - - const TString& TStringSetConstIterator::operator*() const - { - return *m_iterSet; - } - - /////////////////////////////////////////////////////////////////////////////////////////// - // class TStringSet - - TStringSet::TStringSet() - { - } - - TStringSet::~TStringSet() - { - } - - void TStringSet::Insert(const TString& str) - { - m_setItems.insert(str); - } - - void TStringSet::Insert(const TStringSet& setStrings) - { - m_setItems.insert(setStrings.m_setItems.begin(), setStrings.m_setItems.end()); - } - - void TStringSet::Remove(const TString& str) - { - std::set::iterator iter = m_setItems.find(str); - if (iter != m_setItems.end()) - m_setItems.erase(iter); - } - - void TStringSet::Clear() - { - m_setItems.clear(); - } - - bool TStringSet::HasValue(const TString& str) const - { - std::set::const_iterator iter = m_setItems.find(str); - return (iter != m_setItems.end()); - } - - size_t TStringSet::GetCount() const - { - return m_setItems.size(); - } - - bool TStringSet::IsEmpty() const - { - return m_setItems.empty(); - } - - TStringSetIterator TStringSet::Begin() - { - return TStringSetIterator(m_setItems.begin()); - } - - TStringSetIterator TStringSet::End() - { - return TStringSetIterator(m_setItems.end()); - } - - TStringSetConstIterator TStringSet::Begin() const - { - return TStringSetConstIterator(m_setItems.begin()); - } - - TStringSetConstIterator TStringSet::End() const - { - return TStringSetConstIterator(m_setItems.end()); - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TStringSet.cpp +/// @date 2011/06/05 +/// @brief Contains implementation of string set. +// ============================================================================ +#include "stdafx.h" +#include "TStringSet.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSetIterator + + TStringSetIterator::TStringSetIterator(std::set::iterator iterSet) : + m_iterSet(iterSet) + { + } + + TStringSetIterator::TStringSetIterator() + { + + } + + TStringSetIterator::~TStringSetIterator() + { + + } + + TStringSetIterator TStringSetIterator::operator++(int) + { + TStringSetIterator iterCurrent(m_iterSet); + ++m_iterSet; + return iterCurrent; + } + + TStringSetIterator& TStringSetIterator::operator++() + { + ++m_iterSet; + return *this; + } + + bool TStringSetIterator::operator==(const TStringSetIterator& rSrc) const + { + return m_iterSet == rSrc.m_iterSet; + } + + bool TStringSetIterator::operator!=(const TStringSetIterator& rSrc) const + { + return m_iterSet != rSrc.m_iterSet; + } + + const TString& TStringSetIterator::operator*() const + { + return *m_iterSet; + } + + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSetConstIterator + + TStringSetConstIterator::TStringSetConstIterator(std::set::const_iterator iterSet) : + m_iterSet(iterSet) + { + } + + TStringSetConstIterator::TStringSetConstIterator() + { + + } + + TStringSetConstIterator::~TStringSetConstIterator() + { + + } + + TStringSetConstIterator TStringSetConstIterator::operator++(int) + { + TStringSetConstIterator iterCurrent(m_iterSet); + ++m_iterSet; + return iterCurrent; + } + + TStringSetConstIterator& TStringSetConstIterator::operator++() + { + ++m_iterSet; + return *this; + } + + bool TStringSetConstIterator::operator==(const TStringSetConstIterator& rSrc) const + { + return m_iterSet == rSrc.m_iterSet; + } + + bool TStringSetConstIterator::operator!=(const TStringSetConstIterator& rSrc) const + { + return m_iterSet != rSrc.m_iterSet; + } + + const TString& TStringSetConstIterator::operator*() const + { + return *m_iterSet; + } + + /////////////////////////////////////////////////////////////////////////////////////////// + // class TStringSet + + TStringSet::TStringSet() + { + } + + TStringSet::~TStringSet() + { + } + + void TStringSet::Insert(const TString& str) + { + m_setItems.insert(str); + } + + void TStringSet::Insert(const TStringSet& setStrings) + { + m_setItems.insert(setStrings.m_setItems.begin(), setStrings.m_setItems.end()); + } + + void TStringSet::Remove(const TString& str) + { + std::set::iterator iter = m_setItems.find(str); + if (iter != m_setItems.end()) + m_setItems.erase(iter); + } + + void TStringSet::Clear() + { + m_setItems.clear(); + } + + bool TStringSet::HasValue(const TString& str) const + { + std::set::const_iterator iter = m_setItems.find(str); + return (iter != m_setItems.end()); + } + + size_t TStringSet::GetCount() const + { + return m_setItems.size(); + } + + bool TStringSet::IsEmpty() const + { + return m_setItems.empty(); + } + + TStringSetIterator TStringSet::Begin() + { + return TStringSetIterator(m_setItems.begin()); + } + + TStringSetIterator TStringSet::End() + { + return TStringSetIterator(m_setItems.end()); + } + + TStringSetConstIterator TStringSet::Begin() const + { + return TStringSetConstIterator(m_setItems.begin()); + } + + TStringSetConstIterator TStringSet::End() const + { + return TStringSetConstIterator(m_setItems.end()); + } +} Index: src/libchcore/TStringSet.h =================================================================== diff -u -rcb4e9d4b60d62b25ae2cf556c0642601af56c787 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TStringSet.h (.../TStringSet.h) (revision cb4e9d4b60d62b25ae2cf556c0642601af56c787) +++ src/libchcore/TStringSet.h (.../TStringSet.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,115 +1,115 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TStringSet.h -/// @date 2011/06/05 -/// @brief Contains definition of string set. -// ============================================================================ -#ifndef __TSTRINGSET_H__ -#define __TSTRINGSET_H__ - -#include "TString.h" -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API TStringSetIterator - { - protected: - explicit TStringSetIterator(std::set::iterator iterSet); - - public: - TStringSetIterator(); - ~TStringSetIterator(); - - TStringSetIterator operator++(int); - TStringSetIterator& operator++(); - - bool operator==(const TStringSetIterator& rSrc) const; - bool operator!=(const TStringSetIterator& rSrc) const; - - const TString& operator*() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::set::iterator m_iterSet; -#pragma warning(pop) - - friend class TStringSet; - }; - - class LIBCHCORE_API TStringSetConstIterator - { - protected: - explicit TStringSetConstIterator(std::set::const_iterator iterSet); - - public: - TStringSetConstIterator(); - ~TStringSetConstIterator(); - - TStringSetConstIterator operator++(int); - TStringSetConstIterator& operator++(); - - bool operator==(const TStringSetConstIterator& rSrc) const; - bool operator!=(const TStringSetConstIterator& rSrc) const; - - const TString& operator*() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::set::const_iterator m_iterSet; -#pragma warning(pop) - - friend class TStringSet; - }; - - class LIBCHCORE_API TStringSet - { - public: - typedef TStringSetIterator iterator; - typedef TStringSetConstIterator const_iterator; - - public: - TStringSet(); - ~TStringSet(); - - void Insert(const TString& str); - void Insert(const TStringSet& setStrings); - void Remove(const TString& str); - void Clear(); - - bool HasValue(const TString& str) const; - size_t GetCount() const; - bool IsEmpty() const; - - TStringSetIterator Begin(); - TStringSetIterator End(); - TStringSetConstIterator Begin() const; - TStringSetConstIterator End() const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::set m_setItems; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TStringSet.h +/// @date 2011/06/05 +/// @brief Contains definition of string set. +// ============================================================================ +#ifndef __TSTRINGSET_H__ +#define __TSTRINGSET_H__ + +#include "TString.h" +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API TStringSetIterator + { + protected: + explicit TStringSetIterator(std::set::iterator iterSet); + + public: + TStringSetIterator(); + ~TStringSetIterator(); + + TStringSetIterator operator++(int); + TStringSetIterator& operator++(); + + bool operator==(const TStringSetIterator& rSrc) const; + bool operator!=(const TStringSetIterator& rSrc) const; + + const TString& operator*() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::set::iterator m_iterSet; +#pragma warning(pop) + + friend class TStringSet; + }; + + class LIBCHCORE_API TStringSetConstIterator + { + protected: + explicit TStringSetConstIterator(std::set::const_iterator iterSet); + + public: + TStringSetConstIterator(); + ~TStringSetConstIterator(); + + TStringSetConstIterator operator++(int); + TStringSetConstIterator& operator++(); + + bool operator==(const TStringSetConstIterator& rSrc) const; + bool operator!=(const TStringSetConstIterator& rSrc) const; + + const TString& operator*() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::set::const_iterator m_iterSet; +#pragma warning(pop) + + friend class TStringSet; + }; + + class LIBCHCORE_API TStringSet + { + public: + typedef TStringSetIterator iterator; + typedef TStringSetConstIterator const_iterator; + + public: + TStringSet(); + ~TStringSet(); + + void Insert(const TString& str); + void Insert(const TStringSet& setStrings); + void Remove(const TString& str); + void Clear(); + + bool HasValue(const TString& str) const; + size_t GetCount() const; + bool IsEmpty() const; + + TStringSetIterator Begin(); + TStringSetIterator End(); + TStringSetConstIterator Begin() const; + TStringSetConstIterator End() const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::set m_setItems; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskArray.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskArray.cpp (.../TSubTaskArray.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSubTaskArray.cpp (.../TSubTaskArray.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,398 +1,398 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskArray.cpp -/// @date 2011/11/08 -/// @brief File contain implementation of a class handling a sequence of subtasks. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskArray.h" -#include "TTaskOperationPlan.h" -#include "TSubTaskScanDirectory.h" -#include "TSubTaskCopyMove.h" -#include "TSubTaskDelete.h" -#include "TSubTaskContext.h" -#include "TTaskLocalStats.h" -#include "TSubTaskFastMove.h" -#include "TTaskStatsSnapshot.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include -#include "TTaskConfiguration.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - // TSubTasksArray - - TSubTasksArray::TSubTasksArray(TSubTaskContext& rSubTaskContext) : - m_rSubTaskContext(rSubTaskContext), - m_eOperationType(m_setModifications, eOperation_None), - m_oidSubOperationIndex(0), - m_oidLastStoredIndex((object_id_t)-1) - { - m_setModifications[eMod_Added] = true; - } - - TSubTasksArray::TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext) : - m_rSubTaskContext(rSubTaskContext), - m_eOperationType(m_setModifications, eOperation_None), - m_oidSubOperationIndex(0), - m_oidLastStoredIndex((object_id_t)-1) - { - m_setModifications[eMod_Added] = true; - Init(rOperationPlan); - } - - TSubTasksArray::~TSubTasksArray() - { - } - - void TSubTasksArray::Init(const TOperationPlan& rOperationPlan) - { - m_vSubTasks.clear(); - m_rSubTaskContext.GetFilesCache().Clear(); - m_oidSubOperationIndex.store(0, std::memory_order_release); - - m_eOperationType = rOperationPlan.GetOperationType(); - - bool bReadTasksSizeBeforeBlocking = GetTaskPropValue(m_rSubTaskContext.GetConfig()); - bool bFastMoveBeforeBlocking = GetTaskPropValue(m_rSubTaskContext.GetConfig()); - - switch (m_eOperationType) - { - case eOperation_Copy: - { - TSubTaskBasePtr spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, bReadTasksSizeBeforeBlocking); - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, false); - - break; - } - - case eOperation_Move: - { - TSubTaskBasePtr spOperation; - bool bReorderFastMove = bReadTasksSizeBeforeBlocking && !bFastMoveBeforeBlocking; - - // fastmove (if not reordered) - if(!bReorderFastMove) - { - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, bFastMoveBeforeBlocking); - } - - // scanning - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, bReadTasksSizeBeforeBlocking); - - // fastmove (if reordered) - if(bReorderFastMove) - { - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, bFastMoveBeforeBlocking); - } - - // copy/move - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, false); - - // delete - spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); - AddSubTask(spOperation, false); - - break; - } - - default: - throw TCoreException(eErr_UndefinedOperation, L"Operation type not known to the engine", LOCATION); - } - } - - void TSubTasksArray::ResetProgressAndStats() - { - m_oidSubOperationIndex.store(0, std::memory_order_release); - - for (const std::pair& tupleRow : m_vSubTasks) - { - if (tupleRow.first == nullptr) - throw TCoreException(eErr_InternalProblem, L"SubTask is null", LOCATION); - - tupleRow.first->Reset(); - } - } - - void TSubTasksArray::InitBeforeExec() - { - object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); - object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - - if(oidIndex < oidSize) - { - std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); - TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; - - spCurrentSubTask->InitBeforeExec(); - } - } - - TSubTaskBase::ESubOperationResult TSubTasksArray::Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks) - { - TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; - - object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); - object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - - while (oidIndex < oidSize) - { - std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); - TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; - - spCurrentSubTask->InitBeforeExec(); - - // if we run in estimation mode only, then stop processing and return to the caller - if (bRunOnlyEstimationSubTasks && !rCurrentSubTask.second) - { - eResult = TSubTaskBase::eSubResult_Continue; - break; - } - - eResult = spCurrentSubTask->Exec(spFeedbackHandler); - if (eResult != TSubTaskBase::eSubResult_Continue) - break; - - oidIndex = m_oidSubOperationIndex.fetch_add(1, std::memory_order_release) + 1; - } - - return eResult; - } - - bool TSubTasksArray::AreAllBasePathsProcessed() const - { - return m_rSubTaskContext.GetBasePaths()->AllMarkedAsSkipFurtherProcessing(); - } - - void TSubTasksArray::AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation) - { - m_vSubTasks.push_back(std::make_pair(spOperation, bIsPartOfEstimation)); - } - - void TSubTasksArray::GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const - { - rSnapshot.Clear(); - - // current task - // ugly const_cast - const method, non-const interlocked intrinsic and we're really not modifying the member... - object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - rSnapshot.SetCurrentSubtaskIndex(oidIndex); - - // progress - for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) - { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; - TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; - - TSubTaskStatsSnapshotPtr spSubtaskSnapshot(new TSubTaskStatsSnapshot); - - spCurrentSubTask->GetStatsSnapshot(spSubtaskSnapshot); - rSnapshot.AddSubTaskSnapshot(spSubtaskSnapshot); - } - } - - EOperationType TSubTasksArray::GetOperationType() const - { - return m_eOperationType; - } - - void TSubTasksArray::Store(const ISerializerPtr& spSerializer) const - { - bool bAdded = m_setModifications[eMod_Added]; - - /////////////////////////////////////////////////////////////////////// - if (m_eOperationType.IsModified()) - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); - InitSubtasksInfoColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - - rRow.SetValue(_T("operation"), m_eOperationType.Get()); - } - - /////////////////////////////////////////////////////////////////////// - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); - InitSubtasksColumns(spContainer); - - // base data - object_id_t oidCurrentIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); - - // subtasks are stored only once when added as they don't change (at least in context of their order and type) - if (bAdded) - { - if (m_oidLastStoredIndex != -1) - throw TCoreException(eErr_InternalProblem, L"Last object id is set when array is marked as added", LOCATION); - - for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) - { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; - - ISerializerRowData& rRow = spContainer->GetRow(boost::numeric_cast(stSubOperationIndex), bAdded); - rRow.SetValue(_T("type"), rCurrentSubTask.first->GetSubOperationType()); - rRow.SetValue(_T("is_current"), false); - rRow.SetValue(_T("is_estimation"), rCurrentSubTask.second); - } - } - - // serialize current index - if (bAdded || oidCurrentIndex != m_oidLastStoredIndex) - { - // mark subtask at current index as "current"; don't do that if we just finished. - if (boost::numeric_cast(oidCurrentIndex) != m_vSubTasks.size()) - { - ISerializerRowData& rRow = spContainer->GetRow(oidCurrentIndex, false); - rRow.SetValue(_T("is_current"), true); - } - - // unmark the old "current" subtask - if (m_oidLastStoredIndex != -1 && m_oidLastStoredIndex != m_vSubTasks.size()) - { - ISerializerRowData& rRow = spContainer->GetRow(m_oidLastStoredIndex, false); - rRow.SetValue(_T("is_current"), false); - } - } - - m_oidLastStoredIndex = oidCurrentIndex; - } - - m_setModifications.reset(); - - /////////////////////////////////////////////////////////////////////// - // store all the subtasks - for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) - { - const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; - rCurrentSubTask.first->Store(spSerializer); - } - } - - void TSubTasksArray::Load(const ISerializerPtr& spSerializer) - { - /////////////////////////////////////////////////////////////////////// - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); - - InitSubtasksInfoColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) - spRowReader->GetValue(_T("operation"), *(int*)&m_eOperationType.Modify()); - } - - /////////////////////////////////////////////////////////////////////// - { - m_oidLastStoredIndex = (object_id_t)-1; - - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - InitSubtasksColumns(spContainer); - - while (spRowReader->Next()) - { - object_id_t oidID = 0; - int iType = 0; - bool bIsCurrent = false; - bool bIsEstimation = false; - - spRowReader->GetValue(_T("id"), oidID); - spRowReader->GetValue(_T("type"), iType); - spRowReader->GetValue(_T("is_current"), bIsCurrent); - spRowReader->GetValue(_T("is_estimation"), bIsEstimation); - - if (bIsCurrent) - { - m_oidSubOperationIndex.store(oidID, std::memory_order_release); - m_oidLastStoredIndex = oidID; - } - - // create subtask, load it and put into the array - TSubTaskBasePtr spSubTask = CreateSubtask((ESubOperationType)iType, m_rSubTaskContext); - spSubTask->Load(spSerializer); - - if (boost::numeric_cast(oidID) != m_vSubTasks.size()) - throw TCoreException(eErr_InvalidData, L"Object id does not match count of subtasks", LOCATION); - - m_vSubTasks.push_back(std::make_pair(spSubTask, bIsEstimation)); - } - - if (m_oidLastStoredIndex == -1) - m_oidSubOperationIndex.store(boost::numeric_cast(m_vSubTasks.size()), std::memory_order_release); - } - - m_setModifications.reset(); - } - - TSubTaskBasePtr TSubTasksArray::CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext) - { - switch (eType) - { - case eSubOperation_FastMove: - return std::make_shared(boost::ref(rContext)); - - case eSubOperation_Scanning: - return std::make_shared(boost::ref(rContext)); - - case eSubOperation_Copying: - return std::make_shared(boost::ref(rContext)); - - case eSubOperation_Deleting: - return std::make_shared(boost::ref(rContext)); - - default: - throw TCoreException(eErr_UnhandledCase, L"SubTask is unknown to the engine", LOCATION); - } - } - - IColumnsDefinition& TSubTasksArray::InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("type"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("is_current"), IColumnsDefinition::eType_bool); - rColumns.AddColumn(_T("is_estimation"), IColumnsDefinition::eType_bool); - } - - return rColumns; - } - - IColumnsDefinition& TSubTasksArray::InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("operation"), IColumnsDefinition::eType_int); - } - - return rColumns; - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskArray.cpp +/// @date 2011/11/08 +/// @brief File contain implementation of a class handling a sequence of subtasks. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskArray.h" +#include "TTaskOperationPlan.h" +#include "TSubTaskScanDirectory.h" +#include "TSubTaskCopyMove.h" +#include "TSubTaskDelete.h" +#include "TSubTaskContext.h" +#include "TTaskLocalStats.h" +#include "TSubTaskFastMove.h" +#include "TTaskStatsSnapshot.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include +#include "TTaskConfiguration.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + // TSubTasksArray + + TSubTasksArray::TSubTasksArray(TSubTaskContext& rSubTaskContext) : + m_rSubTaskContext(rSubTaskContext), + m_eOperationType(m_setModifications, eOperation_None), + m_oidSubOperationIndex(0), + m_oidLastStoredIndex((object_id_t)-1) + { + m_setModifications[eMod_Added] = true; + } + + TSubTasksArray::TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext) : + m_rSubTaskContext(rSubTaskContext), + m_eOperationType(m_setModifications, eOperation_None), + m_oidSubOperationIndex(0), + m_oidLastStoredIndex((object_id_t)-1) + { + m_setModifications[eMod_Added] = true; + Init(rOperationPlan); + } + + TSubTasksArray::~TSubTasksArray() + { + } + + void TSubTasksArray::Init(const TOperationPlan& rOperationPlan) + { + m_vSubTasks.clear(); + m_rSubTaskContext.GetFilesCache().Clear(); + m_oidSubOperationIndex.store(0, std::memory_order_release); + + m_eOperationType = rOperationPlan.GetOperationType(); + + bool bReadTasksSizeBeforeBlocking = GetTaskPropValue(m_rSubTaskContext.GetConfig()); + bool bFastMoveBeforeBlocking = GetTaskPropValue(m_rSubTaskContext.GetConfig()); + + switch (m_eOperationType) + { + case eOperation_Copy: + { + TSubTaskBasePtr spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, bReadTasksSizeBeforeBlocking); + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, false); + + break; + } + + case eOperation_Move: + { + TSubTaskBasePtr spOperation; + bool bReorderFastMove = bReadTasksSizeBeforeBlocking && !bFastMoveBeforeBlocking; + + // fastmove (if not reordered) + if(!bReorderFastMove) + { + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, bFastMoveBeforeBlocking); + } + + // scanning + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, bReadTasksSizeBeforeBlocking); + + // fastmove (if reordered) + if(bReorderFastMove) + { + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, bFastMoveBeforeBlocking); + } + + // copy/move + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, false); + + // delete + spOperation = std::make_shared(boost::ref(m_rSubTaskContext)); + AddSubTask(spOperation, false); + + break; + } + + default: + throw TCoreException(eErr_UndefinedOperation, L"Operation type not known to the engine", LOCATION); + } + } + + void TSubTasksArray::ResetProgressAndStats() + { + m_oidSubOperationIndex.store(0, std::memory_order_release); + + for (const std::pair& tupleRow : m_vSubTasks) + { + if (tupleRow.first == nullptr) + throw TCoreException(eErr_InternalProblem, L"SubTask is null", LOCATION); + + tupleRow.first->Reset(); + } + } + + void TSubTasksArray::InitBeforeExec() + { + object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); + object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + + if(oidIndex < oidSize) + { + std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); + TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; + + spCurrentSubTask->InitBeforeExec(); + } + } + + TSubTaskBase::ESubOperationResult TSubTasksArray::Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks) + { + TSubTaskBase::ESubOperationResult eResult = TSubTaskBase::eSubResult_Continue; + + object_id_t oidSize = boost::numeric_cast(m_vSubTasks.size()); + object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + + while (oidIndex < oidSize) + { + std::pair& rCurrentSubTask = m_vSubTasks.at(boost::numeric_cast(oidIndex)); + TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; + + spCurrentSubTask->InitBeforeExec(); + + // if we run in estimation mode only, then stop processing and return to the caller + if (bRunOnlyEstimationSubTasks && !rCurrentSubTask.second) + { + eResult = TSubTaskBase::eSubResult_Continue; + break; + } + + eResult = spCurrentSubTask->Exec(spFeedbackHandler); + if (eResult != TSubTaskBase::eSubResult_Continue) + break; + + oidIndex = m_oidSubOperationIndex.fetch_add(1, std::memory_order_release) + 1; + } + + return eResult; + } + + bool TSubTasksArray::AreAllBasePathsProcessed() const + { + return m_rSubTaskContext.GetBasePaths()->AllMarkedAsSkipFurtherProcessing(); + } + + void TSubTasksArray::AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation) + { + m_vSubTasks.push_back(std::make_pair(spOperation, bIsPartOfEstimation)); + } + + void TSubTasksArray::GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const + { + rSnapshot.Clear(); + + // current task + // ugly const_cast - const method, non-const interlocked intrinsic and we're really not modifying the member... + object_id_t oidIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + rSnapshot.SetCurrentSubtaskIndex(oidIndex); + + // progress + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + TSubTaskBasePtr spCurrentSubTask = rCurrentSubTask.first; + + TSubTaskStatsSnapshotPtr spSubtaskSnapshot(new TSubTaskStatsSnapshot); + + spCurrentSubTask->GetStatsSnapshot(spSubtaskSnapshot); + rSnapshot.AddSubTaskSnapshot(spSubtaskSnapshot); + } + } + + EOperationType TSubTasksArray::GetOperationType() const + { + return m_eOperationType; + } + + void TSubTasksArray::Store(const ISerializerPtr& spSerializer) const + { + bool bAdded = m_setModifications[eMod_Added]; + + /////////////////////////////////////////////////////////////////////// + if (m_eOperationType.IsModified()) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); + InitSubtasksInfoColumns(spContainer); + + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); + + rRow.SetValue(_T("operation"), m_eOperationType.Get()); + } + + /////////////////////////////////////////////////////////////////////// + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); + InitSubtasksColumns(spContainer); + + // base data + object_id_t oidCurrentIndex = m_oidSubOperationIndex.load(std::memory_order_acquire); + + // subtasks are stored only once when added as they don't change (at least in context of their order and type) + if (bAdded) + { + if (m_oidLastStoredIndex != -1) + throw TCoreException(eErr_InternalProblem, L"Last object id is set when array is marked as added", LOCATION); + + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + + ISerializerRowData& rRow = spContainer->GetRow(boost::numeric_cast(stSubOperationIndex), bAdded); + rRow.SetValue(_T("type"), rCurrentSubTask.first->GetSubOperationType()); + rRow.SetValue(_T("is_current"), false); + rRow.SetValue(_T("is_estimation"), rCurrentSubTask.second); + } + } + + // serialize current index + if (bAdded || oidCurrentIndex != m_oidLastStoredIndex) + { + // mark subtask at current index as "current"; don't do that if we just finished. + if (boost::numeric_cast(oidCurrentIndex) != m_vSubTasks.size()) + { + ISerializerRowData& rRow = spContainer->GetRow(oidCurrentIndex, false); + rRow.SetValue(_T("is_current"), true); + } + + // unmark the old "current" subtask + if (m_oidLastStoredIndex != -1 && m_oidLastStoredIndex != m_vSubTasks.size()) + { + ISerializerRowData& rRow = spContainer->GetRow(m_oidLastStoredIndex, false); + rRow.SetValue(_T("is_current"), false); + } + } + + m_oidLastStoredIndex = oidCurrentIndex; + } + + m_setModifications.reset(); + + /////////////////////////////////////////////////////////////////////// + // store all the subtasks + for (size_t stSubOperationIndex = 0; stSubOperationIndex < m_vSubTasks.size(); ++stSubOperationIndex) + { + const std::pair& rCurrentSubTask = m_vSubTasks[stSubOperationIndex]; + rCurrentSubTask.first->Store(spSerializer); + } + } + + void TSubTasksArray::Load(const ISerializerPtr& spSerializer) + { + /////////////////////////////////////////////////////////////////////// + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks_info")); + + InitSubtasksInfoColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + spRowReader->GetValue(_T("operation"), *(int*)&m_eOperationType.Modify()); + } + + /////////////////////////////////////////////////////////////////////// + { + m_oidLastStoredIndex = (object_id_t)-1; + + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtasks")); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + InitSubtasksColumns(spContainer); + + while (spRowReader->Next()) + { + object_id_t oidID = 0; + int iType = 0; + bool bIsCurrent = false; + bool bIsEstimation = false; + + spRowReader->GetValue(_T("id"), oidID); + spRowReader->GetValue(_T("type"), iType); + spRowReader->GetValue(_T("is_current"), bIsCurrent); + spRowReader->GetValue(_T("is_estimation"), bIsEstimation); + + if (bIsCurrent) + { + m_oidSubOperationIndex.store(oidID, std::memory_order_release); + m_oidLastStoredIndex = oidID; + } + + // create subtask, load it and put into the array + TSubTaskBasePtr spSubTask = CreateSubtask((ESubOperationType)iType, m_rSubTaskContext); + spSubTask->Load(spSerializer); + + if (boost::numeric_cast(oidID) != m_vSubTasks.size()) + throw TCoreException(eErr_InvalidData, L"Object id does not match count of subtasks", LOCATION); + + m_vSubTasks.push_back(std::make_pair(spSubTask, bIsEstimation)); + } + + if (m_oidLastStoredIndex == -1) + m_oidSubOperationIndex.store(boost::numeric_cast(m_vSubTasks.size()), std::memory_order_release); + } + + m_setModifications.reset(); + } + + TSubTaskBasePtr TSubTasksArray::CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext) + { + switch (eType) + { + case eSubOperation_FastMove: + return std::make_shared(boost::ref(rContext)); + + case eSubOperation_Scanning: + return std::make_shared(boost::ref(rContext)); + + case eSubOperation_Copying: + return std::make_shared(boost::ref(rContext)); + + case eSubOperation_Deleting: + return std::make_shared(boost::ref(rContext)); + + default: + throw TCoreException(eErr_UnhandledCase, L"SubTask is unknown to the engine", LOCATION); + } + } + + IColumnsDefinition& TSubTasksArray::InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("type"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("is_current"), IColumnsDefinition::eType_bool); + rColumns.AddColumn(_T("is_estimation"), IColumnsDefinition::eType_bool); + } + + return rColumns; + } + + IColumnsDefinition& TSubTasksArray::InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("operation"), IColumnsDefinition::eType_int); + } + + return rColumns; + } +} Index: src/libchcore/TSubTaskArray.h =================================================================== diff -u -rcb4e9d4b60d62b25ae2cf556c0642601af56c787 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskArray.h (.../TSubTaskArray.h) (revision cb4e9d4b60d62b25ae2cf556c0642601af56c787) +++ src/libchcore/TSubTaskArray.h (.../TSubTaskArray.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,108 +1,108 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskArray.h -/// @date 2011/11/08 -/// @brief File contain definition of a class handling a sequence of subtasks. -// ============================================================================ -#ifndef __TSUBTASKSARRAY_H__ -#define __TSUBTASKSARRAY_H__ - -#include "libchcore.h" -#include -#include "TSubTaskBase.h" -#include "TTaskLocalStats.h" -#include "TSubTaskArrayStatsSnapshot.h" -#include "TSharedModificationTracker.h" -#include -#include - -namespace chcore -{ - class TOperationPlan; - class TSubTaskContext; - - /////////////////////////////////////////////////////////////////////////// - // TTaskBasicProgressInfo - class LIBCHCORE_API TSubTasksArray - { - public: - explicit TSubTasksArray(TSubTaskContext& rSubTaskContext); - TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext); - ~TSubTasksArray(); - - void Init(const TOperationPlan& rOperationPlan); - EOperationType GetOperationType() const; - - // Stats handling - void GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const; - void ResetProgressAndStats(); - - // progress handling - void Store(const ISerializerPtr& spSerializer) const; - void Load(const ISerializerPtr& spSerializer); - - void InitBeforeExec(); - TSubTaskBase::ESubOperationResult Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks); - - // checks if the fast move already marked all base paths as not be be further processed - bool AreAllBasePathsProcessed() const; - - private: - TSubTasksArray(const TSubTasksArray& rSrc); - TSubTasksArray& operator=(const TSubTasksArray& rSrc); - - void AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation); - static TSubTaskBasePtr CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext); - - IColumnsDefinition& InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const; - IColumnsDefinition& InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const; - - private: - enum EModifications - { - eMod_Added, - eMod_OperationType, - - // last element - eMod_Last - }; - - typedef std::bitset Bitset; - - TSubTaskContext& m_rSubTaskContext; - -#pragma warning(push) -#pragma warning(disable: 4251) - mutable Bitset m_setModifications; - - TSharedModificationTracker m_eOperationType; - - std::vector > m_vSubTasks; // pointer to the subtask object / is this the part of estimation? - - mutable std::atomic m_oidSubOperationIndex; // index of sub-operation from TOperationDescription - -#pragma warning(pop) - - mutable object_id_t m_oidLastStoredIndex; - - friend class TScopedRunningTimeTracker; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskArray.h +/// @date 2011/11/08 +/// @brief File contain definition of a class handling a sequence of subtasks. +// ============================================================================ +#ifndef __TSUBTASKSARRAY_H__ +#define __TSUBTASKSARRAY_H__ + +#include "libchcore.h" +#include +#include "TSubTaskBase.h" +#include "TTaskLocalStats.h" +#include "TSubTaskArrayStatsSnapshot.h" +#include "TSharedModificationTracker.h" +#include +#include + +namespace chcore +{ + class TOperationPlan; + class TSubTaskContext; + + /////////////////////////////////////////////////////////////////////////// + // TTaskBasicProgressInfo + class LIBCHCORE_API TSubTasksArray + { + public: + explicit TSubTasksArray(TSubTaskContext& rSubTaskContext); + TSubTasksArray(const TOperationPlan& rOperationPlan, TSubTaskContext& rSubTaskContext); + ~TSubTasksArray(); + + void Init(const TOperationPlan& rOperationPlan); + EOperationType GetOperationType() const; + + // Stats handling + void GetStatsSnapshot(TSubTaskArrayStatsSnapshot& rSnapshot) const; + void ResetProgressAndStats(); + + // progress handling + void Store(const ISerializerPtr& spSerializer) const; + void Load(const ISerializerPtr& spSerializer); + + void InitBeforeExec(); + TSubTaskBase::ESubOperationResult Execute(const IFeedbackHandlerPtr& spFeedbackHandler, bool bRunOnlyEstimationSubTasks); + + // checks if the fast move already marked all base paths as not be be further processed + bool AreAllBasePathsProcessed() const; + + private: + TSubTasksArray(const TSubTasksArray& rSrc); + TSubTasksArray& operator=(const TSubTasksArray& rSrc); + + void AddSubTask(const TSubTaskBasePtr& spOperation, bool bIsPartOfEstimation); + static TSubTaskBasePtr CreateSubtask(ESubOperationType eType, TSubTaskContext& rContext); + + IColumnsDefinition& InitSubtasksColumns(const ISerializerContainerPtr& spContainer) const; + IColumnsDefinition& InitSubtasksInfoColumns(const ISerializerContainerPtr& spContainer) const; + + private: + enum EModifications + { + eMod_Added, + eMod_OperationType, + + // last element + eMod_Last + }; + + typedef std::bitset Bitset; + + TSubTaskContext& m_rSubTaskContext; + +#pragma warning(push) +#pragma warning(disable: 4251) + mutable Bitset m_setModifications; + + TSharedModificationTracker m_eOperationType; + + std::vector > m_vSubTasks; // pointer to the subtask object / is this the part of estimation? + + mutable std::atomic m_oidSubOperationIndex; // index of sub-operation from TOperationDescription + +#pragma warning(pop) + + mutable object_id_t m_oidLastStoredIndex; + + friend class TScopedRunningTimeTracker; + }; +} + +#endif Index: src/libchcore/TSubTaskArrayStatsSnapshot.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskArrayStatsSnapshot.cpp (.../TSubTaskArrayStatsSnapshot.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSubTaskArrayStatsSnapshot.cpp (.../TSubTaskArrayStatsSnapshot.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,62 +1,62 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskArrayStatsSnapshot.h" -#include "ErrorCodes.h" -#include "TCoreException.h" -#include - -namespace chcore -{ - TSubTaskArrayStatsSnapshot::TSubTaskArrayStatsSnapshot() : - m_oidCurrentSubtaskIndex(0) - { - } - - void TSubTaskArrayStatsSnapshot::Clear() - { - m_vSubTaskSnapshots.clear(); - } - - void TSubTaskArrayStatsSnapshot::AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& spSnapshot) - { - m_vSubTaskSnapshots.push_back(spSnapshot); - } - - TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotAt(size_t stIndex) const - { - if (stIndex >= m_vSubTaskSnapshots.size()) - return TSubTaskStatsSnapshotPtr(); - - return m_vSubTaskSnapshots[stIndex]; - } - - TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetCurrentSubTaskSnapshot() const - { - if (m_oidCurrentSubtaskIndex >= m_vSubTaskSnapshots.size()) - return TSubTaskStatsSnapshotPtr(); - - return m_vSubTaskSnapshots[boost::numeric_cast(m_oidCurrentSubtaskIndex)]; - } - - size_t TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotCount() const - { - return m_vSubTaskSnapshots.size(); - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskArrayStatsSnapshot.h" +#include "ErrorCodes.h" +#include "TCoreException.h" +#include + +namespace chcore +{ + TSubTaskArrayStatsSnapshot::TSubTaskArrayStatsSnapshot() : + m_oidCurrentSubtaskIndex(0) + { + } + + void TSubTaskArrayStatsSnapshot::Clear() + { + m_vSubTaskSnapshots.clear(); + } + + void TSubTaskArrayStatsSnapshot::AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& spSnapshot) + { + m_vSubTaskSnapshots.push_back(spSnapshot); + } + + TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotAt(size_t stIndex) const + { + if (stIndex >= m_vSubTaskSnapshots.size()) + return TSubTaskStatsSnapshotPtr(); + + return m_vSubTaskSnapshots[stIndex]; + } + + TSubTaskStatsSnapshotPtr TSubTaskArrayStatsSnapshot::GetCurrentSubTaskSnapshot() const + { + if (m_oidCurrentSubtaskIndex >= m_vSubTaskSnapshots.size()) + return TSubTaskStatsSnapshotPtr(); + + return m_vSubTaskSnapshots[boost::numeric_cast(m_oidCurrentSubtaskIndex)]; + } + + size_t TSubTaskArrayStatsSnapshot::GetSubTaskSnapshotCount() const + { + return m_vSubTaskSnapshots.size(); + } +} Index: src/libchcore/TSubTaskArrayStatsSnapshot.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskArrayStatsSnapshot.h (.../TSubTaskArrayStatsSnapshot.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TSubTaskArrayStatsSnapshot.h (.../TSubTaskArrayStatsSnapshot.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TSUBTASKARRAYSTATSSNAPSHOT_H__ -#define __TSUBTASKARRAYSTATSSNAPSHOT_H__ - -#include "libchcore.h" -#include "TSubTaskStatsSnapshot.h" -#include "SerializerDataTypes.h" - -namespace chcore -{ - class LIBCHCORE_API TSubTaskArrayStatsSnapshot - { - public: - TSubTaskArrayStatsSnapshot(); - - void Clear(); - - void AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& rSnapshot); - TSubTaskStatsSnapshotPtr GetSubTaskSnapshotAt(size_t stIndex) const; - size_t GetSubTaskSnapshotCount() const; - TSubTaskStatsSnapshotPtr GetCurrentSubTaskSnapshot() const; - - object_id_t GetCurrentSubtaskIndex() const { return m_oidCurrentSubtaskIndex; } - void SetCurrentSubtaskIndex(object_id_t val) { m_oidCurrentSubtaskIndex = val; } - - private: - object_id_t m_oidCurrentSubtaskIndex; -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vSubTaskSnapshots; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TSUBTASKARRAYSTATSSNAPSHOT_H__ +#define __TSUBTASKARRAYSTATSSNAPSHOT_H__ + +#include "libchcore.h" +#include "TSubTaskStatsSnapshot.h" +#include "SerializerDataTypes.h" + +namespace chcore +{ + class LIBCHCORE_API TSubTaskArrayStatsSnapshot + { + public: + TSubTaskArrayStatsSnapshot(); + + void Clear(); + + void AddSubTaskSnapshot(const TSubTaskStatsSnapshotPtr& rSnapshot); + TSubTaskStatsSnapshotPtr GetSubTaskSnapshotAt(size_t stIndex) const; + size_t GetSubTaskSnapshotCount() const; + TSubTaskStatsSnapshotPtr GetCurrentSubTaskSnapshot() const; + + object_id_t GetCurrentSubtaskIndex() const { return m_oidCurrentSubtaskIndex; } + void SetCurrentSubtaskIndex(object_id_t val) { m_oidCurrentSubtaskIndex = val; } + + private: + object_id_t m_oidCurrentSubtaskIndex; +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vSubTaskSnapshots; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskBase.cpp =================================================================== diff -u -r7ba9f25ab2c2a42bac9f5455ecb98aaf6e29f02d -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskBase.cpp (.../TSubTaskBase.cpp) (revision 7ba9f25ab2c2a42bac9f5455ecb98aaf6e29f02d) +++ src/libchcore/TSubTaskBase.cpp (.../TSubTaskBase.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,46 +1,46 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskBase.cpp -/// @date 2010/09/19 -/// @brief Contains implementation of some common subtask elements. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskBase.h" -#include "TBasePathData.h" -#include "TSubTaskContext.h" -#include "TTaskConfiguration.h" -#include -#include "TFileInfo.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - // TSubTaskBase - - TSubTaskBase::TSubTaskBase(TSubTaskContext& rContext) : - m_rContext(rContext) - { - } - - TSubTaskBase::~TSubTaskBase() - { - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskBase.cpp +/// @date 2010/09/19 +/// @brief Contains implementation of some common subtask elements. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskBase.h" +#include "TBasePathData.h" +#include "TSubTaskContext.h" +#include "TTaskConfiguration.h" +#include +#include "TFileInfo.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + // TSubTaskBase + + TSubTaskBase::TSubTaskBase(TSubTaskContext& rContext) : + m_rContext(rContext) + { + } + + TSubTaskBase::~TSubTaskBase() + { + } +} Index: src/libchcore/TSubTaskBase.h =================================================================== diff -u -rc0d9a798f9fbbeda239b84721ed864f9727e1ddc -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskBase.h (.../TSubTaskBase.h) (revision c0d9a798f9fbbeda239b84721ed864f9727e1ddc) +++ src/libchcore/TSubTaskBase.h (.../TSubTaskBase.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,88 +1,88 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskBase.h -/// @date 2010/09/18 -/// @brief Contains declarations of common elements of sub-operations. -// ============================================================================ -#ifndef __TSUBTASKBASE_H__ -#define __TSUBTASKBASE_H__ - -#include "libchcore.h" -#include "ESubTaskTypes.h" -#include "TSubTaskStatsInfo.h" -#include "ISerializer.h" -#include "IFeedbackHandler.h" - -namespace chcore -{ - class TSubTaskContext; - class TFileInfo; - typedef std::shared_ptr TFileInfoPtr; - - /////////////////////////////////////////////////////////////////////////// - // TSubTaskBase - - class LIBCHCORE_API TSubTaskBase - { - public: - enum ESubOperationResult - { - eSubResult_Continue, - eSubResult_KillRequest, - eSubResult_Error, - eSubResult_CancelRequest, - eSubResult_PauseRequest, - eSubResult_Retry, - eSubResult_SkipFile - }; - - public: - explicit TSubTaskBase(TSubTaskContext& rContext); - virtual ~TSubTaskBase(); - - virtual void Reset() = 0; - - virtual void InitBeforeExec() = 0; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) = 0; - virtual ESubOperationType GetSubOperationType() const = 0; - - // serialization - virtual void Store(const ISerializerPtr& spSerializer) const = 0; - virtual void Load(const ISerializerPtr& spSerializer) = 0; - - // stats - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const = 0; - - protected: - // some common operations - TSubTaskContext& GetContext() { return m_rContext; } - const TSubTaskContext& GetContext() const { return m_rContext; } - - private: - TSubTaskBase(const TSubTaskBase&); - TSubTaskBase& operator=(const TSubTaskBase&); - - private: - TSubTaskContext& m_rContext; - }; - - typedef std::shared_ptr TSubTaskBasePtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskBase.h +/// @date 2010/09/18 +/// @brief Contains declarations of common elements of sub-operations. +// ============================================================================ +#ifndef __TSUBTASKBASE_H__ +#define __TSUBTASKBASE_H__ + +#include "libchcore.h" +#include "ESubTaskTypes.h" +#include "TSubTaskStatsInfo.h" +#include "ISerializer.h" +#include "IFeedbackHandler.h" + +namespace chcore +{ + class TSubTaskContext; + class TFileInfo; + typedef std::shared_ptr TFileInfoPtr; + + /////////////////////////////////////////////////////////////////////////// + // TSubTaskBase + + class LIBCHCORE_API TSubTaskBase + { + public: + enum ESubOperationResult + { + eSubResult_Continue, + eSubResult_KillRequest, + eSubResult_Error, + eSubResult_CancelRequest, + eSubResult_PauseRequest, + eSubResult_Retry, + eSubResult_SkipFile + }; + + public: + explicit TSubTaskBase(TSubTaskContext& rContext); + virtual ~TSubTaskBase(); + + virtual void Reset() = 0; + + virtual void InitBeforeExec() = 0; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) = 0; + virtual ESubOperationType GetSubOperationType() const = 0; + + // serialization + virtual void Store(const ISerializerPtr& spSerializer) const = 0; + virtual void Load(const ISerializerPtr& spSerializer) = 0; + + // stats + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const = 0; + + protected: + // some common operations + TSubTaskContext& GetContext() { return m_rContext; } + const TSubTaskContext& GetContext() const { return m_rContext; } + + private: + TSubTaskBase(const TSubTaskBase&); + TSubTaskBase& operator=(const TSubTaskBase&); + + private: + TSubTaskContext& m_rContext; + }; + + typedef std::shared_ptr TSubTaskBasePtr; +} + +#endif Index: src/libchcore/TSubTaskContext.cpp =================================================================== diff -u -r12b36349f6214befeace08efa9acc7e03be0d847 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskContext.cpp (.../TSubTaskContext.cpp) (revision 12b36349f6214befeace08efa9acc7e03be0d847) +++ src/libchcore/TSubTaskContext.cpp (.../TSubTaskContext.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,134 +1,134 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskContext.cpp -/// @date 2010/09/19 -/// @brief Contains implementation of classes related to subtask context. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskContext.h" -#include "ErrorCodes.h" -#include "TCoreException.h" -#include "TFileFiltersArray.h" - -namespace chcore -{ - TSubTaskContext::TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, - const TFileFiltersArray& rFilters, - TTaskConfigTracker& rCfgTracker, const logger::TLogFileDataPtr& spLogFileData, - TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : - m_rConfig(rConfig), - m_eOperationType(eOperation_None), - m_spBasePaths(spBasePaths), - m_pathDestination(), - m_rCfgTracker(rCfgTracker), - m_spLogFileData(spLogFileData), - m_rThreadController(rThreadController), - m_spFilesystem(spFilesystem), - m_rFilters(rFilters) - { - if (!spFilesystem) - throw TCoreException(eErr_InvalidArgument, L"spFilesystem", LOCATION); - if (!spLogFileData) - throw TCoreException(eErr_InvalidArgument, L"spLogFileData", LOCATION); - } - - TSubTaskContext::~TSubTaskContext() - { - } - - TConfig& TSubTaskContext::GetConfig() - { - return m_rConfig; - } - - const TConfig& TSubTaskContext::GetConfig() const - { - return m_rConfig; - } - - EOperationType TSubTaskContext::GetOperationType() const - { - return m_eOperationType; - } - - void TSubTaskContext::SetOperationType(EOperationType eOperationType) - { - m_eOperationType = eOperationType; - } - - TBasePathDataContainerPtr TSubTaskContext::GetBasePaths() const - { - return m_spBasePaths; - } - - TFileInfoArray& TSubTaskContext::GetFilesCache() - { - return m_tFilesCache; - } - - const TFileInfoArray& TSubTaskContext::GetFilesCache() const - { - return m_tFilesCache; - } - - TSmartPath TSubTaskContext::GetDestinationPath() const - { - return m_pathDestination; - } - - void TSubTaskContext::SetDestinationPath(const TSmartPath& pathDestination) - { - m_pathDestination = pathDestination; - } - - TTaskConfigTracker& TSubTaskContext::GetCfgTracker() - { - return m_rCfgTracker; - } - - const TTaskConfigTracker& TSubTaskContext::GetCfgTracker() const - { - return m_rCfgTracker; - } - - logger::TLogFileDataPtr TSubTaskContext::GetLogFileData() const - { - return m_spLogFileData; - } - - TWorkerThreadController& TSubTaskContext::GetThreadController() - { - return m_rThreadController; - } - - const TWorkerThreadController& TSubTaskContext::GetThreadController() const - { - return m_rThreadController; - } - - IFilesystemPtr TSubTaskContext::GetLocalFilesystem() const - { - return m_spFilesystem; - } - - const TFileFiltersArray& TSubTaskContext::GetFilters() const - { - return m_rFilters; - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskContext.cpp +/// @date 2010/09/19 +/// @brief Contains implementation of classes related to subtask context. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskContext.h" +#include "ErrorCodes.h" +#include "TCoreException.h" +#include "TFileFiltersArray.h" + +namespace chcore +{ + TSubTaskContext::TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, + const TFileFiltersArray& rFilters, + TTaskConfigTracker& rCfgTracker, const logger::TLogFileDataPtr& spLogFileData, + TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem) : + m_rConfig(rConfig), + m_eOperationType(eOperation_None), + m_spBasePaths(spBasePaths), + m_pathDestination(), + m_rCfgTracker(rCfgTracker), + m_spLogFileData(spLogFileData), + m_rThreadController(rThreadController), + m_spFilesystem(spFilesystem), + m_rFilters(rFilters) + { + if (!spFilesystem) + throw TCoreException(eErr_InvalidArgument, L"spFilesystem", LOCATION); + if (!spLogFileData) + throw TCoreException(eErr_InvalidArgument, L"spLogFileData", LOCATION); + } + + TSubTaskContext::~TSubTaskContext() + { + } + + TConfig& TSubTaskContext::GetConfig() + { + return m_rConfig; + } + + const TConfig& TSubTaskContext::GetConfig() const + { + return m_rConfig; + } + + EOperationType TSubTaskContext::GetOperationType() const + { + return m_eOperationType; + } + + void TSubTaskContext::SetOperationType(EOperationType eOperationType) + { + m_eOperationType = eOperationType; + } + + TBasePathDataContainerPtr TSubTaskContext::GetBasePaths() const + { + return m_spBasePaths; + } + + TFileInfoArray& TSubTaskContext::GetFilesCache() + { + return m_tFilesCache; + } + + const TFileInfoArray& TSubTaskContext::GetFilesCache() const + { + return m_tFilesCache; + } + + TSmartPath TSubTaskContext::GetDestinationPath() const + { + return m_pathDestination; + } + + void TSubTaskContext::SetDestinationPath(const TSmartPath& pathDestination) + { + m_pathDestination = pathDestination; + } + + TTaskConfigTracker& TSubTaskContext::GetCfgTracker() + { + return m_rCfgTracker; + } + + const TTaskConfigTracker& TSubTaskContext::GetCfgTracker() const + { + return m_rCfgTracker; + } + + logger::TLogFileDataPtr TSubTaskContext::GetLogFileData() const + { + return m_spLogFileData; + } + + TWorkerThreadController& TSubTaskContext::GetThreadController() + { + return m_rThreadController; + } + + const TWorkerThreadController& TSubTaskContext::GetThreadController() const + { + return m_rThreadController; + } + + IFilesystemPtr TSubTaskContext::GetLocalFilesystem() const + { + return m_spFilesystem; + } + + const TFileFiltersArray& TSubTaskContext::GetFilters() const + { + return m_rFilters; + } +} Index: src/libchcore/TSubTaskContext.h =================================================================== diff -u -r12b36349f6214befeace08efa9acc7e03be0d847 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskContext.h (.../TSubTaskContext.h) (revision 12b36349f6214befeace08efa9acc7e03be0d847) +++ src/libchcore/TSubTaskContext.h (.../TSubTaskContext.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,115 +1,115 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskContext.h -/// @date 2010/09/19 -/// @brief Contains declaration of subtask context class. -// ============================================================================ -#ifndef __TSUBTASKCONTEXT_H__ -#define __TSUBTASKCONTEXT_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "EOperationTypes.h" -#include "TBasePathData.h" -#include "TFileInfoArray.h" -#include "IFilesystem.h" -#include "..\liblogger\TLogFileData.h" - -namespace chcore -{ - class TWorkerThreadController; - class TTaskConfigTracker; - class TConfig; - class TFileFiltersArray; - - /////////////////////////////////////////////////////////////////////////// - // TSubTaskContext - - class LIBCHCORE_API TSubTaskContext - { - public: - TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, - const TFileFiltersArray& rFilters, - TTaskConfigTracker& rCfgTracker, const logger::TLogFileDataPtr& spLogFileData, - TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem); - ~TSubTaskContext(); - - TConfig& GetConfig(); - const TConfig& GetConfig() const; - - EOperationType GetOperationType() const; - void SetOperationType(EOperationType eOperationType); - - TBasePathDataContainerPtr GetBasePaths() const; - - const TFileFiltersArray& GetFilters() const; - TFileInfoArray& GetFilesCache(); - const TFileInfoArray& GetFilesCache() const; - - TSmartPath GetDestinationPath() const; - void SetDestinationPath(const TSmartPath& pathDestination); - - TTaskConfigTracker& GetCfgTracker(); - const TTaskConfigTracker& GetCfgTracker() const; - - logger::TLogFileDataPtr GetLogFileData() const; - - TWorkerThreadController& GetThreadController(); - const TWorkerThreadController& GetThreadController() const; - - IFilesystemPtr GetLocalFilesystem() const; - - private: - TSubTaskContext(const TSubTaskContext& rSrc); - TSubTaskContext& operator=(const TSubTaskContext& rSrc); - - private: - TConfig& m_rConfig; - - EOperationType m_eOperationType; - - // information about input paths -#pragma warning(push) -#pragma warning(disable: 4251) - TBasePathDataContainerPtr m_spBasePaths; -#pragma warning(pop) - - const TFileFiltersArray& m_rFilters; - - // data on which to operate - TFileInfoArray m_tFilesCache; - - TSmartPath m_pathDestination; - - // configuration changes tracking - TTaskConfigTracker& m_rCfgTracker; - - // local filesystem access functions -#pragma warning(push) -#pragma warning(disable: 4251) - IFilesystemPtr m_spFilesystem; - logger::TLogFileDataPtr m_spLogFileData; -#pragma warning(pop) - - // thread control - TWorkerThreadController& m_rThreadController; - }; -} - -#endif // __TSUBTASKCONTEXT_H__ +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskContext.h +/// @date 2010/09/19 +/// @brief Contains declaration of subtask context class. +// ============================================================================ +#ifndef __TSUBTASKCONTEXT_H__ +#define __TSUBTASKCONTEXT_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "EOperationTypes.h" +#include "TBasePathData.h" +#include "TFileInfoArray.h" +#include "IFilesystem.h" +#include "..\liblogger\TLogFileData.h" + +namespace chcore +{ + class TWorkerThreadController; + class TTaskConfigTracker; + class TConfig; + class TFileFiltersArray; + + /////////////////////////////////////////////////////////////////////////// + // TSubTaskContext + + class LIBCHCORE_API TSubTaskContext + { + public: + TSubTaskContext(TConfig& rConfig, const TBasePathDataContainerPtr& spBasePaths, + const TFileFiltersArray& rFilters, + TTaskConfigTracker& rCfgTracker, const logger::TLogFileDataPtr& spLogFileData, + TWorkerThreadController& rThreadController, const IFilesystemPtr& spFilesystem); + ~TSubTaskContext(); + + TConfig& GetConfig(); + const TConfig& GetConfig() const; + + EOperationType GetOperationType() const; + void SetOperationType(EOperationType eOperationType); + + TBasePathDataContainerPtr GetBasePaths() const; + + const TFileFiltersArray& GetFilters() const; + TFileInfoArray& GetFilesCache(); + const TFileInfoArray& GetFilesCache() const; + + TSmartPath GetDestinationPath() const; + void SetDestinationPath(const TSmartPath& pathDestination); + + TTaskConfigTracker& GetCfgTracker(); + const TTaskConfigTracker& GetCfgTracker() const; + + logger::TLogFileDataPtr GetLogFileData() const; + + TWorkerThreadController& GetThreadController(); + const TWorkerThreadController& GetThreadController() const; + + IFilesystemPtr GetLocalFilesystem() const; + + private: + TSubTaskContext(const TSubTaskContext& rSrc); + TSubTaskContext& operator=(const TSubTaskContext& rSrc); + + private: + TConfig& m_rConfig; + + EOperationType m_eOperationType; + + // information about input paths +#pragma warning(push) +#pragma warning(disable: 4251) + TBasePathDataContainerPtr m_spBasePaths; +#pragma warning(pop) + + const TFileFiltersArray& m_rFilters; + + // data on which to operate + TFileInfoArray m_tFilesCache; + + TSmartPath m_pathDestination; + + // configuration changes tracking + TTaskConfigTracker& m_rCfgTracker; + + // local filesystem access functions +#pragma warning(push) +#pragma warning(disable: 4251) + IFilesystemPtr m_spFilesystem; + logger::TLogFileDataPtr m_spLogFileData; +#pragma warning(pop) + + // thread control + TWorkerThreadController& m_rThreadController; + }; +} + +#endif // __TSUBTASKCONTEXT_H__ Index: src/libchcore/TSubTaskCopyMove.cpp =================================================================== diff -u -rb0a003dc39e6d21e34779cf1cf5d8a07318c1f5f -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskCopyMove.cpp (.../TSubTaskCopyMove.cpp) (revision b0a003dc39e6d21e34779cf1cf5d8a07318c1f5f) +++ src/libchcore/TSubTaskCopyMove.cpp (.../TSubTaskCopyMove.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,455 +1,455 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskCopyMove.cpp -/// @date 2010/09/19 -/// @brief Contains implementations of classes responsible for copy and move sub-operation. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskCopyMove.h" -#include "TSubTaskContext.h" -#include "TTaskConfiguration.h" -#include "TTaskLocalStats.h" -#include "TTaskConfigTracker.h" -#include "TWorkerThreadController.h" -#include "IFeedbackHandler.h" -#include -#include "TBasePathData.h" -#include "TFileInfo.h" -#include "TFileInfoArray.h" -#include "ErrorCodes.h" -#include "TCoreException.h" -#include "TPathContainer.h" -#include "TScopedRunningTimeTracker.h" -#include "TFeedbackHandlerWrapper.h" -#include "TOverlappedMemoryPool.h" -#include "RoundingFunctions.h" -#include "TTaskConfigBufferSizes.h" -#include "TFileException.h" -#include "TFilesystemFeedbackWrapper.h" -#include "TFilesystemFileFeedbackWrapper.h" -#include "TDestinationPathProvider.h" -#include "TOverlappedReaderWriterFB.h" -#include "TThreadedQueueRunner.h" -#include "TOverlappedThreadPool.h" - -namespace chcore -{ - struct CUSTOM_COPY_PARAMS - { - CUSTOM_COPY_PARAMS() : - spMemoryPool(std::make_shared()) - { - } - - TFileInfoPtr spSrcFile; // CFileInfo - src file - TSmartPath pathDstFile; // dest path with filename - - TBufferSizes tBufferSizes; - TOverlappedMemoryPoolPtr spMemoryPool; // buffer handling - bool bOnlyCreate = false; // flag from configuration - skips real copying - only create - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // class TSubTaskCopyMove - - TSubTaskCopyMove::TSubTaskCopyMove(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_spSubTaskStats(std::make_shared(eSubOperation_Copying)), - m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-CopyMove")) - { - } - - void TSubTaskCopyMove::Reset() - { - m_spSubTaskStats->Clear(); - } - - void TSubTaskCopyMove::InitBeforeExec() - { - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - - file_count_t fcCount = rFilesCache.GetSize(); - if(fcCount == 0) - { - m_spSubTaskStats->SetCurrentPath(TString()); - return; - } - - file_count_t fcIndex = m_spSubTaskStats->GetCurrentIndex(); - if(fcIndex >= fcCount) - fcIndex = 0; - - TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); - m_spSubTaskStats->SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); - } - - TSubTaskBase::ESubOperationResult TSubTaskCopyMove::Exec(const IFeedbackHandlerPtr& spFeedback) - { - TScopedRunningTimeTracker guard(*m_spSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); - - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - const TConfig& rConfig = GetContext().GetConfig(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - TBasePathDataContainerPtr spSrcPaths = GetContext().GetBasePaths(); - - TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); - - // log - LOG_INFO(m_spLog) << _T("Processing files/folders (ProcessFiles)"); - - // initialize stats if not resuming (when resuming we have already initialized - // the stats once - it is being restored in Load() too). - if (!m_spSubTaskStats->IsInitialized()) - m_spSubTaskStats->Init(TBufferSizes::eBuffer_Default, rFilesCache.GetSize(), 0, rFilesCache.CalculateTotalSize(), rFilesCache.CalculatePartialSize(m_spSubTaskStats->GetCurrentIndex()), TString()); - else - { - _ASSERTE(rFilesCache.GetSize() == m_spSubTaskStats->GetTotalCount()); - if (rFilesCache.GetSize() != m_spSubTaskStats->GetTotalCount()) - throw TCoreException(eErr_InternalProblem, L"Size of files' cache differs from stats information", LOCATION); - } - - // now it's time to check if there is enough space on destination device - unsigned long long ullNeededSize = rFilesCache.CalculateTotalSize() - rFilesCache.CalculatePartialSize(m_spSubTaskStats->GetCurrentIndex()); - TSmartPath pathSingleSrc = spSrcPaths->GetAt(0)->GetSrcPath(); - TSubTaskBase::ESubOperationResult eResult = tFilesystemFBWrapper.CheckForFreeSpaceFB(pathSingleSrc, pathDestination, ullNeededSize); - if(eResult != eSubResult_Continue) - return eResult; - - // begin at index which wasn't processed previously - file_count_t fcSize = rFilesCache.GetSize(); - file_count_t fcIndex = m_spSubTaskStats->GetCurrentIndex(); - unsigned long long ullCurrentItemProcessedSize = m_spSubTaskStats->GetCurrentItemProcessedSize(); - bool bCurrentFileSilentResume = m_spSubTaskStats->CanCurrentItemSilentResume(); - - // create a buffer of size m_nBufferSize - CUSTOM_COPY_PARAMS ccp; - ccp.bOnlyCreate = GetTaskPropValue(rConfig); - - // remove changes in buffer sizes to avoid re-creation later - rCfgTracker.RemoveModificationSet(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth); - - AdjustBufferIfNeeded(ccp.spMemoryPool, ccp.tBufferSizes, true); - - bool bIgnoreFolders = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); - - TDestinationPathProvider tDstPathProvider(spFilesystem, pathDestination, - bIgnoreFolders, bForceDirectories, - GetTaskPropValue(GetContext().GetConfig()), - GetTaskPropValue(GetContext().GetConfig())); - - // log - TString strFormat; - strFormat = _T("Processing files/folders (ProcessFiles):\r\n\tOnlyCreate: %create\r\n\tFiles/folders count: %filecount\r\n\tIgnore Folders: %ignorefolders\r\n\tDest path: %dstpath\r\n\tCurrent index (0-based): %currindex"); - strFormat.Replace(_T("%create"), boost::lexical_cast(ccp.bOnlyCreate).c_str()); - strFormat.Replace(_T("%filecount"), boost::lexical_cast(fcSize).c_str()); - strFormat.Replace(_T("%ignorefolders"), boost::lexical_cast(bIgnoreFolders).c_str()); - strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); - strFormat.Replace(_T("%currindex"), boost::lexical_cast(fcIndex).c_str()); - - LOG_INFO(m_spLog) << strFormat.c_str(); - - TOverlappedThreadPool threadPool(rThreadController.GetKillThreadHandle()); - - for(; fcIndex < fcSize; fcIndex++) - { - // should we kill ? - if(rThreadController.KillRequested()) - { - // log - LOG_INFO(m_spLog) << _T("Kill request while processing file in ProcessFiles"); - return eSubResult_KillRequest; - } - - // next file to be copied - TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); - if(spFileInfo->IsProcessed()) - continue; - - TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); - - // new stats - m_spSubTaskStats->SetCurrentIndex(fcIndex); - m_spSubTaskStats->SetProcessedCount(fcIndex); - m_spSubTaskStats->SetCurrentPath(pathCurrent.ToString()); - m_spSubTaskStats->SetCurrentItemSizes(ullCurrentItemProcessedSize, spFileInfo->GetLength64()); // preserve the processed size for the first item - ullCurrentItemProcessedSize = 0; // in next iteration we're not resuming anymore - m_spSubTaskStats->SetCurrentItemSilentResume(bCurrentFileSilentResume); - bCurrentFileSilentResume = false; - - // if the file was already processed (e.g. by fast-move), just consider the file skipped - if(spFileInfo->IsBasePathProcessed()) - { - AdjustProcessedSizeForSkip(spFileInfo); - spFileInfo->MarkAsProcessed(true); - continue; - } - - // set dest path with filename - ccp.pathDstFile = tDstPathProvider.CalculateDestinationPath(spFileInfo); - - // are the files/folders lie on the same partition ? - bool bMove = GetContext().GetOperationType() == eOperation_Move; - - // if folder - create it - if(spFileInfo->IsDirectory()) - { - eResult = tFilesystemFBWrapper.CreateDirectoryFB(ccp.pathDstFile); - if(eResult != eSubResult_Continue) - return eResult; - - // new stats - AdjustProcessedSizeForSkip(spFileInfo); - - spFileInfo->MarkAsProcessed(true); - } - else - { - // start copying/moving file - ccp.spSrcFile = spFileInfo; - - // copy data - eResult = CustomCopyFileFB(spFeedbackHandler, threadPool, &ccp); - if (eResult == eSubResult_SkipFile) - { - spFileInfo->MarkAsProcessed(false); - AdjustProcessedSizeForSkip(spFileInfo); - } - else if(eResult != eSubResult_Continue) - return eResult; - else - spFileInfo->MarkAsProcessed(true); - - // if moving - delete file (only if config flag is set) - if(bMove && spFileInfo->IsProcessed() && !GetTaskPropValue(rConfig)) - { - tFilesystemFBWrapper.DeleteFileFB(spFileInfo, GetTaskPropValue(rConfig)); - } - } - - // only set attributes and times when file/dir had been processed successfully. - if(spFileInfo->IsProcessed()) - { - if(GetTaskPropValue(rConfig)) - spFilesystem->SetFileDirectoryTime(ccp.pathDstFile, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); // no error checking (but most probably it should be checked) - - // attributes - if(GetTaskPropValue(rConfig)) - spFilesystem->SetAttributes(ccp.pathDstFile, spFileInfo->GetAttributes()); // as above - } - } - - // update directories file times - bool bUpdateDirTimes = GetTaskPropValue(rConfig); - if(bUpdateDirTimes) - { - LOG_INFO(m_spLog) << _T("Setting directory attributes"); - - // iterate backwards - for(file_count_t fcAttrIndex = fcSize; fcAttrIndex != 0; --fcAttrIndex) - { - // should we kill ? - if(rThreadController.KillRequested()) - { - // log - LOG_INFO(m_spLog) << _T("Kill request while processing file in ProcessFiles"); - return eSubResult_KillRequest; - } - - TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcAttrIndex - 1); - if(spFileInfo->IsDirectory()) - { - TSmartPath pathDstDir = tDstPathProvider.CalculateDestinationPath(spFileInfo); - - spFilesystem->SetFileDirectoryTime(pathDstDir, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); - } - } - } - - // stats - m_spSubTaskStats->SetCurrentIndex(fcIndex); - m_spSubTaskStats->SetProcessedCount(fcIndex); - m_spSubTaskStats->SetCurrentPath(TString()); - - // log - LOG_INFO(m_spLog) << _T("Finished processing in ProcessFiles"); - - return eSubResult_Continue; - } - - void TSubTaskCopyMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const - { - m_spSubTaskStats->GetSnapshot(spStats); - // if this subtask is not started yet, try to get the most fresh information for processing - if(!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) - { - const auto& rCache = GetContext().GetFilesCache(); - spStats->SetTotalCount(rCache.GetSize()); - spStats->SetTotalSize(rCache.CalculateTotalSize()); - } - } - - TBufferSizes::EBufferType TSubTaskCopyMove::GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo) - { - if(rBufferSizes.IsOnlyDefault()) - return TBufferSizes::eBuffer_Default; - - if(!spFileInfo) - throw TCoreException(eErr_InvalidArgument, L"spFileInfo", LOCATION); - - TSmartPath pathSource = spFileInfo->GetFullFilePath(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - - IFilesystem::EPathsRelation eRelation = GetContext().GetLocalFilesystem()->GetPathsRelation(pathSource, pathDestination); - switch(eRelation) - { - case IFilesystem::eRelation_Network: - return TBufferSizes::eBuffer_LAN; - - case IFilesystem::eRelation_CDRom: - return TBufferSizes::eBuffer_CD; - - case IFilesystem::eRelation_TwoPhysicalDisks: - return TBufferSizes::eBuffer_TwoDisks; - - case IFilesystem::eRelation_SinglePhysicalDisk: - return TBufferSizes::eBuffer_OneDisk; - - //case eRelation_Other: - default: - return TBufferSizes::eBuffer_Default; - } - } - - TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, - TOverlappedThreadPool& rThreadPool, - CUSTOM_COPY_PARAMS* pData) - { - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - const TConfig& rConfig = GetContext().GetConfig(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - - // calculate if we want to disable buffering for file transfer - // NOTE: we are using here the file size read when scanning directories for files; it might be - // outdated at this point, but at present we don't want to re-read file size since it - // will cost additional disk access - bool bNoBuffer = (GetTaskPropValue(rConfig) && - pData->spSrcFile->GetLength64() >= GetTaskPropValue(rConfig)); - - // recreate buffer if needed - AdjustBufferIfNeeded(pData->spMemoryPool, pData->tBufferSizes); - - // establish count of data to read - TBufferSizes::EBufferType eBufferIndex = GetBufferIndex(pData->tBufferSizes, pData->spSrcFile); - m_spSubTaskStats->SetCurrentBufferIndex(eBufferIndex); - - // determine buffer size to use for the operation - DWORD dwCurrentBufferSize = RoundUp(pData->tBufferSizes.GetSizeByType(eBufferIndex), IFilesystemFile::MaxSectorSize); - - // resume copying from the position after the last processed mark; the proper value should be set - // by OpenSrcAndDstFilesFB() - that includes the no-buffering setting if required. - unsigned long long ullNextReadPos = m_spSubTaskStats->GetCurrentItemProcessedSize(); - - TOverlappedReaderWriterFB tReaderWriter(spFilesystem, - spFeedbackHandler, - rThreadController, - rThreadPool, - pData->spSrcFile, - pData->pathDstFile, - m_spSubTaskStats, - m_spLog->GetLogFileData(), - pData->spMemoryPool, - ullNextReadPos, - dwCurrentBufferSize, - bNoBuffer, - GetTaskPropValue(rConfig), - pData->bOnlyCreate); - - ESubOperationResult eResult = tReaderWriter.Start(); - - return eResult; - } - - void TSubTaskCopyMove::AdjustProcessedSizeForSkip(const TFileInfoPtr& spSrcFileInfo) - { - m_spSubTaskStats->AdjustProcessedSize(m_spSubTaskStats->GetCurrentItemProcessedSize(), spSrcFileInfo->GetLength64()); - } - - bool TSubTaskCopyMove::AdjustBufferIfNeeded(const TOverlappedMemoryPoolPtr& spBuffer, TBufferSizes& rBufferSizes, bool bForce) - { - const TConfig& rConfig = GetContext().GetConfig(); - TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); - - if(bForce || (rCfgTracker.IsModified() && rCfgTracker.IsModified(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth, true))) - { - rBufferSizes = GetTaskPropBufferSizes(rConfig); - - // log - TString strFormat; - strFormat = _T("Changing buffer size to [Def:%defsize2, One:%onesize2, Two:%twosize2, CD:%cdsize2, LAN:%lansize2, Count:%cnt]"); - - strFormat.Replace(_T("%defsize2"), boost::lexical_cast(rBufferSizes.GetDefaultSize()).c_str()); - strFormat.Replace(_T("%onesize2"), boost::lexical_cast(rBufferSizes.GetOneDiskSize()).c_str()); - strFormat.Replace(_T("%twosize2"), boost::lexical_cast(rBufferSizes.GetTwoDisksSize()).c_str()); - strFormat.Replace(_T("%cdsize2"), boost::lexical_cast(rBufferSizes.GetCDSize()).c_str()); - strFormat.Replace(_T("%lansize2"), boost::lexical_cast(rBufferSizes.GetLANSize()).c_str()); - strFormat.Replace(_T("%cnt"), boost::lexical_cast(rBufferSizes.GetBufferCount()).c_str()); - - LOG_INFO(m_spLog) << strFormat.c_str(); - - spBuffer->ReinitializeBuffers(rBufferSizes.GetBufferCount(), rBufferSizes.GetMaxSize()); - - return true; // buffer adjusted - } - - return false; // buffer did not need adjusting - } - - void TSubTaskCopyMove::Store(const ISerializerPtr& spSerializer) const - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); - InitColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, m_spSubTaskStats->WasAdded()); - - m_spSubTaskStats->Store(rRow); - } - - void TSubTaskCopyMove::Load(const ISerializerPtr& spSerializer) - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - m_spSubTaskStats->Load(spRowReader); - } - - void TSubTaskCopyMove::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskCopyMove.cpp +/// @date 2010/09/19 +/// @brief Contains implementations of classes responsible for copy and move sub-operation. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskCopyMove.h" +#include "TSubTaskContext.h" +#include "TTaskConfiguration.h" +#include "TTaskLocalStats.h" +#include "TTaskConfigTracker.h" +#include "TWorkerThreadController.h" +#include "IFeedbackHandler.h" +#include +#include "TBasePathData.h" +#include "TFileInfo.h" +#include "TFileInfoArray.h" +#include "ErrorCodes.h" +#include "TCoreException.h" +#include "TPathContainer.h" +#include "TScopedRunningTimeTracker.h" +#include "TFeedbackHandlerWrapper.h" +#include "TOverlappedMemoryPool.h" +#include "RoundingFunctions.h" +#include "TTaskConfigBufferSizes.h" +#include "TFileException.h" +#include "TFilesystemFeedbackWrapper.h" +#include "TFilesystemFileFeedbackWrapper.h" +#include "TDestinationPathProvider.h" +#include "TOverlappedReaderWriterFB.h" +#include "TThreadedQueueRunner.h" +#include "TOverlappedThreadPool.h" + +namespace chcore +{ + struct CUSTOM_COPY_PARAMS + { + CUSTOM_COPY_PARAMS() : + spMemoryPool(std::make_shared()) + { + } + + TFileInfoPtr spSrcFile; // CFileInfo - src file + TSmartPath pathDstFile; // dest path with filename + + TBufferSizes tBufferSizes; + TOverlappedMemoryPoolPtr spMemoryPool; // buffer handling + bool bOnlyCreate = false; // flag from configuration - skips real copying - only create + }; + + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskCopyMove + + TSubTaskCopyMove::TSubTaskCopyMove(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_spSubTaskStats(std::make_shared(eSubOperation_Copying)), + m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-CopyMove")) + { + } + + void TSubTaskCopyMove::Reset() + { + m_spSubTaskStats->Clear(); + } + + void TSubTaskCopyMove::InitBeforeExec() + { + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + + file_count_t fcCount = rFilesCache.GetSize(); + if(fcCount == 0) + { + m_spSubTaskStats->SetCurrentPath(TString()); + return; + } + + file_count_t fcIndex = m_spSubTaskStats->GetCurrentIndex(); + if(fcIndex >= fcCount) + fcIndex = 0; + + TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); + m_spSubTaskStats->SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); + } + + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(*m_spSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); + + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + const TConfig& rConfig = GetContext().GetConfig(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + TBasePathDataContainerPtr spSrcPaths = GetContext().GetBasePaths(); + + TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); + + // log + LOG_INFO(m_spLog) << _T("Processing files/folders (ProcessFiles)"); + + // initialize stats if not resuming (when resuming we have already initialized + // the stats once - it is being restored in Load() too). + if (!m_spSubTaskStats->IsInitialized()) + m_spSubTaskStats->Init(TBufferSizes::eBuffer_Default, rFilesCache.GetSize(), 0, rFilesCache.CalculateTotalSize(), rFilesCache.CalculatePartialSize(m_spSubTaskStats->GetCurrentIndex()), TString()); + else + { + _ASSERTE(rFilesCache.GetSize() == m_spSubTaskStats->GetTotalCount()); + if (rFilesCache.GetSize() != m_spSubTaskStats->GetTotalCount()) + throw TCoreException(eErr_InternalProblem, L"Size of files' cache differs from stats information", LOCATION); + } + + // now it's time to check if there is enough space on destination device + unsigned long long ullNeededSize = rFilesCache.CalculateTotalSize() - rFilesCache.CalculatePartialSize(m_spSubTaskStats->GetCurrentIndex()); + TSmartPath pathSingleSrc = spSrcPaths->GetAt(0)->GetSrcPath(); + TSubTaskBase::ESubOperationResult eResult = tFilesystemFBWrapper.CheckForFreeSpaceFB(pathSingleSrc, pathDestination, ullNeededSize); + if(eResult != eSubResult_Continue) + return eResult; + + // begin at index which wasn't processed previously + file_count_t fcSize = rFilesCache.GetSize(); + file_count_t fcIndex = m_spSubTaskStats->GetCurrentIndex(); + unsigned long long ullCurrentItemProcessedSize = m_spSubTaskStats->GetCurrentItemProcessedSize(); + bool bCurrentFileSilentResume = m_spSubTaskStats->CanCurrentItemSilentResume(); + + // create a buffer of size m_nBufferSize + CUSTOM_COPY_PARAMS ccp; + ccp.bOnlyCreate = GetTaskPropValue(rConfig); + + // remove changes in buffer sizes to avoid re-creation later + rCfgTracker.RemoveModificationSet(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth); + + AdjustBufferIfNeeded(ccp.spMemoryPool, ccp.tBufferSizes, true); + + bool bIgnoreFolders = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); + + TDestinationPathProvider tDstPathProvider(spFilesystem, pathDestination, + bIgnoreFolders, bForceDirectories, + GetTaskPropValue(GetContext().GetConfig()), + GetTaskPropValue(GetContext().GetConfig())); + + // log + TString strFormat; + strFormat = _T("Processing files/folders (ProcessFiles):\r\n\tOnlyCreate: %create\r\n\tFiles/folders count: %filecount\r\n\tIgnore Folders: %ignorefolders\r\n\tDest path: %dstpath\r\n\tCurrent index (0-based): %currindex"); + strFormat.Replace(_T("%create"), boost::lexical_cast(ccp.bOnlyCreate).c_str()); + strFormat.Replace(_T("%filecount"), boost::lexical_cast(fcSize).c_str()); + strFormat.Replace(_T("%ignorefolders"), boost::lexical_cast(bIgnoreFolders).c_str()); + strFormat.Replace(_T("%dstpath"), pathDestination.ToString()); + strFormat.Replace(_T("%currindex"), boost::lexical_cast(fcIndex).c_str()); + + LOG_INFO(m_spLog) << strFormat.c_str(); + + TOverlappedThreadPool threadPool(rThreadController.GetKillThreadHandle()); + + for(; fcIndex < fcSize; fcIndex++) + { + // should we kill ? + if(rThreadController.KillRequested()) + { + // log + LOG_INFO(m_spLog) << _T("Kill request while processing file in ProcessFiles"); + return eSubResult_KillRequest; + } + + // next file to be copied + TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); + if(spFileInfo->IsProcessed()) + continue; + + TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); + + // new stats + m_spSubTaskStats->SetCurrentIndex(fcIndex); + m_spSubTaskStats->SetProcessedCount(fcIndex); + m_spSubTaskStats->SetCurrentPath(pathCurrent.ToString()); + m_spSubTaskStats->SetCurrentItemSizes(ullCurrentItemProcessedSize, spFileInfo->GetLength64()); // preserve the processed size for the first item + ullCurrentItemProcessedSize = 0; // in next iteration we're not resuming anymore + m_spSubTaskStats->SetCurrentItemSilentResume(bCurrentFileSilentResume); + bCurrentFileSilentResume = false; + + // if the file was already processed (e.g. by fast-move), just consider the file skipped + if(spFileInfo->IsBasePathProcessed()) + { + AdjustProcessedSizeForSkip(spFileInfo); + spFileInfo->MarkAsProcessed(true); + continue; + } + + // set dest path with filename + ccp.pathDstFile = tDstPathProvider.CalculateDestinationPath(spFileInfo); + + // are the files/folders lie on the same partition ? + bool bMove = GetContext().GetOperationType() == eOperation_Move; + + // if folder - create it + if(spFileInfo->IsDirectory()) + { + eResult = tFilesystemFBWrapper.CreateDirectoryFB(ccp.pathDstFile); + if(eResult != eSubResult_Continue) + return eResult; + + // new stats + AdjustProcessedSizeForSkip(spFileInfo); + + spFileInfo->MarkAsProcessed(true); + } + else + { + // start copying/moving file + ccp.spSrcFile = spFileInfo; + + // copy data + eResult = CustomCopyFileFB(spFeedbackHandler, threadPool, &ccp); + if (eResult == eSubResult_SkipFile) + { + spFileInfo->MarkAsProcessed(false); + AdjustProcessedSizeForSkip(spFileInfo); + } + else if(eResult != eSubResult_Continue) + return eResult; + else + spFileInfo->MarkAsProcessed(true); + + // if moving - delete file (only if config flag is set) + if(bMove && spFileInfo->IsProcessed() && !GetTaskPropValue(rConfig)) + { + tFilesystemFBWrapper.DeleteFileFB(spFileInfo, GetTaskPropValue(rConfig)); + } + } + + // only set attributes and times when file/dir had been processed successfully. + if(spFileInfo->IsProcessed()) + { + if(GetTaskPropValue(rConfig)) + spFilesystem->SetFileDirectoryTime(ccp.pathDstFile, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); // no error checking (but most probably it should be checked) + + // attributes + if(GetTaskPropValue(rConfig)) + spFilesystem->SetAttributes(ccp.pathDstFile, spFileInfo->GetAttributes()); // as above + } + } + + // update directories file times + bool bUpdateDirTimes = GetTaskPropValue(rConfig); + if(bUpdateDirTimes) + { + LOG_INFO(m_spLog) << _T("Setting directory attributes"); + + // iterate backwards + for(file_count_t fcAttrIndex = fcSize; fcAttrIndex != 0; --fcAttrIndex) + { + // should we kill ? + if(rThreadController.KillRequested()) + { + // log + LOG_INFO(m_spLog) << _T("Kill request while processing file in ProcessFiles"); + return eSubResult_KillRequest; + } + + TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcAttrIndex - 1); + if(spFileInfo->IsDirectory()) + { + TSmartPath pathDstDir = tDstPathProvider.CalculateDestinationPath(spFileInfo); + + spFilesystem->SetFileDirectoryTime(pathDstDir, spFileInfo->GetCreationTime(), spFileInfo->GetLastAccessTime(), spFileInfo->GetLastWriteTime()); + } + } + } + + // stats + m_spSubTaskStats->SetCurrentIndex(fcIndex); + m_spSubTaskStats->SetProcessedCount(fcIndex); + m_spSubTaskStats->SetCurrentPath(TString()); + + // log + LOG_INFO(m_spLog) << _T("Finished processing in ProcessFiles"); + + return eSubResult_Continue; + } + + void TSubTaskCopyMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_spSubTaskStats->GetSnapshot(spStats); + // if this subtask is not started yet, try to get the most fresh information for processing + if(!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + { + const auto& rCache = GetContext().GetFilesCache(); + spStats->SetTotalCount(rCache.GetSize()); + spStats->SetTotalSize(rCache.CalculateTotalSize()); + } + } + + TBufferSizes::EBufferType TSubTaskCopyMove::GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo) + { + if(rBufferSizes.IsOnlyDefault()) + return TBufferSizes::eBuffer_Default; + + if(!spFileInfo) + throw TCoreException(eErr_InvalidArgument, L"spFileInfo", LOCATION); + + TSmartPath pathSource = spFileInfo->GetFullFilePath(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); + + IFilesystem::EPathsRelation eRelation = GetContext().GetLocalFilesystem()->GetPathsRelation(pathSource, pathDestination); + switch(eRelation) + { + case IFilesystem::eRelation_Network: + return TBufferSizes::eBuffer_LAN; + + case IFilesystem::eRelation_CDRom: + return TBufferSizes::eBuffer_CD; + + case IFilesystem::eRelation_TwoPhysicalDisks: + return TBufferSizes::eBuffer_TwoDisks; + + case IFilesystem::eRelation_SinglePhysicalDisk: + return TBufferSizes::eBuffer_OneDisk; + + //case eRelation_Other: + default: + return TBufferSizes::eBuffer_Default; + } + } + + TSubTaskBase::ESubOperationResult TSubTaskCopyMove::CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, + TOverlappedThreadPool& rThreadPool, + CUSTOM_COPY_PARAMS* pData) + { + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + const TConfig& rConfig = GetContext().GetConfig(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + + // calculate if we want to disable buffering for file transfer + // NOTE: we are using here the file size read when scanning directories for files; it might be + // outdated at this point, but at present we don't want to re-read file size since it + // will cost additional disk access + bool bNoBuffer = (GetTaskPropValue(rConfig) && + pData->spSrcFile->GetLength64() >= GetTaskPropValue(rConfig)); + + // recreate buffer if needed + AdjustBufferIfNeeded(pData->spMemoryPool, pData->tBufferSizes); + + // establish count of data to read + TBufferSizes::EBufferType eBufferIndex = GetBufferIndex(pData->tBufferSizes, pData->spSrcFile); + m_spSubTaskStats->SetCurrentBufferIndex(eBufferIndex); + + // determine buffer size to use for the operation + DWORD dwCurrentBufferSize = RoundUp(pData->tBufferSizes.GetSizeByType(eBufferIndex), IFilesystemFile::MaxSectorSize); + + // resume copying from the position after the last processed mark; the proper value should be set + // by OpenSrcAndDstFilesFB() - that includes the no-buffering setting if required. + unsigned long long ullNextReadPos = m_spSubTaskStats->GetCurrentItemProcessedSize(); + + TOverlappedReaderWriterFB tReaderWriter(spFilesystem, + spFeedbackHandler, + rThreadController, + rThreadPool, + pData->spSrcFile, + pData->pathDstFile, + m_spSubTaskStats, + m_spLog->GetLogFileData(), + pData->spMemoryPool, + ullNextReadPos, + dwCurrentBufferSize, + bNoBuffer, + GetTaskPropValue(rConfig), + pData->bOnlyCreate); + + ESubOperationResult eResult = tReaderWriter.Start(); + + return eResult; + } + + void TSubTaskCopyMove::AdjustProcessedSizeForSkip(const TFileInfoPtr& spSrcFileInfo) + { + m_spSubTaskStats->AdjustProcessedSize(m_spSubTaskStats->GetCurrentItemProcessedSize(), spSrcFileInfo->GetLength64()); + } + + bool TSubTaskCopyMove::AdjustBufferIfNeeded(const TOverlappedMemoryPoolPtr& spBuffer, TBufferSizes& rBufferSizes, bool bForce) + { + const TConfig& rConfig = GetContext().GetConfig(); + TTaskConfigTracker& rCfgTracker = GetContext().GetCfgTracker(); + + if(bForce || (rCfgTracker.IsModified() && rCfgTracker.IsModified(TOptionsSet() % eTO_DefaultBufferSize % eTO_OneDiskBufferSize % eTO_TwoDisksBufferSize % eTO_CDBufferSize % eTO_LANBufferSize % eTO_UseOnlyDefaultBuffer % eTO_BufferQueueDepth, true))) + { + rBufferSizes = GetTaskPropBufferSizes(rConfig); + + // log + TString strFormat; + strFormat = _T("Changing buffer size to [Def:%defsize2, One:%onesize2, Two:%twosize2, CD:%cdsize2, LAN:%lansize2, Count:%cnt]"); + + strFormat.Replace(_T("%defsize2"), boost::lexical_cast(rBufferSizes.GetDefaultSize()).c_str()); + strFormat.Replace(_T("%onesize2"), boost::lexical_cast(rBufferSizes.GetOneDiskSize()).c_str()); + strFormat.Replace(_T("%twosize2"), boost::lexical_cast(rBufferSizes.GetTwoDisksSize()).c_str()); + strFormat.Replace(_T("%cdsize2"), boost::lexical_cast(rBufferSizes.GetCDSize()).c_str()); + strFormat.Replace(_T("%lansize2"), boost::lexical_cast(rBufferSizes.GetLANSize()).c_str()); + strFormat.Replace(_T("%cnt"), boost::lexical_cast(rBufferSizes.GetBufferCount()).c_str()); + + LOG_INFO(m_spLog) << strFormat.c_str(); + + spBuffer->ReinitializeBuffers(rBufferSizes.GetBufferCount(), rBufferSizes.GetMaxSize()); + + return true; // buffer adjusted + } + + return false; // buffer did not need adjusting + } + + void TSubTaskCopyMove::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); + InitColumns(spContainer); + + ISerializerRowData& rRow = spContainer->GetRow(0, m_spSubTaskStats->WasAdded()); + + m_spSubTaskStats->Store(rRow); + } + + void TSubTaskCopyMove::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_copymove")); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if(spRowReader->Next()) + m_spSubTaskStats->Load(spRowReader); + } + + void TSubTaskCopyMove::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if(rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } +} Index: src/libchcore/TSubTaskCopyMove.h =================================================================== diff -u -rb0a003dc39e6d21e34779cf1cf5d8a07318c1f5f -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskCopyMove.h (.../TSubTaskCopyMove.h) (revision b0a003dc39e6d21e34779cf1cf5d8a07318c1f5f) +++ src/libchcore/TSubTaskCopyMove.h (.../TSubTaskCopyMove.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,82 +1,82 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskCopyMove.h -/// @date 2010/09/18 -/// @brief Contains declarations of classes responsible for copy and move sub-operation. -// ============================================================================ -#ifndef __TSUBTASKCOPYMOVE_H__ -#define __TSUBTASKCOPYMOVE_H__ - -#include "libchcore.h" -#include "TSubTaskBase.h" -#include "TBufferSizes.h" -#include "../liblogger/TLogger.h" -#include "TOverlappedMemoryPool.h" -#include "TOverlappedReaderFB.h" -#include "TOverlappedWriterFB.h" - -namespace chcore -{ - class TOverlappedThreadPool; - typedef std::shared_ptr TFileInfoPtr; - struct CUSTOM_COPY_PARAMS; - - class TDataBufferManager; - class TSimpleDataBuffer; - class TBufferSizes; - class TFilesystemFileFeedbackWrapper; - - class LIBCHCORE_API TSubTaskCopyMove : public TSubTaskBase - { - public: - explicit TSubTaskCopyMove(TSubTaskContext& tSubTaskContext); - - virtual void Reset(); - - virtual void InitBeforeExec() override; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Copying; } - - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; - - private: - TBufferSizes::EBufferType GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo); - bool AdjustBufferIfNeeded(const TOverlappedMemoryPoolPtr& spBuffer, TBufferSizes& rBufferSizes, bool bForce = false); - - ESubOperationResult CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, - TOverlappedThreadPool& rThreadPool, - CUSTOM_COPY_PARAMS* pData); - - void AdjustProcessedSizeForSkip(const TFileInfoPtr& spSrcFileInfo); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - TSubTaskStatsInfoPtr m_spSubTaskStats; - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskCopyMove.h +/// @date 2010/09/18 +/// @brief Contains declarations of classes responsible for copy and move sub-operation. +// ============================================================================ +#ifndef __TSUBTASKCOPYMOVE_H__ +#define __TSUBTASKCOPYMOVE_H__ + +#include "libchcore.h" +#include "TSubTaskBase.h" +#include "TBufferSizes.h" +#include "../liblogger/TLogger.h" +#include "TOverlappedMemoryPool.h" +#include "TOverlappedReaderFB.h" +#include "TOverlappedWriterFB.h" + +namespace chcore +{ + class TOverlappedThreadPool; + typedef std::shared_ptr TFileInfoPtr; + struct CUSTOM_COPY_PARAMS; + + class TDataBufferManager; + class TSimpleDataBuffer; + class TBufferSizes; + class TFilesystemFileFeedbackWrapper; + + class LIBCHCORE_API TSubTaskCopyMove : public TSubTaskBase + { + public: + explicit TSubTaskCopyMove(TSubTaskContext& tSubTaskContext); + + virtual void Reset(); + + virtual void InitBeforeExec() override; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Copying; } + + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const; + + private: + TBufferSizes::EBufferType GetBufferIndex(const TBufferSizes& rBufferSizes, const TFileInfoPtr& spFileInfo); + bool AdjustBufferIfNeeded(const TOverlappedMemoryPoolPtr& spBuffer, TBufferSizes& rBufferSizes, bool bForce = false); + + ESubOperationResult CustomCopyFileFB(const IFeedbackHandlerPtr& spFeedbackHandler, + TOverlappedThreadPool& rThreadPool, + CUSTOM_COPY_PARAMS* pData); + + void AdjustProcessedSizeForSkip(const TFileInfoPtr& spSrcFileInfo); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + TSubTaskStatsInfoPtr m_spSubTaskStats; + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskDelete.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskDelete.cpp (.../TSubTaskDelete.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSubTaskDelete.cpp (.../TSubTaskDelete.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,190 +1,190 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskDelete.cpp -/// @date 2010/09/19 -/// @brief Contains implementation of classes responsible for delete sub-operation. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskDelete.h" -#include "TSubTaskContext.h" -#include "TWorkerThreadController.h" -#include "TTaskConfiguration.h" -#include "IFeedbackHandler.h" -#include -#include "TFileInfoArray.h" -#include "TFileInfo.h" -#include "TTaskLocalStats.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TScopedRunningTimeTracker.h" -#include "TFeedbackHandlerWrapper.h" -#include "TBufferSizes.h" -#include "TFileException.h" -#include "TFilesystemFeedbackWrapper.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////////////////////// - // class TSubTaskDelete - - TSubTaskDelete::TSubTaskDelete(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_Deleting), - m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-Delete")) - { - } - - void TSubTaskDelete::Reset() - { - m_tSubTaskStats.Clear(); - } - - void TSubTaskDelete::InitBeforeExec() - { - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - - file_count_t fcCount = rFilesCache.GetSize(); - if(fcCount == 0) - { - m_tSubTaskStats.SetCurrentPath(TString()); - return; - } - - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - if(fcIndex >= fcCount) - fcIndex = 0; - - TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); - m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); - } - - TSubTaskBase::ESubOperationResult TSubTaskDelete::Exec(const IFeedbackHandlerPtr& spFeedback) - { - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); - - // log - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - - TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); - - // log - LOG_INFO(m_spLog) << _T("Deleting files (DeleteFiles)..."); - - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetTotalCount(rFilesCache.GetSize()); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); - - // current processed path - TFileInfoPtr spFileInfo; - TString strFormat; - - // index points to 0 or next item to process - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - while (fcIndex < rFilesCache.GetSize()) - { - spFileInfo = rFilesCache.GetAt(rFilesCache.GetSize() - fcIndex - 1); - - m_tSubTaskStats.SetCurrentIndex(fcIndex); - - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); - - // check for kill flag - if (rThreadController.KillRequested()) - { - // log - LOG_INFO(m_spLog) << _T("Kill request while deleting files (Delete Files)"); - return TSubTaskBase::eSubResult_KillRequest; - } - - // if the file/dir was not processed by copy/move then do not delete - // on the other hand, if the base path was processed (at this this it would be only by fast-move) then skip deleting - if (!spFileInfo->IsProcessed() || spFileInfo->IsBasePathProcessed()) - { - ++fcIndex; - continue; - } - - // delete data - bool bProtectReadOnlyFiles = GetTaskPropValue(GetContext().GetConfig()); - if (spFileInfo->IsDirectory()) - tFilesystemFBWrapper.RemoveDirectoryFB(spFileInfo, bProtectReadOnlyFiles); - else - tFilesystemFBWrapper.DeleteFileFB(spFileInfo, bProtectReadOnlyFiles); - - ++fcIndex; - } - - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); - - // log - LOG_INFO(m_spLog) << _T("Deleting files finished"); - - return TSubTaskBase::eSubResult_Continue; - } - - void TSubTaskDelete::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const - { - m_tSubTaskStats.GetSnapshot(spStats); - // if this subtask is not started yet, try to get the most fresh information for processing - if (!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) - { - spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); - spStats->SetTotalSize(0); - } - } - - void TSubTaskDelete::Store(const ISerializerPtr& spSerializer) const - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); - InitColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - - m_tSubTaskStats.Store(rRow); - } - - void TSubTaskDelete::Load(const ISerializerPtr& spSerializer) - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); - } - - void TSubTaskDelete::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskDelete.cpp +/// @date 2010/09/19 +/// @brief Contains implementation of classes responsible for delete sub-operation. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskDelete.h" +#include "TSubTaskContext.h" +#include "TWorkerThreadController.h" +#include "TTaskConfiguration.h" +#include "IFeedbackHandler.h" +#include +#include "TFileInfoArray.h" +#include "TFileInfo.h" +#include "TTaskLocalStats.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TScopedRunningTimeTracker.h" +#include "TFeedbackHandlerWrapper.h" +#include "TBufferSizes.h" +#include "TFileException.h" +#include "TFilesystemFeedbackWrapper.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskDelete + + TSubTaskDelete::TSubTaskDelete(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_Deleting), + m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-Delete")) + { + } + + void TSubTaskDelete::Reset() + { + m_tSubTaskStats.Clear(); + } + + void TSubTaskDelete::InitBeforeExec() + { + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + + file_count_t fcCount = rFilesCache.GetSize(); + if(fcCount == 0) + { + m_tSubTaskStats.SetCurrentPath(TString()); + return; + } + + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + if(fcIndex >= fcCount) + fcIndex = 0; + + TFileInfoPtr spFileInfo = rFilesCache.GetAt(fcIndex); + m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); + } + + TSubTaskBase::ESubOperationResult TSubTaskDelete::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); + + // log + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + + TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); + + // log + LOG_INFO(m_spLog) << _T("Deleting files (DeleteFiles)..."); + + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetTotalCount(rFilesCache.GetSize()); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); + + // current processed path + TFileInfoPtr spFileInfo; + TString strFormat; + + // index points to 0 or next item to process + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + while (fcIndex < rFilesCache.GetSize()) + { + spFileInfo = rFilesCache.GetAt(rFilesCache.GetSize() - fcIndex - 1); + + m_tSubTaskStats.SetCurrentIndex(fcIndex); + + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(spFileInfo->GetFullFilePath().ToString()); + + // check for kill flag + if (rThreadController.KillRequested()) + { + // log + LOG_INFO(m_spLog) << _T("Kill request while deleting files (Delete Files)"); + return TSubTaskBase::eSubResult_KillRequest; + } + + // if the file/dir was not processed by copy/move then do not delete + // on the other hand, if the base path was processed (at this this it would be only by fast-move) then skip deleting + if (!spFileInfo->IsProcessed() || spFileInfo->IsBasePathProcessed()) + { + ++fcIndex; + continue; + } + + // delete data + bool bProtectReadOnlyFiles = GetTaskPropValue(GetContext().GetConfig()); + if (spFileInfo->IsDirectory()) + tFilesystemFBWrapper.RemoveDirectoryFB(spFileInfo, bProtectReadOnlyFiles); + else + tFilesystemFBWrapper.DeleteFileFB(spFileInfo, bProtectReadOnlyFiles); + + ++fcIndex; + } + + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); + + // log + LOG_INFO(m_spLog) << _T("Deleting files finished"); + + return TSubTaskBase::eSubResult_Continue; + } + + void TSubTaskDelete::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_tSubTaskStats.GetSnapshot(spStats); + // if this subtask is not started yet, try to get the most fresh information for processing + if (!spStats->IsRunning() && spStats->GetTotalCount() == 0 && spStats->GetTotalSize() == 0) + { + spStats->SetTotalCount(GetContext().GetFilesCache().GetSize()); + spStats->SetTotalSize(0); + } + } + + void TSubTaskDelete::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); + InitColumns(spContainer); + + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + + m_tSubTaskStats.Store(rRow); + } + + void TSubTaskDelete::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_delete")); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } + + void TSubTaskDelete::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } +} Index: src/libchcore/TSubTaskDelete.h =================================================================== diff -u -r12b36349f6214befeace08efa9acc7e03be0d847 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskDelete.h (.../TSubTaskDelete.h) (revision 12b36349f6214befeace08efa9acc7e03be0d847) +++ src/libchcore/TSubTaskDelete.h (.../TSubTaskDelete.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,62 +1,62 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskDelete.h -/// @date 2010/09/18 -/// @brief Contains declarations of classes responsible for delete sub-operation. -// ============================================================================ -#ifndef __TSUBTASKDELETE_H__ -#define __TSUBTASKDELETE_H__ - -#include "libchcore.h" -#include "TSubTaskBase.h" -#include "../liblogger/TLogger.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - // TSubTaskDelete - - class LIBCHCORE_API TSubTaskDelete : public TSubTaskBase - { - public: - explicit TSubTaskDelete(TSubTaskContext& rContext); - - virtual void Reset(); - - virtual void InitBeforeExec() override; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Deleting; } - - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskDelete.h +/// @date 2010/09/18 +/// @brief Contains declarations of classes responsible for delete sub-operation. +// ============================================================================ +#ifndef __TSUBTASKDELETE_H__ +#define __TSUBTASKDELETE_H__ + +#include "libchcore.h" +#include "TSubTaskBase.h" +#include "../liblogger/TLogger.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + // TSubTaskDelete + + class LIBCHCORE_API TSubTaskDelete : public TSubTaskBase + { + public: + explicit TSubTaskDelete(TSubTaskContext& rContext); + + virtual void Reset(); + + virtual void InitBeforeExec() override; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Deleting; } + + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + TSubTaskStatsInfo m_tSubTaskStats; + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskFastMove.cpp =================================================================== diff -u -rc0d9a798f9fbbeda239b84721ed864f9727e1ddc -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskFastMove.cpp (.../TSubTaskFastMove.cpp) (revision c0d9a798f9fbbeda239b84721ed864f9727e1ddc) +++ src/libchcore/TSubTaskFastMove.cpp (.../TSubTaskFastMove.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,219 +1,219 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskScanDirectory.cpp -/// @date 2010/09/18 -/// @brief Contains implementation of classes related to scan directory subtask. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskFastMove.h" -#include "TSubTaskContext.h" -#include "TTaskConfiguration.h" -#include "IFeedbackHandler.h" -#include "TBasePathData.h" -#include "TWorkerThreadController.h" -#include "TTaskLocalStats.h" -#include "TFileInfo.h" -#include -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TPathContainer.h" -#include "TScopedRunningTimeTracker.h" -#include "TFeedbackHandlerWrapper.h" -#include "TBufferSizes.h" -#include "TFileException.h" -#include "TFilesystemFeedbackWrapper.h" -#include "TDestinationPathProvider.h" - -namespace chcore -{ - TSubTaskFastMove::TSubTaskFastMove(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_FastMove), - m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-FastMove")) - { - } - - TSubTaskFastMove::~TSubTaskFastMove() - { - } - - void TSubTaskFastMove::Reset() - { - m_tSubTaskStats.Clear(); - } - - void TSubTaskFastMove::InitBeforeExec() - { - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - - file_count_t fcSize = spBasePaths->GetCount(); - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - - if(fcIndex >= fcSize) - fcIndex = 0; - - if(fcSize > 0) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - m_tSubTaskStats.SetCurrentPath(spBasePath->GetSrcPath().ToString()); - } - else - m_tSubTaskStats.SetCurrentPath(TString()); - } - - TSubTaskFastMove::ESubOperationResult TSubTaskFastMove::Exec(const IFeedbackHandlerPtr& spFeedback) - { - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); - - // log - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const TConfig& rConfig = GetContext().GetConfig(); - TSmartPath pathDestination = GetContext().GetDestinationPath(); - const TFileFiltersArray& rafFilters = GetContext().GetFilters(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - - TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); - - LOG_INFO(m_spLog) << _T("Performing initial fast-move operation..."); - - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); - - bool bIgnoreDirs = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); - - // when using special options with move operation, we don't want to use fast-moving, since most probably - // some searching and special processing needs to be done - if (bIgnoreDirs || bForceDirectories) - { - m_tSubTaskStats.SetTotalCount(0); - return eSubResult_Continue; - } - else - m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); - - TDestinationPathProvider tDstPathProvider(spFilesystem, pathDestination, - bIgnoreDirs, bForceDirectories, - GetTaskPropValue(GetContext().GetConfig()), - GetTaskPropValue(GetContext().GetConfig())); - - // add everything - TString strFormat; - - file_count_t fcSize = spBasePaths->GetCount(); - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - for (; fcIndex < fcSize; fcIndex++) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - TSmartPath pathCurrent = spBasePath->GetSrcPath(); - - // store currently processed index - m_tSubTaskStats.SetCurrentIndex(fcIndex); - - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); - - // retrieve base path data - // check if we want to process this path at all - if (spBasePath->GetSkipFurtherProcessing()) - continue; - - TFileInfoPtr spFileInfo(std::make_shared()); - - ESubOperationResult eResult = tFilesystemFBWrapper.GetFileInfoFB(pathCurrent, spFileInfo, spBasePath); - if (eResult == TSubTaskBase::eSubResult_SkipFile) - { - spBasePath->SetSkipFurtherProcessing(true); - continue; - } - else if (eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - - // does it match the input filter? - if (!spFileInfo->IsDirectory() && !rafFilters.Match(spFileInfo)) - { - spBasePath->SetSkipFurtherProcessing(true); - continue; - } - - // try to fast move - eResult = tFilesystemFBWrapper.FastMoveFB(spFileInfo, tDstPathProvider.CalculateDestinationPath(spFileInfo), spBasePath); - if (eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - - // check for kill need - if (rThreadController.KillRequested()) - { - // log - LOG_INFO(m_spLog) << _T("Kill request while fast moving items"); - return eSubResult_KillRequest; - } - } - - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); - - // log - LOG_INFO(m_spLog) << _T("Fast moving finished"); - - return eSubResult_Continue; - } - - void TSubTaskFastMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const - { - m_tSubTaskStats.GetSnapshot(spStats); - } - - void TSubTaskFastMove::Store(const ISerializerPtr& spSerializer) const - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); - - InitColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - - m_tSubTaskStats.Store(rRow); - } - - void TSubTaskFastMove::Load(const ISerializerPtr& spSerializer) - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); - } - - void TSubTaskFastMove::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskScanDirectory.cpp +/// @date 2010/09/18 +/// @brief Contains implementation of classes related to scan directory subtask. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskFastMove.h" +#include "TSubTaskContext.h" +#include "TTaskConfiguration.h" +#include "IFeedbackHandler.h" +#include "TBasePathData.h" +#include "TWorkerThreadController.h" +#include "TTaskLocalStats.h" +#include "TFileInfo.h" +#include +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TPathContainer.h" +#include "TScopedRunningTimeTracker.h" +#include "TFeedbackHandlerWrapper.h" +#include "TBufferSizes.h" +#include "TFileException.h" +#include "TFilesystemFeedbackWrapper.h" +#include "TDestinationPathProvider.h" + +namespace chcore +{ + TSubTaskFastMove::TSubTaskFastMove(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_FastMove), + m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-FastMove")) + { + } + + TSubTaskFastMove::~TSubTaskFastMove() + { + } + + void TSubTaskFastMove::Reset() + { + m_tSubTaskStats.Clear(); + } + + void TSubTaskFastMove::InitBeforeExec() + { + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + + file_count_t fcSize = spBasePaths->GetCount(); + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + + if(fcIndex >= fcSize) + fcIndex = 0; + + if(fcSize > 0) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + m_tSubTaskStats.SetCurrentPath(spBasePath->GetSrcPath().ToString()); + } + else + m_tSubTaskStats.SetCurrentPath(TString()); + } + + TSubTaskFastMove::ESubOperationResult TSubTaskFastMove::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); + + // log + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const TConfig& rConfig = GetContext().GetConfig(); + TSmartPath pathDestination = GetContext().GetDestinationPath(); + const TFileFiltersArray& rafFilters = GetContext().GetFilters(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + + TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); + + LOG_INFO(m_spLog) << _T("Performing initial fast-move operation..."); + + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); + + bool bIgnoreDirs = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); + + // when using special options with move operation, we don't want to use fast-moving, since most probably + // some searching and special processing needs to be done + if (bIgnoreDirs || bForceDirectories) + { + m_tSubTaskStats.SetTotalCount(0); + return eSubResult_Continue; + } + else + m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); + + TDestinationPathProvider tDstPathProvider(spFilesystem, pathDestination, + bIgnoreDirs, bForceDirectories, + GetTaskPropValue(GetContext().GetConfig()), + GetTaskPropValue(GetContext().GetConfig())); + + // add everything + TString strFormat; + + file_count_t fcSize = spBasePaths->GetCount(); + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + for (; fcIndex < fcSize; fcIndex++) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + TSmartPath pathCurrent = spBasePath->GetSrcPath(); + + // store currently processed index + m_tSubTaskStats.SetCurrentIndex(fcIndex); + + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); + + // retrieve base path data + // check if we want to process this path at all + if (spBasePath->GetSkipFurtherProcessing()) + continue; + + TFileInfoPtr spFileInfo(std::make_shared()); + + ESubOperationResult eResult = tFilesystemFBWrapper.GetFileInfoFB(pathCurrent, spFileInfo, spBasePath); + if (eResult == TSubTaskBase::eSubResult_SkipFile) + { + spBasePath->SetSkipFurtherProcessing(true); + continue; + } + else if (eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + + // does it match the input filter? + if (!spFileInfo->IsDirectory() && !rafFilters.Match(spFileInfo)) + { + spBasePath->SetSkipFurtherProcessing(true); + continue; + } + + // try to fast move + eResult = tFilesystemFBWrapper.FastMoveFB(spFileInfo, tDstPathProvider.CalculateDestinationPath(spFileInfo), spBasePath); + if (eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + + // check for kill need + if (rThreadController.KillRequested()) + { + // log + LOG_INFO(m_spLog) << _T("Kill request while fast moving items"); + return eSubResult_KillRequest; + } + } + + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); + + // log + LOG_INFO(m_spLog) << _T("Fast moving finished"); + + return eSubResult_Continue; + } + + void TSubTaskFastMove::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_tSubTaskStats.GetSnapshot(spStats); + } + + void TSubTaskFastMove::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); + + InitColumns(spContainer); + + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + + m_tSubTaskStats.Store(rRow); + } + + void TSubTaskFastMove::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_fastmove")); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } + + void TSubTaskFastMove::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } +} Index: src/libchcore/TSubTaskFastMove.h =================================================================== diff -u -r12b36349f6214befeace08efa9acc7e03be0d847 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskFastMove.h (.../TSubTaskFastMove.h) (revision 12b36349f6214befeace08efa9acc7e03be0d847) +++ src/libchcore/TSubTaskFastMove.h (.../TSubTaskFastMove.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,65 +1,65 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskFastMove.h -/// @date 2011/11/13 -/// @brief Contains declarations of classes responsible for fast move subtask. -// ============================================================================ -#ifndef __TSUBTASKFASTMOVE_H__ -#define __TSUBTASKFASTMOVE_H__ - -#include "libchcore.h" -#include "TSubTaskBase.h" -#include "../liblogger/TLogger.h" - -namespace chcore -{ - class TFileFiltersArray; - - /////////////////////////////////////////////////////////////////////////// - // TSubTaskFastMove - - class LIBCHCORE_API TSubTaskFastMove : public TSubTaskBase - { - public: - explicit TSubTaskFastMove(TSubTaskContext& rContext); - virtual ~TSubTaskFastMove(); - - virtual void Reset(); - - virtual void InitBeforeExec() override; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_FastMove; } - - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const override; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskFastMove.h +/// @date 2011/11/13 +/// @brief Contains declarations of classes responsible for fast move subtask. +// ============================================================================ +#ifndef __TSUBTASKFASTMOVE_H__ +#define __TSUBTASKFASTMOVE_H__ + +#include "libchcore.h" +#include "TSubTaskBase.h" +#include "../liblogger/TLogger.h" + +namespace chcore +{ + class TFileFiltersArray; + + /////////////////////////////////////////////////////////////////////////// + // TSubTaskFastMove + + class LIBCHCORE_API TSubTaskFastMove : public TSubTaskBase + { + public: + explicit TSubTaskFastMove(TSubTaskContext& rContext); + virtual ~TSubTaskFastMove(); + + virtual void Reset(); + + virtual void InitBeforeExec() override; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_FastMove; } + + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& rStats) const override; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + TSubTaskStatsInfo m_tSubTaskStats; + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskScanDirectory.cpp =================================================================== diff -u -rc0d9a798f9fbbeda239b84721ed864f9727e1ddc -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskScanDirectory.cpp (.../TSubTaskScanDirectory.cpp) (revision c0d9a798f9fbbeda239b84721ed864f9727e1ddc) +++ src/libchcore/TSubTaskScanDirectory.cpp (.../TSubTaskScanDirectory.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,283 +1,283 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskScanDirectory.cpp -/// @date 2010/09/18 -/// @brief Contains implementation of classes related to scan directory subtask. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskScanDirectory.h" -#include "TSubTaskContext.h" -#include "TTaskConfiguration.h" -#include "IFeedbackHandler.h" -#include "TBasePathData.h" -#include "TWorkerThreadController.h" -#include "TTaskLocalStats.h" -#include "TFileInfoArray.h" -#include "TFileInfo.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TPathContainer.h" -#include "TScopedRunningTimeTracker.h" -#include "TFeedbackHandlerWrapper.h" -#include "TBufferSizes.h" -#include "TFileException.h" -#include "TFilesystemFeedbackWrapper.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////////////////////// - // class TSubTaskScanDirectories - TSubTaskScanDirectories::TSubTaskScanDirectories(TSubTaskContext& rContext) : - TSubTaskBase(rContext), - m_tSubTaskStats(eSubOperation_Scanning), - m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-ScanDirs")) - { - } - - TSubTaskScanDirectories::~TSubTaskScanDirectories() - { - } - - void TSubTaskScanDirectories::Reset() - { - m_tSubTaskStats.Clear(); - } - - void TSubTaskScanDirectories::InitBeforeExec() - { - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - - file_count_t fcSize = spBasePaths->GetCount(); - file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); - - if(fcIndex >= fcSize) - fcIndex = 0; - - if(fcSize > 0) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - m_tSubTaskStats.SetCurrentPath(spBasePath->GetSrcPath().ToString()); - } - else - m_tSubTaskStats.SetCurrentPath(TString()); - } - - TSubTaskScanDirectories::ESubOperationResult TSubTaskScanDirectories::Exec(const IFeedbackHandlerPtr& spFeedback) - { - TScopedRunningTimeTracker guard(m_tSubTaskStats); - TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); - - // log - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const TConfig& rConfig = GetContext().GetConfig(); - const TFileFiltersArray& rafFilters = GetContext().GetFilters(); - IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); - - TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); - - LOG_INFO(m_spLog) << _T("Searching for files..."); - - // reset progress - rFilesCache.SetComplete(false); - - // new stats - m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); - m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); - m_tSubTaskStats.SetProcessedCount(0); - m_tSubTaskStats.SetTotalSize(0); - m_tSubTaskStats.SetProcessedSize(0); - m_tSubTaskStats.SetCurrentPath(TString()); - - // delete the content of rFilesCache - rFilesCache.Clear(); - - bool bIgnoreDirs = GetTaskPropValue(rConfig); - bool bForceDirectories = GetTaskPropValue(rConfig); - - // add everything - TString strFormat; - - file_count_t fcSize = spBasePaths->GetCount(); - // NOTE: in theory, we should resume the scanning, but in practice we are always restarting scanning if interrupted. - file_count_t fcIndex = 0; // m_tSubTaskStats.GetCurrentIndex() - for (; fcIndex < fcSize; fcIndex++) - { - TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); - TSmartPath pathCurrent = spBasePath->GetSrcPath(); - - m_tSubTaskStats.SetCurrentIndex(fcIndex); - - // new stats - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); - - TFileInfoPtr spFileInfo(std::make_shared()); - - // check if we want to process this path at all (might be already fast moved) - if (spBasePath->GetSkipFurtherProcessing()) - continue; - - // try to get some info about the input path; let user know if the path does not exist. - ESubOperationResult eResult = tFilesystemFBWrapper.GetFileInfoFB(pathCurrent, spFileInfo, spBasePath); - if (eResult == TSubTaskBase::eSubResult_SkipFile) - continue; - else if (eResult != TSubTaskBase::eSubResult_Continue) - return eResult; - - // log - strFormat = _T("Adding file/folder (clipboard) : %path ..."); - strFormat.Replace(_T("%path"), pathCurrent.ToString()); - LOG_INFO(m_spLog) << strFormat.c_str(); - - // add if needed - if (spFileInfo->IsDirectory()) - { - // add if folder's aren't ignored - if (!bIgnoreDirs && !bForceDirectories) - { - // add directory info; it is not to be filtered with afFilters - rFilesCache.AddFileInfo(spFileInfo); - - // log - strFormat = _T("Added folder %path"); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - LOG_INFO(m_spLog) << strFormat.c_str(); - } - - // don't add folder contents when moving inside one disk boundary - // log - strFormat = _T("Recursing folder %path"); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - LOG_INFO(m_spLog) << strFormat.c_str(); - - ScanDirectory(spFileInfo->GetFullFilePath(), spBasePath, true, !bIgnoreDirs || bForceDirectories, rafFilters); - - // check for kill need - if (rThreadController.KillRequested()) - { - // log - LOG_INFO(m_spLog) << _T("Kill request while adding data to files array (RecurseDirectories)"); - rFilesCache.Clear(); - return eSubResult_KillRequest; - } - } - else - { - // add file info if passes filters - if (rafFilters.Match(spFileInfo)) - rFilesCache.AddFileInfo(spFileInfo); - - // log - strFormat = _T("Added file %path"); - strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); - LOG_INFO(m_spLog) << strFormat.c_str(); - } - } - - // update stats - m_tSubTaskStats.SetCurrentIndex(fcIndex); - m_tSubTaskStats.SetProcessedCount(fcIndex); - m_tSubTaskStats.SetCurrentPath(TString()); - - rFilesCache.SetComplete(true); - - // log - LOG_INFO(m_spLog) << _T("Searching for files finished"); - - return eSubResult_Continue; - } - - void TSubTaskScanDirectories::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const - { - m_tSubTaskStats.GetSnapshot(spStats); - } - - int TSubTaskScanDirectories::ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, - bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters) - { - TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); - TWorkerThreadController& rThreadController = GetContext().GetThreadController(); - TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); - const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); - - IFilesystemFindPtr spFinder = spFilesystem->CreateFinderObject(pathDirName, PathFromString(_T("*"))); - TFileInfoPtr spFileInfo(std::make_shared()); - - while (spFinder->FindNext(spFileInfo)) - { - if (rThreadController.KillRequested()) - break; - - if (!spFileInfo->IsDirectory()) - { - if (afFilters.Match(spFileInfo)) - { - spFileInfo->SetParentObject(spBasePathData); - rFilesCache.AddFileInfo(spFileInfo); - spFileInfo = std::make_shared(); - } - } - else - { - TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); - if (bIncludeDirs) - { - spFileInfo->SetParentObject(spBasePathData); - rFilesCache.AddFileInfo(spFileInfo); - spFileInfo = std::make_shared(); - } - - if (bRecurse) - ScanDirectory(pathCurrent, spBasePathData, bRecurse, bIncludeDirs, afFilters); - } - } - - return 0; - } - void TSubTaskScanDirectories::Store(const ISerializerPtr& spSerializer) const - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_scan")); - - InitColumns(spContainer); - - ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); - - m_tSubTaskStats.Store(rRow); - } - - void TSubTaskScanDirectories::Load(const ISerializerPtr& spSerializer) - { - ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_scan")); - - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if(spRowReader->Next()) - m_tSubTaskStats.Load(spRowReader); - } - - void TSubTaskScanDirectories::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if(rColumns.IsEmpty()) - TSubTaskStatsInfo::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskScanDirectory.cpp +/// @date 2010/09/18 +/// @brief Contains implementation of classes related to scan directory subtask. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskScanDirectory.h" +#include "TSubTaskContext.h" +#include "TTaskConfiguration.h" +#include "IFeedbackHandler.h" +#include "TBasePathData.h" +#include "TWorkerThreadController.h" +#include "TTaskLocalStats.h" +#include "TFileInfoArray.h" +#include "TFileInfo.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TPathContainer.h" +#include "TScopedRunningTimeTracker.h" +#include "TFeedbackHandlerWrapper.h" +#include "TBufferSizes.h" +#include "TFileException.h" +#include "TFilesystemFeedbackWrapper.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskScanDirectories + TSubTaskScanDirectories::TSubTaskScanDirectories(TSubTaskContext& rContext) : + TSubTaskBase(rContext), + m_tSubTaskStats(eSubOperation_Scanning), + m_spLog(std::make_unique(rContext.GetLogFileData(), L"ST-ScanDirs")) + { + } + + TSubTaskScanDirectories::~TSubTaskScanDirectories() + { + } + + void TSubTaskScanDirectories::Reset() + { + m_tSubTaskStats.Clear(); + } + + void TSubTaskScanDirectories::InitBeforeExec() + { + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + + file_count_t fcSize = spBasePaths->GetCount(); + file_count_t fcIndex = m_tSubTaskStats.GetCurrentIndex(); + + if(fcIndex >= fcSize) + fcIndex = 0; + + if(fcSize > 0) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + m_tSubTaskStats.SetCurrentPath(spBasePath->GetSrcPath().ToString()); + } + else + m_tSubTaskStats.SetCurrentPath(TString()); + } + + TSubTaskScanDirectories::ESubOperationResult TSubTaskScanDirectories::Exec(const IFeedbackHandlerPtr& spFeedback) + { + TScopedRunningTimeTracker guard(m_tSubTaskStats); + TFeedbackHandlerWrapperPtr spFeedbackHandler(std::make_shared(spFeedback, guard)); + + // log + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const TConfig& rConfig = GetContext().GetConfig(); + const TFileFiltersArray& rafFilters = GetContext().GetFilters(); + IFilesystemPtr spFilesystem = GetContext().GetLocalFilesystem(); + + TFilesystemFeedbackWrapper tFilesystemFBWrapper(spFeedbackHandler, spFilesystem, GetContext().GetLogFileData(), rThreadController); + + LOG_INFO(m_spLog) << _T("Searching for files..."); + + // reset progress + rFilesCache.SetComplete(false); + + // new stats + m_tSubTaskStats.SetCurrentBufferIndex(TBufferSizes::eBuffer_Default); + m_tSubTaskStats.SetTotalCount(spBasePaths->GetCount()); + m_tSubTaskStats.SetProcessedCount(0); + m_tSubTaskStats.SetTotalSize(0); + m_tSubTaskStats.SetProcessedSize(0); + m_tSubTaskStats.SetCurrentPath(TString()); + + // delete the content of rFilesCache + rFilesCache.Clear(); + + bool bIgnoreDirs = GetTaskPropValue(rConfig); + bool bForceDirectories = GetTaskPropValue(rConfig); + + // add everything + TString strFormat; + + file_count_t fcSize = spBasePaths->GetCount(); + // NOTE: in theory, we should resume the scanning, but in practice we are always restarting scanning if interrupted. + file_count_t fcIndex = 0; // m_tSubTaskStats.GetCurrentIndex() + for (; fcIndex < fcSize; fcIndex++) + { + TBasePathDataPtr spBasePath = spBasePaths->GetAt(fcIndex); + TSmartPath pathCurrent = spBasePath->GetSrcPath(); + + m_tSubTaskStats.SetCurrentIndex(fcIndex); + + // new stats + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(pathCurrent.ToString()); + + TFileInfoPtr spFileInfo(std::make_shared()); + + // check if we want to process this path at all (might be already fast moved) + if (spBasePath->GetSkipFurtherProcessing()) + continue; + + // try to get some info about the input path; let user know if the path does not exist. + ESubOperationResult eResult = tFilesystemFBWrapper.GetFileInfoFB(pathCurrent, spFileInfo, spBasePath); + if (eResult == TSubTaskBase::eSubResult_SkipFile) + continue; + else if (eResult != TSubTaskBase::eSubResult_Continue) + return eResult; + + // log + strFormat = _T("Adding file/folder (clipboard) : %path ..."); + strFormat.Replace(_T("%path"), pathCurrent.ToString()); + LOG_INFO(m_spLog) << strFormat.c_str(); + + // add if needed + if (spFileInfo->IsDirectory()) + { + // add if folder's aren't ignored + if (!bIgnoreDirs && !bForceDirectories) + { + // add directory info; it is not to be filtered with afFilters + rFilesCache.AddFileInfo(spFileInfo); + + // log + strFormat = _T("Added folder %path"); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + LOG_INFO(m_spLog) << strFormat.c_str(); + } + + // don't add folder contents when moving inside one disk boundary + // log + strFormat = _T("Recursing folder %path"); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + LOG_INFO(m_spLog) << strFormat.c_str(); + + ScanDirectory(spFileInfo->GetFullFilePath(), spBasePath, true, !bIgnoreDirs || bForceDirectories, rafFilters); + + // check for kill need + if (rThreadController.KillRequested()) + { + // log + LOG_INFO(m_spLog) << _T("Kill request while adding data to files array (RecurseDirectories)"); + rFilesCache.Clear(); + return eSubResult_KillRequest; + } + } + else + { + // add file info if passes filters + if (rafFilters.Match(spFileInfo)) + rFilesCache.AddFileInfo(spFileInfo); + + // log + strFormat = _T("Added file %path"); + strFormat.Replace(_T("%path"), spFileInfo->GetFullFilePath().ToString()); + LOG_INFO(m_spLog) << strFormat.c_str(); + } + } + + // update stats + m_tSubTaskStats.SetCurrentIndex(fcIndex); + m_tSubTaskStats.SetProcessedCount(fcIndex); + m_tSubTaskStats.SetCurrentPath(TString()); + + rFilesCache.SetComplete(true); + + // log + LOG_INFO(m_spLog) << _T("Searching for files finished"); + + return eSubResult_Continue; + } + + void TSubTaskScanDirectories::GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const + { + m_tSubTaskStats.GetSnapshot(spStats); + } + + int TSubTaskScanDirectories::ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, + bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters) + { + TFileInfoArray& rFilesCache = GetContext().GetFilesCache(); + TWorkerThreadController& rThreadController = GetContext().GetThreadController(); + TBasePathDataContainerPtr spBasePaths = GetContext().GetBasePaths(); + const IFilesystemPtr& spFilesystem = GetContext().GetLocalFilesystem(); + + IFilesystemFindPtr spFinder = spFilesystem->CreateFinderObject(pathDirName, PathFromString(_T("*"))); + TFileInfoPtr spFileInfo(std::make_shared()); + + while (spFinder->FindNext(spFileInfo)) + { + if (rThreadController.KillRequested()) + break; + + if (!spFileInfo->IsDirectory()) + { + if (afFilters.Match(spFileInfo)) + { + spFileInfo->SetParentObject(spBasePathData); + rFilesCache.AddFileInfo(spFileInfo); + spFileInfo = std::make_shared(); + } + } + else + { + TSmartPath pathCurrent = spFileInfo->GetFullFilePath(); + if (bIncludeDirs) + { + spFileInfo->SetParentObject(spBasePathData); + rFilesCache.AddFileInfo(spFileInfo); + spFileInfo = std::make_shared(); + } + + if (bRecurse) + ScanDirectory(pathCurrent, spBasePathData, bRecurse, bIncludeDirs, afFilters); + } + } + + return 0; + } + void TSubTaskScanDirectories::Store(const ISerializerPtr& spSerializer) const + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_scan")); + + InitColumns(spContainer); + + ISerializerRowData& rRow = spContainer->GetRow(0, m_tSubTaskStats.WasAdded()); + + m_tSubTaskStats.Store(rRow); + } + + void TSubTaskScanDirectories::Load(const ISerializerPtr& spSerializer) + { + ISerializerContainerPtr spContainer = spSerializer->GetContainer(_T("subtask_scan")); + + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if(spRowReader->Next()) + m_tSubTaskStats.Load(spRowReader); + } + + void TSubTaskScanDirectories::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if(rColumns.IsEmpty()) + TSubTaskStatsInfo::InitColumns(rColumns); + } +} Index: src/libchcore/TSubTaskScanDirectory.h =================================================================== diff -u -r12b36349f6214befeace08efa9acc7e03be0d847 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskScanDirectory.h (.../TSubTaskScanDirectory.h) (revision 12b36349f6214befeace08efa9acc7e03be0d847) +++ src/libchcore/TSubTaskScanDirectory.h (.../TSubTaskScanDirectory.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,70 +1,70 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskScanDirectory.h -/// @date 2010/09/18 -/// @brief Contains declarations of classes responsible for directory scan sub-operation. -// ============================================================================ -#ifndef __TSUBTASKSCANDIRECTORY_H__ -#define __TSUBTASKSCANDIRECTORY_H__ - -#include "libchcore.h" -#include "TSubTaskBase.h" -#include "TPath.h" -#include "TBasePathData.h" -#include "../liblogger/TLogger.h" - -namespace chcore -{ - class TFileFiltersArray; - - /////////////////////////////////////////////////////////////////////////// - // TSubTaskScanDirectories - - class LIBCHCORE_API TSubTaskScanDirectories : public TSubTaskBase - { - public: - explicit TSubTaskScanDirectories(TSubTaskContext& rContext); - virtual ~TSubTaskScanDirectories(); - - virtual void Reset(); - - virtual void InitBeforeExec() override; - virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; - virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Scanning; } - - virtual void Store(const ISerializerPtr& spSerializer) const; - virtual void Load(const ISerializerPtr& spSerializer); - - virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; - - private: - int ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, - bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters); - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - TSubTaskStatsInfo m_tSubTaskStats; - logger::TLoggerPtr m_spLog; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskScanDirectory.h +/// @date 2010/09/18 +/// @brief Contains declarations of classes responsible for directory scan sub-operation. +// ============================================================================ +#ifndef __TSUBTASKSCANDIRECTORY_H__ +#define __TSUBTASKSCANDIRECTORY_H__ + +#include "libchcore.h" +#include "TSubTaskBase.h" +#include "TPath.h" +#include "TBasePathData.h" +#include "../liblogger/TLogger.h" + +namespace chcore +{ + class TFileFiltersArray; + + /////////////////////////////////////////////////////////////////////////// + // TSubTaskScanDirectories + + class LIBCHCORE_API TSubTaskScanDirectories : public TSubTaskBase + { + public: + explicit TSubTaskScanDirectories(TSubTaskContext& rContext); + virtual ~TSubTaskScanDirectories(); + + virtual void Reset(); + + virtual void InitBeforeExec() override; + virtual ESubOperationResult Exec(const IFeedbackHandlerPtr& spFeedbackHandler) override; + virtual ESubOperationType GetSubOperationType() const override { return eSubOperation_Scanning; } + + virtual void Store(const ISerializerPtr& spSerializer) const; + virtual void Load(const ISerializerPtr& spSerializer); + + virtual void GetStatsSnapshot(TSubTaskStatsSnapshotPtr& spStats) const; + + private: + int ScanDirectory(TSmartPath pathDirName, const TBasePathDataPtr& spBasePathData, + bool bRecurse, bool bIncludeDirs, const TFileFiltersArray& afFilters); + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + TSubTaskStatsInfo m_tSubTaskStats; + logger::TLoggerPtr m_spLog; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TSubTaskStatsInfo.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskStatsInfo.cpp (.../TSubTaskStatsInfo.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TSubTaskStatsInfo.cpp (.../TSubTaskStatsInfo.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,524 +1,524 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskStatsInfo.cpp -/// @date 2012/02/22 -/// @brief Contains definition of class responsible for tracking stats for subtasks. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskStatsInfo.h" -#include -#include "TSubTaskStatsSnapshot.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "SerializerDataTypes.h" -#include - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////// - // class TSubTaskStatsInfo - - TSubTaskStatsInfo::TSubTaskStatsInfo(ESubOperationType eSubTaskType) : - m_eSubOperationType(eSubTaskType), - m_bSubTaskIsRunning(m_setModifications, false), - m_ullTotalSize(m_setModifications, 0), - m_ullProcessedSize(m_setModifications, 0), - m_fcTotalCount(m_setModifications, 0), - m_fcProcessedCount(m_setModifications, 0), - m_iCurrentBufferIndex(m_setModifications, 0), - m_strCurrentPath(m_setModifications), - m_tSizeSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), - m_tCountSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), - m_ullCurrentItemProcessedSize(m_setModifications, 0), - m_ullCurrentItemTotalSize(m_setModifications, 0), - m_tTimer(m_setModifications), - m_bIsInitialized(m_setModifications, false), - m_fcCurrentIndex(m_setModifications, 0), - m_bCurrentItemSilentResume(m_setModifications, false) - { - m_setModifications[eMod_Added] = true; - } - - void TSubTaskStatsInfo::Clear() - { - m_bSubTaskIsRunning = false; - m_ullTotalSize = 0; - m_ullProcessedSize = 0; - m_fcTotalCount = 0UL; - m_fcProcessedCount = 0UL; - m_iCurrentBufferIndex = 0; - m_strCurrentPath.Modify().Clear(); - m_tTimer.Modify().Reset(); - m_tSizeSpeed.Modify().Clear(); - m_tCountSpeed.Modify().Clear(); - m_ullCurrentItemProcessedSize = 0; - m_ullCurrentItemTotalSize = 0; - m_bIsInitialized = false; - m_fcCurrentIndex = 0UL; - m_bCurrentItemSilentResume = false; - } - - void TSubTaskStatsInfo::GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const - { - if (!spStatsSnapshot) - throw TCoreException(eErr_InvalidArgument, L"spStatsSnapshot", LOCATION); - - spStatsSnapshot->Clear(); - - boost::upgrade_lock lock(m_lock); - if (m_bSubTaskIsRunning) - UpdateTime(lock); - - spStatsSnapshot->SetRunning(m_bSubTaskIsRunning); - spStatsSnapshot->SetProcessedCount(m_fcProcessedCount); - spStatsSnapshot->SetTotalCount(m_fcTotalCount); - spStatsSnapshot->SetProcessedSize(m_ullProcessedSize); - spStatsSnapshot->SetTotalSize(m_ullTotalSize); - spStatsSnapshot->SetCurrentBufferIndex(m_iCurrentBufferIndex); - spStatsSnapshot->SetCurrentPath(m_strCurrentPath); - spStatsSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); - spStatsSnapshot->SetSizeSpeed(m_tSizeSpeed.Get().GetSpeed()); - spStatsSnapshot->SetCountSpeed(m_tCountSpeed.Get().GetSpeed()); - spStatsSnapshot->SetCurrentItemProcessedSize(m_ullCurrentItemProcessedSize); - spStatsSnapshot->SetCurrentItemTotalSize(m_ullCurrentItemTotalSize); - spStatsSnapshot->SetSubOperationType(m_eSubOperationType); - spStatsSnapshot->SetCurrentIndex(m_fcCurrentIndex); - } - - // is running? - void TSubTaskStatsInfo::MarkAsRunning() - { - boost::unique_lock lock(m_lock); - m_bSubTaskIsRunning = true; - } - - void TSubTaskStatsInfo::MarkAsNotRunning() - { - boost::unique_lock lock(m_lock); - m_bSubTaskIsRunning = false; - } - - void TSubTaskStatsInfo::IncreaseProcessedCount(file_count_t fcIncreaseBy) - { - boost::unique_lock lock(m_lock); - m_fcProcessedCount.Modify() += fcIncreaseBy; - - m_tCountSpeed.Modify().AddSample(fcIncreaseBy, m_tTimer.Modify().Tick()); - - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if (m_fcProcessedCount > m_fcTotalCount) - throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded the total", LOCATION); - } - - void TSubTaskStatsInfo::SetProcessedCount(file_count_t fcProcessedCount) - { - boost::unique_lock lock(m_lock); - - m_tCountSpeed.Modify().AddSample(fcProcessedCount > m_fcProcessedCount ? fcProcessedCount - m_fcProcessedCount : 0, m_tTimer.Modify().Tick()); - - m_fcProcessedCount = fcProcessedCount; - - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if (m_fcProcessedCount > m_fcTotalCount) - throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total", LOCATION); - } - - void TSubTaskStatsInfo::SetTotalCount(file_count_t fcCount) - { - boost::unique_lock lock(m_lock); - m_fcTotalCount = fcCount; - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if (m_fcProcessedCount > m_fcTotalCount) - throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total", LOCATION); - } - - file_count_t TSubTaskStatsInfo::GetTotalCount() const - { - boost::shared_lock lock(m_lock); - return m_fcTotalCount; - } - - void TSubTaskStatsInfo::IncreaseProcessedSize(unsigned long long ullIncreaseBy) - { - boost::unique_lock lock(m_lock); - m_ullProcessedSize.Modify() += ullIncreaseBy; - - m_tSizeSpeed.Modify().AddSample(ullIncreaseBy, m_tTimer.Modify().Tick()); - - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); - } - - void TSubTaskStatsInfo::DecreaseProcessedSize(unsigned long long ullDecreaseBy) - { - boost::unique_lock lock(m_lock); - m_ullProcessedSize.Modify() -= ullDecreaseBy; - - // we didn't process anything here - hence the 0-sized sample - m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); - - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); - } - - void TSubTaskStatsInfo::SetProcessedSize(unsigned long long ullProcessedSize) - { - boost::unique_lock lock(m_lock); - - m_tSizeSpeed.Modify().AddSample(ullProcessedSize > m_ullProcessedSize ? ullProcessedSize - m_ullProcessedSize : 0, m_tTimer.Modify().Tick()); - - m_ullProcessedSize = ullProcessedSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); - } - - void TSubTaskStatsInfo::SetTotalSize(unsigned long long ullTotalSize) - { - boost::unique_lock lock(m_lock); - m_ullTotalSize = ullTotalSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); - } - - // current item - void TSubTaskStatsInfo::ResetCurrentItemProcessedSize() - { - boost::unique_lock lock(m_lock); - m_ullCurrentItemProcessedSize = 0; - } - - void TSubTaskStatsInfo::SetCurrentItemSizes(unsigned long long ullProcessedSize, unsigned long long ullTotalSize) - { - boost::unique_lock lock(m_lock); - - m_ullCurrentItemProcessedSize = ullProcessedSize; - m_ullCurrentItemTotalSize = ullTotalSize; - - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - throw TCoreException(eErr_InternalProblem, L"Current file processed size exceeded total size", LOCATION); - } - - bool TSubTaskStatsInfo::WillAdjustProcessedSizeExceedTotalSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize) - { - if (fsNewProcessedSize <= fsIncludedProcessedSize) - return false; - - boost::shared_lock lock(m_lock); - - file_size_t fsDiff = fsNewProcessedSize - fsIncludedProcessedSize; - if (m_ullCurrentItemProcessedSize.Get() + fsDiff > m_ullCurrentItemTotalSize.Get()) - return true; - - return false; - } - - void TSubTaskStatsInfo::AdjustProcessedSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize) - { - if (fsNewProcessedSize == fsIncludedProcessedSize) - return; - - file_size_t fsDiff = 0; - - boost::unique_lock lock(m_lock); - if (fsNewProcessedSize > fsIncludedProcessedSize) - { - fsDiff = fsNewProcessedSize - fsIncludedProcessedSize; - - m_ullCurrentItemProcessedSize.Modify() += fsDiff; - m_ullProcessedSize.Modify() += fsDiff; - - m_tSizeSpeed.Modify().AddSample(fsDiff, m_tTimer.Modify().Tick()); - } - else - { - fsDiff = fsIncludedProcessedSize - fsNewProcessedSize; - - m_ullCurrentItemProcessedSize.Modify() -= fsDiff; - m_ullProcessedSize.Modify() -= fsDiff; - - m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); - } - - VerifyProcessedVsTotal(); - } - - void TSubTaskStatsInfo::AdjustTotalSize(file_size_t fsIncludedSize, file_size_t fsNewSize) - { - if (fsIncludedSize == fsNewSize) - return; - - boost::unique_lock lock(m_lock); - if (fsNewSize > fsIncludedSize) - { - m_ullTotalSize.Modify() += fsNewSize - fsIncludedSize; - m_ullCurrentItemTotalSize.Modify() += fsNewSize - fsIncludedSize; - } - else - { - m_ullTotalSize.Modify() -= fsIncludedSize - fsNewSize; - m_ullCurrentItemTotalSize.Modify() -= fsIncludedSize - fsNewSize; - } - - VerifyProcessedVsTotal(); - } - - // buffer index - void TSubTaskStatsInfo::SetCurrentBufferIndex(int iCurrentIndex) - { - boost::unique_lock lock(m_lock); - m_iCurrentBufferIndex = iCurrentIndex; - } - // current path - void TSubTaskStatsInfo::SetCurrentPath(const TString& strPath) - { - boost::unique_lock lock(m_lock); - m_strCurrentPath = strPath; - } - - // time - void TSubTaskStatsInfo::EnableTimeTracking() - { - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Start(); - } - - void TSubTaskStatsInfo::DisableTimeTracking() - { - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Stop(); - } - - void TSubTaskStatsInfo::UpdateTime(boost::upgrade_lock& lock) const - { - boost::upgrade_to_unique_lock lock_upgraded(lock); - if (m_tTimer.Get().IsRunning()) - { - m_tTimer.Modify().Tick(); - m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); - m_tCountSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); - } - } - - void TSubTaskStatsInfo::Store(ISerializerRowData& rRowData) const - { - boost::shared_lock lock(m_lock); - - if (m_bSubTaskIsRunning.IsModified()) - rRowData.SetValue(_T("is_running"), m_bSubTaskIsRunning); - if (m_bIsInitialized.IsModified()) - rRowData.SetValue(_T("is_initialized"), m_bIsInitialized); - - if (m_ullTotalSize.IsModified()) - rRowData.SetValue(_T("total_size"), m_ullTotalSize); - - if (m_ullProcessedSize.IsModified()) - rRowData.SetValue(_T("processed_size"), m_ullProcessedSize); - if (m_tSizeSpeed.IsModified()) - rRowData.SetValue(_T("size_speed"), m_tSizeSpeed.Get().ToString()); - - if (m_fcTotalCount.IsModified()) - rRowData.SetValue(_T("total_count"), m_fcTotalCount); - if (m_fcProcessedCount.IsModified()) - rRowData.SetValue(_T("processed_count"), m_fcProcessedCount); - if (m_tCountSpeed.IsModified()) - rRowData.SetValue(_T("count_speed"), m_tCountSpeed.Get().ToString()); - - if (m_ullCurrentItemProcessedSize.IsModified()) - rRowData.SetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize); - if (m_ullCurrentItemTotalSize.IsModified()) - rRowData.SetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize); - if (m_bCurrentItemSilentResume.IsModified()) - rRowData.SetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume); - if (m_fcCurrentIndex.IsModified()) - rRowData.SetValue(_T("current_index"), m_fcCurrentIndex); - - if (m_tTimer.IsModified()) - rRowData.SetValue(_T("timer"), m_tTimer.Get().GetTotalTime()); - - if (m_iCurrentBufferIndex.IsModified()) - rRowData.SetValue(_T("buffer_index"), m_iCurrentBufferIndex); - - if (m_strCurrentPath.IsModified()) - rRowData.SetValue(_T("current_path"), m_strCurrentPath); - - m_setModifications.reset(); - } - - void TSubTaskStatsInfo::InitColumns(IColumnsDefinition& rColumnDefs) - { - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("is_running"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("is_initialized"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("total_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("processed_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("size_speed"), IColumnsDefinition::eType_string); - rColumnDefs.AddColumn(_T("total_count"), ColumnType::value); - rColumnDefs.AddColumn(_T("processed_count"), ColumnType::value); - rColumnDefs.AddColumn(_T("count_speed"), IColumnsDefinition::eType_string); - rColumnDefs.AddColumn(_T("ci_processed_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("ci_total_size"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("ci_silent_resume"), IColumnsDefinition::eType_bool); - rColumnDefs.AddColumn(_T("current_index"), ColumnType::value); - rColumnDefs.AddColumn(_T("timer"), IColumnsDefinition::eType_ulonglong); - rColumnDefs.AddColumn(_T("buffer_index"), IColumnsDefinition::eType_int); - rColumnDefs.AddColumn(_T("current_path"), IColumnsDefinition::eType_string); - } - - void TSubTaskStatsInfo::Load(const ISerializerRowReaderPtr& spRowReader) - { - boost::unique_lock lock(m_lock); - - spRowReader->GetValue(_T("is_running"), m_bSubTaskIsRunning.Modify()); - spRowReader->GetValue(_T("is_initialized"), m_bIsInitialized.Modify()); - - spRowReader->GetValue(_T("total_size"), m_ullTotalSize.Modify()); - - spRowReader->GetValue(_T("processed_size"), m_ullProcessedSize.Modify()); - - TString strSpeed; - spRowReader->GetValue(_T("size_speed"), strSpeed); - m_tSizeSpeed.Modify().FromString(strSpeed); - - spRowReader->GetValue(_T("total_count"), m_fcTotalCount.Modify()); - spRowReader->GetValue(_T("processed_count"), m_fcProcessedCount.Modify()); - - spRowReader->GetValue(_T("count_speed"), strSpeed); - m_tCountSpeed.Modify().FromString(strSpeed); - - spRowReader->GetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize.Modify()); - spRowReader->GetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize.Modify()); - spRowReader->GetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume.Modify()); - spRowReader->GetValue(_T("current_index"), m_fcCurrentIndex.Modify()); - - unsigned long long ullTimer = 0; - spRowReader->GetValue(_T("timer"), ullTimer); - m_tTimer.Modify().Init(ullTimer); - - spRowReader->GetValue(_T("buffer_index"), m_iCurrentBufferIndex.Modify()); - - spRowReader->GetValue(_T("current_path"), m_strCurrentPath.Modify()); - - m_setModifications.reset(); - } - - void TSubTaskStatsInfo::Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath) - { - boost::unique_lock lock(m_lock); - - if (m_bIsInitialized) - throw TCoreException(eErr_InvalidData, L"SubTask stats already initialized", LOCATION); - - m_iCurrentBufferIndex = iCurrentBufferIndex; - - m_fcTotalCount = fcTotalCount; - m_fcProcessedCount = fcProcessedCount; - - _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); - if (m_fcProcessedCount > m_fcTotalCount) - throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total count", LOCATION); - - m_ullTotalSize = ullTotalSize; - m_ullProcessedSize = ullProcessedSize; - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); - - m_strCurrentPath = strCurrentPath; - - m_bIsInitialized = true; - } - - bool TSubTaskStatsInfo::IsInitialized() const - { - boost::shared_lock lock(m_lock); - bool bInitialized = m_bIsInitialized; - - return bInitialized; - } - - void TSubTaskStatsInfo::SetCurrentIndex(file_count_t fcIndex) - { - boost::unique_lock lock(m_lock); - m_fcCurrentIndex = fcIndex; - } - - file_count_t TSubTaskStatsInfo::GetCurrentIndex() const - { - boost::shared_lock lock(m_lock); - return m_fcCurrentIndex.Get(); - } - - unsigned long long TSubTaskStatsInfo::GetCurrentItemProcessedSize() const - { - boost::shared_lock lock(m_lock); - return m_ullCurrentItemProcessedSize; - } - - unsigned long long TSubTaskStatsInfo::GetCurrentItemTotalSize() const - { - boost::shared_lock lock(m_lock); - return m_ullCurrentItemTotalSize; - } - - bool TSubTaskStatsInfo::CanCurrentItemSilentResume() const - { - boost::shared_lock lock(m_lock); - return m_bCurrentItemSilentResume; - } - - void TSubTaskStatsInfo::SetCurrentItemSilentResume(bool bEnableSilentResume) - { - boost::unique_lock lock(m_lock); - m_bCurrentItemSilentResume = bEnableSilentResume; - } - - bool TSubTaskStatsInfo::WasAdded() const - { - boost::shared_lock lock(m_lock); - return m_setModifications[eMod_Added]; - } - - void TSubTaskStatsInfo::IncreaseTotalSize(unsigned long long ullIncreaseBy) - { - boost::unique_lock lock(m_lock); - m_ullTotalSize = m_ullTotalSize + ullIncreaseBy; - } - - void TSubTaskStatsInfo::DecreaseTotalSize(unsigned long long ullDecreaseBy) - { - boost::unique_lock lock(m_lock); - m_ullTotalSize = m_ullTotalSize - ullDecreaseBy; - } - - void TSubTaskStatsInfo::VerifyProcessedVsTotal() - { - _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); - _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); - - if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) - throw TCoreException(eErr_InternalProblem, L"Current item processed size exceeded total size", LOCATION); - if (m_ullProcessedSize > m_ullTotalSize) - throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total", LOCATION); - } -} +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskStatsInfo.cpp +/// @date 2012/02/22 +/// @brief Contains definition of class responsible for tracking stats for subtasks. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskStatsInfo.h" +#include +#include "TSubTaskStatsSnapshot.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "SerializerDataTypes.h" +#include + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskStatsInfo + + TSubTaskStatsInfo::TSubTaskStatsInfo(ESubOperationType eSubTaskType) : + m_eSubOperationType(eSubTaskType), + m_bSubTaskIsRunning(m_setModifications, false), + m_ullTotalSize(m_setModifications, 0), + m_ullProcessedSize(m_setModifications, 0), + m_fcTotalCount(m_setModifications, 0), + m_fcProcessedCount(m_setModifications, 0), + m_iCurrentBufferIndex(m_setModifications, 0), + m_strCurrentPath(m_setModifications), + m_tSizeSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), + m_tCountSpeed(m_setModifications, DefaultSpeedTrackTime, DefaultSpeedSampleTime), + m_ullCurrentItemProcessedSize(m_setModifications, 0), + m_ullCurrentItemTotalSize(m_setModifications, 0), + m_tTimer(m_setModifications), + m_bIsInitialized(m_setModifications, false), + m_fcCurrentIndex(m_setModifications, 0), + m_bCurrentItemSilentResume(m_setModifications, false) + { + m_setModifications[eMod_Added] = true; + } + + void TSubTaskStatsInfo::Clear() + { + m_bSubTaskIsRunning = false; + m_ullTotalSize = 0; + m_ullProcessedSize = 0; + m_fcTotalCount = 0UL; + m_fcProcessedCount = 0UL; + m_iCurrentBufferIndex = 0; + m_strCurrentPath.Modify().Clear(); + m_tTimer.Modify().Reset(); + m_tSizeSpeed.Modify().Clear(); + m_tCountSpeed.Modify().Clear(); + m_ullCurrentItemProcessedSize = 0; + m_ullCurrentItemTotalSize = 0; + m_bIsInitialized = false; + m_fcCurrentIndex = 0UL; + m_bCurrentItemSilentResume = false; + } + + void TSubTaskStatsInfo::GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const + { + if (!spStatsSnapshot) + throw TCoreException(eErr_InvalidArgument, L"spStatsSnapshot", LOCATION); + + spStatsSnapshot->Clear(); + + boost::upgrade_lock lock(m_lock); + if (m_bSubTaskIsRunning) + UpdateTime(lock); + + spStatsSnapshot->SetRunning(m_bSubTaskIsRunning); + spStatsSnapshot->SetProcessedCount(m_fcProcessedCount); + spStatsSnapshot->SetTotalCount(m_fcTotalCount); + spStatsSnapshot->SetProcessedSize(m_ullProcessedSize); + spStatsSnapshot->SetTotalSize(m_ullTotalSize); + spStatsSnapshot->SetCurrentBufferIndex(m_iCurrentBufferIndex); + spStatsSnapshot->SetCurrentPath(m_strCurrentPath); + spStatsSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); + spStatsSnapshot->SetSizeSpeed(m_tSizeSpeed.Get().GetSpeed()); + spStatsSnapshot->SetCountSpeed(m_tCountSpeed.Get().GetSpeed()); + spStatsSnapshot->SetCurrentItemProcessedSize(m_ullCurrentItemProcessedSize); + spStatsSnapshot->SetCurrentItemTotalSize(m_ullCurrentItemTotalSize); + spStatsSnapshot->SetSubOperationType(m_eSubOperationType); + spStatsSnapshot->SetCurrentIndex(m_fcCurrentIndex); + } + + // is running? + void TSubTaskStatsInfo::MarkAsRunning() + { + boost::unique_lock lock(m_lock); + m_bSubTaskIsRunning = true; + } + + void TSubTaskStatsInfo::MarkAsNotRunning() + { + boost::unique_lock lock(m_lock); + m_bSubTaskIsRunning = false; + } + + void TSubTaskStatsInfo::IncreaseProcessedCount(file_count_t fcIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_fcProcessedCount.Modify() += fcIncreaseBy; + + m_tCountSpeed.Modify().AddSample(fcIncreaseBy, m_tTimer.Modify().Tick()); + + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded the total", LOCATION); + } + + void TSubTaskStatsInfo::SetProcessedCount(file_count_t fcProcessedCount) + { + boost::unique_lock lock(m_lock); + + m_tCountSpeed.Modify().AddSample(fcProcessedCount > m_fcProcessedCount ? fcProcessedCount - m_fcProcessedCount : 0, m_tTimer.Modify().Tick()); + + m_fcProcessedCount = fcProcessedCount; + + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total", LOCATION); + } + + void TSubTaskStatsInfo::SetTotalCount(file_count_t fcCount) + { + boost::unique_lock lock(m_lock); + m_fcTotalCount = fcCount; + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total", LOCATION); + } + + file_count_t TSubTaskStatsInfo::GetTotalCount() const + { + boost::shared_lock lock(m_lock); + return m_fcTotalCount; + } + + void TSubTaskStatsInfo::IncreaseProcessedSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullProcessedSize.Modify() += ullIncreaseBy; + + m_tSizeSpeed.Modify().AddSample(ullIncreaseBy, m_tTimer.Modify().Tick()); + + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); + } + + void TSubTaskStatsInfo::DecreaseProcessedSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullProcessedSize.Modify() -= ullDecreaseBy; + + // we didn't process anything here - hence the 0-sized sample + m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); + + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); + } + + void TSubTaskStatsInfo::SetProcessedSize(unsigned long long ullProcessedSize) + { + boost::unique_lock lock(m_lock); + + m_tSizeSpeed.Modify().AddSample(ullProcessedSize > m_ullProcessedSize ? ullProcessedSize - m_ullProcessedSize : 0, m_tTimer.Modify().Tick()); + + m_ullProcessedSize = ullProcessedSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); + } + + void TSubTaskStatsInfo::SetTotalSize(unsigned long long ullTotalSize) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = ullTotalSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); + } + + // current item + void TSubTaskStatsInfo::ResetCurrentItemProcessedSize() + { + boost::unique_lock lock(m_lock); + m_ullCurrentItemProcessedSize = 0; + } + + void TSubTaskStatsInfo::SetCurrentItemSizes(unsigned long long ullProcessedSize, unsigned long long ullTotalSize) + { + boost::unique_lock lock(m_lock); + + m_ullCurrentItemProcessedSize = ullProcessedSize; + m_ullCurrentItemTotalSize = ullTotalSize; + + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + throw TCoreException(eErr_InternalProblem, L"Current file processed size exceeded total size", LOCATION); + } + + bool TSubTaskStatsInfo::WillAdjustProcessedSizeExceedTotalSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize) + { + if (fsNewProcessedSize <= fsIncludedProcessedSize) + return false; + + boost::shared_lock lock(m_lock); + + file_size_t fsDiff = fsNewProcessedSize - fsIncludedProcessedSize; + if (m_ullCurrentItemProcessedSize.Get() + fsDiff > m_ullCurrentItemTotalSize.Get()) + return true; + + return false; + } + + void TSubTaskStatsInfo::AdjustProcessedSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize) + { + if (fsNewProcessedSize == fsIncludedProcessedSize) + return; + + file_size_t fsDiff = 0; + + boost::unique_lock lock(m_lock); + if (fsNewProcessedSize > fsIncludedProcessedSize) + { + fsDiff = fsNewProcessedSize - fsIncludedProcessedSize; + + m_ullCurrentItemProcessedSize.Modify() += fsDiff; + m_ullProcessedSize.Modify() += fsDiff; + + m_tSizeSpeed.Modify().AddSample(fsDiff, m_tTimer.Modify().Tick()); + } + else + { + fsDiff = fsIncludedProcessedSize - fsNewProcessedSize; + + m_ullCurrentItemProcessedSize.Modify() -= fsDiff; + m_ullProcessedSize.Modify() -= fsDiff; + + m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Modify().Tick()); + } + + VerifyProcessedVsTotal(); + } + + void TSubTaskStatsInfo::AdjustTotalSize(file_size_t fsIncludedSize, file_size_t fsNewSize) + { + if (fsIncludedSize == fsNewSize) + return; + + boost::unique_lock lock(m_lock); + if (fsNewSize > fsIncludedSize) + { + m_ullTotalSize.Modify() += fsNewSize - fsIncludedSize; + m_ullCurrentItemTotalSize.Modify() += fsNewSize - fsIncludedSize; + } + else + { + m_ullTotalSize.Modify() -= fsIncludedSize - fsNewSize; + m_ullCurrentItemTotalSize.Modify() -= fsIncludedSize - fsNewSize; + } + + VerifyProcessedVsTotal(); + } + + // buffer index + void TSubTaskStatsInfo::SetCurrentBufferIndex(int iCurrentIndex) + { + boost::unique_lock lock(m_lock); + m_iCurrentBufferIndex = iCurrentIndex; + } + // current path + void TSubTaskStatsInfo::SetCurrentPath(const TString& strPath) + { + boost::unique_lock lock(m_lock); + m_strCurrentPath = strPath; + } + + // time + void TSubTaskStatsInfo::EnableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Start(); + } + + void TSubTaskStatsInfo::DisableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Stop(); + } + + void TSubTaskStatsInfo::UpdateTime(boost::upgrade_lock& lock) const + { + boost::upgrade_to_unique_lock lock_upgraded(lock); + if (m_tTimer.Get().IsRunning()) + { + m_tTimer.Modify().Tick(); + m_tSizeSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); + m_tCountSpeed.Modify().AddSample(0, m_tTimer.Get().GetLastTimestamp()); + } + } + + void TSubTaskStatsInfo::Store(ISerializerRowData& rRowData) const + { + boost::shared_lock lock(m_lock); + + if (m_bSubTaskIsRunning.IsModified()) + rRowData.SetValue(_T("is_running"), m_bSubTaskIsRunning); + if (m_bIsInitialized.IsModified()) + rRowData.SetValue(_T("is_initialized"), m_bIsInitialized); + + if (m_ullTotalSize.IsModified()) + rRowData.SetValue(_T("total_size"), m_ullTotalSize); + + if (m_ullProcessedSize.IsModified()) + rRowData.SetValue(_T("processed_size"), m_ullProcessedSize); + if (m_tSizeSpeed.IsModified()) + rRowData.SetValue(_T("size_speed"), m_tSizeSpeed.Get().ToString()); + + if (m_fcTotalCount.IsModified()) + rRowData.SetValue(_T("total_count"), m_fcTotalCount); + if (m_fcProcessedCount.IsModified()) + rRowData.SetValue(_T("processed_count"), m_fcProcessedCount); + if (m_tCountSpeed.IsModified()) + rRowData.SetValue(_T("count_speed"), m_tCountSpeed.Get().ToString()); + + if (m_ullCurrentItemProcessedSize.IsModified()) + rRowData.SetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize); + if (m_ullCurrentItemTotalSize.IsModified()) + rRowData.SetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize); + if (m_bCurrentItemSilentResume.IsModified()) + rRowData.SetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume); + if (m_fcCurrentIndex.IsModified()) + rRowData.SetValue(_T("current_index"), m_fcCurrentIndex); + + if (m_tTimer.IsModified()) + rRowData.SetValue(_T("timer"), m_tTimer.Get().GetTotalTime()); + + if (m_iCurrentBufferIndex.IsModified()) + rRowData.SetValue(_T("buffer_index"), m_iCurrentBufferIndex); + + if (m_strCurrentPath.IsModified()) + rRowData.SetValue(_T("current_path"), m_strCurrentPath); + + m_setModifications.reset(); + } + + void TSubTaskStatsInfo::InitColumns(IColumnsDefinition& rColumnDefs) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("is_running"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("is_initialized"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("total_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("processed_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("size_speed"), IColumnsDefinition::eType_string); + rColumnDefs.AddColumn(_T("total_count"), ColumnType::value); + rColumnDefs.AddColumn(_T("processed_count"), ColumnType::value); + rColumnDefs.AddColumn(_T("count_speed"), IColumnsDefinition::eType_string); + rColumnDefs.AddColumn(_T("ci_processed_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("ci_total_size"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("ci_silent_resume"), IColumnsDefinition::eType_bool); + rColumnDefs.AddColumn(_T("current_index"), ColumnType::value); + rColumnDefs.AddColumn(_T("timer"), IColumnsDefinition::eType_ulonglong); + rColumnDefs.AddColumn(_T("buffer_index"), IColumnsDefinition::eType_int); + rColumnDefs.AddColumn(_T("current_path"), IColumnsDefinition::eType_string); + } + + void TSubTaskStatsInfo::Load(const ISerializerRowReaderPtr& spRowReader) + { + boost::unique_lock lock(m_lock); + + spRowReader->GetValue(_T("is_running"), m_bSubTaskIsRunning.Modify()); + spRowReader->GetValue(_T("is_initialized"), m_bIsInitialized.Modify()); + + spRowReader->GetValue(_T("total_size"), m_ullTotalSize.Modify()); + + spRowReader->GetValue(_T("processed_size"), m_ullProcessedSize.Modify()); + + TString strSpeed; + spRowReader->GetValue(_T("size_speed"), strSpeed); + m_tSizeSpeed.Modify().FromString(strSpeed); + + spRowReader->GetValue(_T("total_count"), m_fcTotalCount.Modify()); + spRowReader->GetValue(_T("processed_count"), m_fcProcessedCount.Modify()); + + spRowReader->GetValue(_T("count_speed"), strSpeed); + m_tCountSpeed.Modify().FromString(strSpeed); + + spRowReader->GetValue(_T("ci_processed_size"), m_ullCurrentItemProcessedSize.Modify()); + spRowReader->GetValue(_T("ci_total_size"), m_ullCurrentItemTotalSize.Modify()); + spRowReader->GetValue(_T("ci_silent_resume"), m_bCurrentItemSilentResume.Modify()); + spRowReader->GetValue(_T("current_index"), m_fcCurrentIndex.Modify()); + + unsigned long long ullTimer = 0; + spRowReader->GetValue(_T("timer"), ullTimer); + m_tTimer.Modify().Init(ullTimer); + + spRowReader->GetValue(_T("buffer_index"), m_iCurrentBufferIndex.Modify()); + + spRowReader->GetValue(_T("current_path"), m_strCurrentPath.Modify()); + + m_setModifications.reset(); + } + + void TSubTaskStatsInfo::Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath) + { + boost::unique_lock lock(m_lock); + + if (m_bIsInitialized) + throw TCoreException(eErr_InvalidData, L"SubTask stats already initialized", LOCATION); + + m_iCurrentBufferIndex = iCurrentBufferIndex; + + m_fcTotalCount = fcTotalCount; + m_fcProcessedCount = fcProcessedCount; + + _ASSERTE(m_fcProcessedCount <= m_fcTotalCount); + if (m_fcProcessedCount > m_fcTotalCount) + throw TCoreException(eErr_InternalProblem, L"Count of processed files exceeded total count", LOCATION); + + m_ullTotalSize = ullTotalSize; + m_ullProcessedSize = ullProcessedSize; + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total size", LOCATION); + + m_strCurrentPath = strCurrentPath; + + m_bIsInitialized = true; + } + + bool TSubTaskStatsInfo::IsInitialized() const + { + boost::shared_lock lock(m_lock); + bool bInitialized = m_bIsInitialized; + + return bInitialized; + } + + void TSubTaskStatsInfo::SetCurrentIndex(file_count_t fcIndex) + { + boost::unique_lock lock(m_lock); + m_fcCurrentIndex = fcIndex; + } + + file_count_t TSubTaskStatsInfo::GetCurrentIndex() const + { + boost::shared_lock lock(m_lock); + return m_fcCurrentIndex.Get(); + } + + unsigned long long TSubTaskStatsInfo::GetCurrentItemProcessedSize() const + { + boost::shared_lock lock(m_lock); + return m_ullCurrentItemProcessedSize; + } + + unsigned long long TSubTaskStatsInfo::GetCurrentItemTotalSize() const + { + boost::shared_lock lock(m_lock); + return m_ullCurrentItemTotalSize; + } + + bool TSubTaskStatsInfo::CanCurrentItemSilentResume() const + { + boost::shared_lock lock(m_lock); + return m_bCurrentItemSilentResume; + } + + void TSubTaskStatsInfo::SetCurrentItemSilentResume(bool bEnableSilentResume) + { + boost::unique_lock lock(m_lock); + m_bCurrentItemSilentResume = bEnableSilentResume; + } + + bool TSubTaskStatsInfo::WasAdded() const + { + boost::shared_lock lock(m_lock); + return m_setModifications[eMod_Added]; + } + + void TSubTaskStatsInfo::IncreaseTotalSize(unsigned long long ullIncreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = m_ullTotalSize + ullIncreaseBy; + } + + void TSubTaskStatsInfo::DecreaseTotalSize(unsigned long long ullDecreaseBy) + { + boost::unique_lock lock(m_lock); + m_ullTotalSize = m_ullTotalSize - ullDecreaseBy; + } + + void TSubTaskStatsInfo::VerifyProcessedVsTotal() + { + _ASSERTE(m_ullCurrentItemProcessedSize <= m_ullCurrentItemTotalSize); + _ASSERTE(m_ullProcessedSize <= m_ullTotalSize); + + if (m_ullCurrentItemProcessedSize > m_ullCurrentItemTotalSize) + throw TCoreException(eErr_InternalProblem, L"Current item processed size exceeded total size", LOCATION); + if (m_ullProcessedSize > m_ullTotalSize) + throw TCoreException(eErr_InternalProblem, L"Size of processed files exceeded total", LOCATION); + } +} Index: src/libchcore/TSubTaskStatsInfo.h =================================================================== diff -u -r10d42e85d810f6da082cb2ce4415dcb72903410e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskStatsInfo.h (.../TSubTaskStatsInfo.h) (revision 10d42e85d810f6da082cb2ce4415dcb72903410e) +++ src/libchcore/TSubTaskStatsInfo.h (.../TSubTaskStatsInfo.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,190 +1,190 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskStatsInfo.h -/// @date 2012/02/22 -/// @brief Contains declaration of class responsible for tracking stats for subtasks. -// ============================================================================ -#ifndef __TSUBTASKSTATSINFO_H__ -#define __TSUBTASKSTATSINFO_H__ - -#include "TString.h" -#include "TSimpleTimer.h" -#include "TSpeedTracker.h" -#include "ESubTaskTypes.h" -#include "TSubTaskStatsSnapshot.h" -#include "ISerializerRowData.h" -#include "ISerializerRowReader.h" -#include "TSharedModificationTracker.h" -#include -#include "CommonDataTypes.h" -#include "IRunningTimeControl.h" - -namespace boost -{ - template class upgrade_lock; -} - -namespace chcore -{ - class TSubTaskStatsInfo; - class TSubTaskStatsSnapshot; - - class TSubTaskStatsInfo : public IRunningTimeControl - { - private: - static const unsigned long long DefaultSpeedTrackTime = 1000; // in miliseconds - static const unsigned long long DefaultSpeedSampleTime = 100; // in miliseconds - - public: - explicit TSubTaskStatsInfo(ESubOperationType eSubTaskType); - - void Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath); - void Clear(); - bool WasAdded() const; - - bool IsInitialized() const; - - void GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const; - - void IncreaseProcessedCount(file_count_t fcIncreaseBy); - void SetProcessedCount(file_count_t fcIndex); - - void SetTotalCount(file_count_t fcCount); - file_count_t GetTotalCount() const; - - // size stats - void IncreaseProcessedSize(unsigned long long ullIncreaseBy); - void DecreaseProcessedSize(unsigned long long ullDecreaseBy); - void SetProcessedSize(unsigned long long ullProcessedSize); - - void IncreaseTotalSize(unsigned long long ullIncreaseBy); - void DecreaseTotalSize(unsigned long long ullDecreaseBy); - void SetTotalSize(unsigned long long ullTotalSize); - - // current item - void SetCurrentItemSizes(unsigned long long ullProcessedSize, unsigned long long ullTotalSize); - void ResetCurrentItemProcessedSize(); - unsigned long long GetCurrentItemProcessedSize() const; - unsigned long long GetCurrentItemTotalSize() const; - - // current item processed and overall processed - bool WillAdjustProcessedSizeExceedTotalSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize); - void AdjustProcessedSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize); - void AdjustTotalSize(file_size_t fsIncludedSize, file_size_t fsNewSize); - - bool CanCurrentItemSilentResume() const; - void SetCurrentItemSilentResume(bool bEnableSilentResume); - - // current index - void SetCurrentIndex(file_count_t fcIndex); - file_count_t GetCurrentIndex() const; - - // buffer index - void SetCurrentBufferIndex(int iCurrentIndex); - - // current path - void SetCurrentPath(const TString& strPath); - - ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } - - // serialization - void Store(ISerializerRowData& rRowData) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); - - private: - TSubTaskStatsInfo(const TSubTaskStatsInfo&) = delete; - TSubTaskStatsInfo& operator=(const TSubTaskStatsInfo&) = delete; - - // is running? - virtual void MarkAsRunning() override; - virtual void MarkAsNotRunning() override; - - // time tracking - virtual void EnableTimeTracking() override; - virtual void DisableTimeTracking() override; - - void UpdateTime(boost::upgrade_lock& lock) const; - - void VerifyProcessedVsTotal(); - - private: - enum EModifications - { - eMod_Added = 0, - eMod_IsRunning, - eMod_TotalSize, - eMod_ProcessedSize, - eMod_SizeSpeed, - eMod_TotalCount, - eMod_ProcessedCount, - eMod_CountSpeed, - eMod_CurrentItemProcessedSize, - eMod_CurrentItemTotalSize, - eMod_Timer, - eMod_CurrentBufferIndex, - eMod_CurrentPath, - eMod_IsInitialized, - eMod_CurrentItemIndex, - eMod_CurrentItemCanResumeSilently, - - // last item - eMod_Last - }; - - typedef std::bitset Bitset; - mutable Bitset m_setModifications; - - TSharedModificationTracker m_bSubTaskIsRunning; - - TSharedModificationTracker m_ullTotalSize; - TSharedModificationTracker m_ullProcessedSize; - mutable TSharedModificationTracker m_tSizeSpeed; - - TSharedModificationTracker m_fcTotalCount; - TSharedModificationTracker m_fcProcessedCount; - mutable TSharedModificationTracker m_tCountSpeed; - - TSharedModificationTracker m_fcCurrentIndex; //?? - - TSharedModificationTracker m_ullCurrentItemProcessedSize; //?? - TSharedModificationTracker m_ullCurrentItemTotalSize; //?? - TSharedModificationTracker m_bCurrentItemSilentResume; //?? - - mutable TSharedModificationTracker m_tTimer; - - TSharedModificationTracker m_iCurrentBufferIndex; //?? - TSharedModificationTracker m_strCurrentPath; //?? - - TSharedModificationTracker m_bIsInitialized; - - const ESubOperationType m_eSubOperationType; - -#pragma warning(push) -#pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; -#pragma warning(pop) - - friend class TSubTaskProcessingGuard; - }; - - using TSubTaskStatsInfoPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskStatsInfo.h +/// @date 2012/02/22 +/// @brief Contains declaration of class responsible for tracking stats for subtasks. +// ============================================================================ +#ifndef __TSUBTASKSTATSINFO_H__ +#define __TSUBTASKSTATSINFO_H__ + +#include "TString.h" +#include "TSimpleTimer.h" +#include "TSpeedTracker.h" +#include "ESubTaskTypes.h" +#include "TSubTaskStatsSnapshot.h" +#include "ISerializerRowData.h" +#include "ISerializerRowReader.h" +#include "TSharedModificationTracker.h" +#include +#include "CommonDataTypes.h" +#include "IRunningTimeControl.h" + +namespace boost +{ + template class upgrade_lock; +} + +namespace chcore +{ + class TSubTaskStatsInfo; + class TSubTaskStatsSnapshot; + + class TSubTaskStatsInfo : public IRunningTimeControl + { + private: + static const unsigned long long DefaultSpeedTrackTime = 1000; // in miliseconds + static const unsigned long long DefaultSpeedSampleTime = 100; // in miliseconds + + public: + explicit TSubTaskStatsInfo(ESubOperationType eSubTaskType); + + void Init(int iCurrentBufferIndex, file_count_t fcTotalCount, file_count_t fcProcessedCount, unsigned long long ullTotalSize, unsigned long long ullProcessedSize, const TString& strCurrentPath); + void Clear(); + bool WasAdded() const; + + bool IsInitialized() const; + + void GetSnapshot(TSubTaskStatsSnapshotPtr& spStatsSnapshot) const; + + void IncreaseProcessedCount(file_count_t fcIncreaseBy); + void SetProcessedCount(file_count_t fcIndex); + + void SetTotalCount(file_count_t fcCount); + file_count_t GetTotalCount() const; + + // size stats + void IncreaseProcessedSize(unsigned long long ullIncreaseBy); + void DecreaseProcessedSize(unsigned long long ullDecreaseBy); + void SetProcessedSize(unsigned long long ullProcessedSize); + + void IncreaseTotalSize(unsigned long long ullIncreaseBy); + void DecreaseTotalSize(unsigned long long ullDecreaseBy); + void SetTotalSize(unsigned long long ullTotalSize); + + // current item + void SetCurrentItemSizes(unsigned long long ullProcessedSize, unsigned long long ullTotalSize); + void ResetCurrentItemProcessedSize(); + unsigned long long GetCurrentItemProcessedSize() const; + unsigned long long GetCurrentItemTotalSize() const; + + // current item processed and overall processed + bool WillAdjustProcessedSizeExceedTotalSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize); + void AdjustProcessedSize(file_size_t fsIncludedProcessedSize, file_size_t fsNewProcessedSize); + void AdjustTotalSize(file_size_t fsIncludedSize, file_size_t fsNewSize); + + bool CanCurrentItemSilentResume() const; + void SetCurrentItemSilentResume(bool bEnableSilentResume); + + // current index + void SetCurrentIndex(file_count_t fcIndex); + file_count_t GetCurrentIndex() const; + + // buffer index + void SetCurrentBufferIndex(int iCurrentIndex); + + // current path + void SetCurrentPath(const TString& strPath); + + ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } + + // serialization + void Store(ISerializerRowData& rRowData) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); + + private: + TSubTaskStatsInfo(const TSubTaskStatsInfo&) = delete; + TSubTaskStatsInfo& operator=(const TSubTaskStatsInfo&) = delete; + + // is running? + virtual void MarkAsRunning() override; + virtual void MarkAsNotRunning() override; + + // time tracking + virtual void EnableTimeTracking() override; + virtual void DisableTimeTracking() override; + + void UpdateTime(boost::upgrade_lock& lock) const; + + void VerifyProcessedVsTotal(); + + private: + enum EModifications + { + eMod_Added = 0, + eMod_IsRunning, + eMod_TotalSize, + eMod_ProcessedSize, + eMod_SizeSpeed, + eMod_TotalCount, + eMod_ProcessedCount, + eMod_CountSpeed, + eMod_CurrentItemProcessedSize, + eMod_CurrentItemTotalSize, + eMod_Timer, + eMod_CurrentBufferIndex, + eMod_CurrentPath, + eMod_IsInitialized, + eMod_CurrentItemIndex, + eMod_CurrentItemCanResumeSilently, + + // last item + eMod_Last + }; + + typedef std::bitset Bitset; + mutable Bitset m_setModifications; + + TSharedModificationTracker m_bSubTaskIsRunning; + + TSharedModificationTracker m_ullTotalSize; + TSharedModificationTracker m_ullProcessedSize; + mutable TSharedModificationTracker m_tSizeSpeed; + + TSharedModificationTracker m_fcTotalCount; + TSharedModificationTracker m_fcProcessedCount; + mutable TSharedModificationTracker m_tCountSpeed; + + TSharedModificationTracker m_fcCurrentIndex; //?? + + TSharedModificationTracker m_ullCurrentItemProcessedSize; //?? + TSharedModificationTracker m_ullCurrentItemTotalSize; //?? + TSharedModificationTracker m_bCurrentItemSilentResume; //?? + + mutable TSharedModificationTracker m_tTimer; + + TSharedModificationTracker m_iCurrentBufferIndex; //?? + TSharedModificationTracker m_strCurrentPath; //?? + + TSharedModificationTracker m_bIsInitialized; + + const ESubOperationType m_eSubOperationType; + +#pragma warning(push) +#pragma warning(disable: 4251) + mutable boost::shared_mutex m_lock; +#pragma warning(pop) + + friend class TSubTaskProcessingGuard; + }; + + using TSubTaskStatsInfoPtr = std::shared_ptr; +} + +#endif Index: src/libchcore/TSubTaskStatsSnapshot.cpp =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskStatsSnapshot.cpp (.../TSubTaskStatsSnapshot.cpp) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TSubTaskStatsSnapshot.cpp (.../TSubTaskStatsSnapshot.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,138 +1,138 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskStatsSnapshot.cpp -/// @date 2012/2/26 -/// @brief Contains class responsible for holding sub task stats. -// ============================================================================ -#include "stdafx.h" -#include "TSubTaskStatsSnapshot.h" -#include -#include "MathFunctions.h" -#include "TBufferSizes.h" -#include "EngineConstants.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////////////// - // class TSubTaskStats - TSubTaskStatsSnapshot::TSubTaskStatsSnapshot() : - m_bSubTaskIsRunning(false), - m_ullTotalSize(0), - m_ullProcessedSize(0), - m_fcTotalCount(0), - m_fcProcessedCount(0), - m_iCurrentBufferIndex(TBufferSizes::eBuffer_Default), - m_strCurrentPath(0), - m_timeElapsed(0), - m_dSizeSpeed(0), - m_dCountSpeed(0), - m_ullCurrentItemProcessedSize(0), - m_ullCurrentItemTotalSize(0), - m_eSubOperationType(eSubOperation_None), - m_fcCurrentIndex(0) - { - } - - void TSubTaskStatsSnapshot::Clear() - { - m_bSubTaskIsRunning = false; - m_ullTotalSize = 0; - m_ullProcessedSize = 0; - m_fcTotalCount = 0; - m_fcProcessedCount = 0; - m_iCurrentBufferIndex = TBufferSizes::eBuffer_Default; - m_strCurrentPath = 0; - m_timeElapsed = 0; - m_dSizeSpeed = 0; - m_dCountSpeed = 0; - m_ullCurrentItemProcessedSize = 0; - m_ullCurrentItemTotalSize = 0; - m_eSubOperationType = eSubOperation_None; - m_fcCurrentIndex = 0; - } - - double TSubTaskStatsSnapshot::CalculateProgress() const - { - // we're treating each of the items as 4k object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = AssumedFileMinDataSize * m_fcProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = AssumedFileMinDataSize * m_fcTotalCount + m_ullTotalSize; - - if (ullTotal != 0) - return Math::Div64(ullProcessed, ullTotal); - else - return 0.0; - } - - unsigned long long TSubTaskStatsSnapshot::GetEstimatedTotalTime() const - { - double dProgress = CalculateProgress(); - if (dProgress == 0.0) - return std::numeric_limits::max(); - else - return (unsigned long long)(m_timeElapsed * (1.0 / dProgress)); - } - - void TSubTaskStatsSnapshot::SetSizeSpeed(double dSizeSpeed) - { - m_dSizeSpeed = dSizeSpeed; - } - - double TSubTaskStatsSnapshot::GetSizeSpeed() const - { - if(m_bSubTaskIsRunning) - return m_dSizeSpeed; - - return 0.0; - } - - void TSubTaskStatsSnapshot::SetCountSpeed(double dCountSpeed) - { - m_dCountSpeed = dCountSpeed; - } - - double TSubTaskStatsSnapshot::GetCountSpeed() const - { - if(m_bSubTaskIsRunning) - return m_dCountSpeed; - return 0.0; - } - - double TSubTaskStatsSnapshot::GetAvgSizeSpeed() const - { - if (m_timeElapsed) - return Math::Div64(m_ullProcessedSize, m_timeElapsed / 1000.0); - else - return 0.0; - } - - double TSubTaskStatsSnapshot::GetAvgCountSpeed() const - { - if (m_timeElapsed) - return Math::Div64(m_fcProcessedCount, m_timeElapsed / 1000.0); - - return 0.0; - } - - double TSubTaskStatsSnapshot::GetCombinedProgress() const - { - return CalculateProgress(); - } -} +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskStatsSnapshot.cpp +/// @date 2012/2/26 +/// @brief Contains class responsible for holding sub task stats. +// ============================================================================ +#include "stdafx.h" +#include "TSubTaskStatsSnapshot.h" +#include +#include "MathFunctions.h" +#include "TBufferSizes.h" +#include "EngineConstants.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////////////// + // class TSubTaskStats + TSubTaskStatsSnapshot::TSubTaskStatsSnapshot() : + m_bSubTaskIsRunning(false), + m_ullTotalSize(0), + m_ullProcessedSize(0), + m_fcTotalCount(0), + m_fcProcessedCount(0), + m_iCurrentBufferIndex(TBufferSizes::eBuffer_Default), + m_strCurrentPath(0), + m_timeElapsed(0), + m_dSizeSpeed(0), + m_dCountSpeed(0), + m_ullCurrentItemProcessedSize(0), + m_ullCurrentItemTotalSize(0), + m_eSubOperationType(eSubOperation_None), + m_fcCurrentIndex(0) + { + } + + void TSubTaskStatsSnapshot::Clear() + { + m_bSubTaskIsRunning = false; + m_ullTotalSize = 0; + m_ullProcessedSize = 0; + m_fcTotalCount = 0; + m_fcProcessedCount = 0; + m_iCurrentBufferIndex = TBufferSizes::eBuffer_Default; + m_strCurrentPath = 0; + m_timeElapsed = 0; + m_dSizeSpeed = 0; + m_dCountSpeed = 0; + m_ullCurrentItemProcessedSize = 0; + m_ullCurrentItemTotalSize = 0; + m_eSubOperationType = eSubOperation_None; + m_fcCurrentIndex = 0; + } + + double TSubTaskStatsSnapshot::CalculateProgress() const + { + // we're treating each of the items as 4k object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = AssumedFileMinDataSize * m_fcProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = AssumedFileMinDataSize * m_fcTotalCount + m_ullTotalSize; + + if (ullTotal != 0) + return Math::Div64(ullProcessed, ullTotal); + else + return 0.0; + } + + unsigned long long TSubTaskStatsSnapshot::GetEstimatedTotalTime() const + { + double dProgress = CalculateProgress(); + if (dProgress == 0.0) + return std::numeric_limits::max(); + else + return (unsigned long long)(m_timeElapsed * (1.0 / dProgress)); + } + + void TSubTaskStatsSnapshot::SetSizeSpeed(double dSizeSpeed) + { + m_dSizeSpeed = dSizeSpeed; + } + + double TSubTaskStatsSnapshot::GetSizeSpeed() const + { + if(m_bSubTaskIsRunning) + return m_dSizeSpeed; + + return 0.0; + } + + void TSubTaskStatsSnapshot::SetCountSpeed(double dCountSpeed) + { + m_dCountSpeed = dCountSpeed; + } + + double TSubTaskStatsSnapshot::GetCountSpeed() const + { + if(m_bSubTaskIsRunning) + return m_dCountSpeed; + return 0.0; + } + + double TSubTaskStatsSnapshot::GetAvgSizeSpeed() const + { + if (m_timeElapsed) + return Math::Div64(m_ullProcessedSize, m_timeElapsed / 1000.0); + else + return 0.0; + } + + double TSubTaskStatsSnapshot::GetAvgCountSpeed() const + { + if (m_timeElapsed) + return Math::Div64(m_fcProcessedCount, m_timeElapsed / 1000.0); + + return 0.0; + } + + double TSubTaskStatsSnapshot::GetCombinedProgress() const + { + return CalculateProgress(); + } +} Index: src/libchcore/TSubTaskStatsSnapshot.h =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TSubTaskStatsSnapshot.h (.../TSubTaskStatsSnapshot.h) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TSubTaskStatsSnapshot.h (.../TSubTaskStatsSnapshot.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,131 +1,131 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TSubTaskStatsSnapshot.h -/// @date 2012/2/26 -/// @brief Contains class responsible for holding sub task stats. -// ============================================================================ -#ifndef __TSUBTASKSTATSSNAPSHOT_H__ -#define __TSUBTASKSTATSSNAPSHOT_H__ - -#include "libchcore.h" -#include "TString.h" -#include "ESubTaskTypes.h" -#include "CommonDataTypes.h" - -namespace chcore -{ - class LIBCHCORE_API TSubTaskStatsSnapshot - { - public: - TSubTaskStatsSnapshot(); - - void Clear(); - - // is running? - void SetRunning(bool bRunning) { m_bSubTaskIsRunning = bRunning; } - bool IsRunning() const { return m_bSubTaskIsRunning; } - - // count stats - void SetProcessedCount(file_count_t fcIndex) { m_fcProcessedCount = fcIndex; } - file_count_t GetProcessedCount() const { return m_fcProcessedCount; } - - void SetTotalCount(file_count_t fcCount) { m_fcTotalCount = fcCount; } - file_count_t GetTotalCount() const { return m_fcTotalCount; } - - // size stats - void SetProcessedSize(unsigned long long ullProcessedSize) { m_ullProcessedSize = ullProcessedSize; } - unsigned long long GetProcessedSize() const { return m_ullProcessedSize; } - - void SetTotalSize(unsigned long long ullTotalSize) { m_ullTotalSize = ullTotalSize; } - unsigned long long GetTotalSize() const { return m_ullTotalSize; } - - // current file - void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) { m_ullCurrentItemProcessedSize = ullProcessedSize; } - unsigned long long GetCurrentItemProcessedSize() const { return m_ullCurrentItemProcessedSize; } - - void SetCurrentItemTotalSize(unsigned long long ullTotalSize) { m_ullCurrentItemTotalSize = ullTotalSize; } - unsigned long long GetCurrentItemTotalSize() const { return m_ullCurrentItemTotalSize; } - - void SetCurrentIndex(file_count_t fcCurrentIndex) { m_fcCurrentIndex = fcCurrentIndex; } - file_count_t GetCurrentIndex() const { return m_fcCurrentIndex; } - - // progress in percent - double GetCombinedProgress() const; // returns progress [0.0, 1.0] - - // buffer index - void SetCurrentBufferIndex(int iCurrentIndex) { m_iCurrentBufferIndex = iCurrentIndex; } - int GetCurrentBufferIndex() const { return m_iCurrentBufferIndex; } - - // current path - void SetCurrentPath(const TString& strPath) { m_strCurrentPath = strPath; } - const TString& GetCurrentPath() const { return m_strCurrentPath; } - - // time - void SetTimeElapsed(unsigned long long timeElapsed) { m_timeElapsed = timeElapsed; } - unsigned long long GetTimeElapsed() { return m_timeElapsed; } - - // time estimations - unsigned long long GetEstimatedTotalTime() const; - - // speed - void SetSizeSpeed(double dSizeSpeed); - double GetSizeSpeed() const; - void SetCountSpeed(double dCountSpeed); - double GetCountSpeed() const; - - double GetAvgSizeSpeed() const; - double GetAvgCountSpeed() const; - - ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } - void SetSubOperationType(ESubOperationType val) { m_eSubOperationType = val; } - - private: - double CalculateProgress() const; - - private: - bool m_bSubTaskIsRunning; - - // subtask size and size speed per second - unsigned long long m_ullTotalSize; - unsigned long long m_ullProcessedSize; - double m_dSizeSpeed; - - // subtask count of items and its speed per second - file_count_t m_fcTotalCount; - file_count_t m_fcProcessedCount; - double m_dCountSpeed; - - // current item size - unsigned long long m_ullCurrentItemTotalSize; - unsigned long long m_ullCurrentItemProcessedSize; - file_count_t m_fcCurrentIndex; - - ESubOperationType m_eSubOperationType; - - int m_iCurrentBufferIndex; - - TString m_strCurrentPath; // currently processed path - - unsigned long long m_timeElapsed; // time really elapsed for the subtask - }; - - typedef std::shared_ptr TSubTaskStatsSnapshotPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TSubTaskStatsSnapshot.h +/// @date 2012/2/26 +/// @brief Contains class responsible for holding sub task stats. +// ============================================================================ +#ifndef __TSUBTASKSTATSSNAPSHOT_H__ +#define __TSUBTASKSTATSSNAPSHOT_H__ + +#include "libchcore.h" +#include "TString.h" +#include "ESubTaskTypes.h" +#include "CommonDataTypes.h" + +namespace chcore +{ + class LIBCHCORE_API TSubTaskStatsSnapshot + { + public: + TSubTaskStatsSnapshot(); + + void Clear(); + + // is running? + void SetRunning(bool bRunning) { m_bSubTaskIsRunning = bRunning; } + bool IsRunning() const { return m_bSubTaskIsRunning; } + + // count stats + void SetProcessedCount(file_count_t fcIndex) { m_fcProcessedCount = fcIndex; } + file_count_t GetProcessedCount() const { return m_fcProcessedCount; } + + void SetTotalCount(file_count_t fcCount) { m_fcTotalCount = fcCount; } + file_count_t GetTotalCount() const { return m_fcTotalCount; } + + // size stats + void SetProcessedSize(unsigned long long ullProcessedSize) { m_ullProcessedSize = ullProcessedSize; } + unsigned long long GetProcessedSize() const { return m_ullProcessedSize; } + + void SetTotalSize(unsigned long long ullTotalSize) { m_ullTotalSize = ullTotalSize; } + unsigned long long GetTotalSize() const { return m_ullTotalSize; } + + // current file + void SetCurrentItemProcessedSize(unsigned long long ullProcessedSize) { m_ullCurrentItemProcessedSize = ullProcessedSize; } + unsigned long long GetCurrentItemProcessedSize() const { return m_ullCurrentItemProcessedSize; } + + void SetCurrentItemTotalSize(unsigned long long ullTotalSize) { m_ullCurrentItemTotalSize = ullTotalSize; } + unsigned long long GetCurrentItemTotalSize() const { return m_ullCurrentItemTotalSize; } + + void SetCurrentIndex(file_count_t fcCurrentIndex) { m_fcCurrentIndex = fcCurrentIndex; } + file_count_t GetCurrentIndex() const { return m_fcCurrentIndex; } + + // progress in percent + double GetCombinedProgress() const; // returns progress [0.0, 1.0] + + // buffer index + void SetCurrentBufferIndex(int iCurrentIndex) { m_iCurrentBufferIndex = iCurrentIndex; } + int GetCurrentBufferIndex() const { return m_iCurrentBufferIndex; } + + // current path + void SetCurrentPath(const TString& strPath) { m_strCurrentPath = strPath; } + const TString& GetCurrentPath() const { return m_strCurrentPath; } + + // time + void SetTimeElapsed(unsigned long long timeElapsed) { m_timeElapsed = timeElapsed; } + unsigned long long GetTimeElapsed() { return m_timeElapsed; } + + // time estimations + unsigned long long GetEstimatedTotalTime() const; + + // speed + void SetSizeSpeed(double dSizeSpeed); + double GetSizeSpeed() const; + void SetCountSpeed(double dCountSpeed); + double GetCountSpeed() const; + + double GetAvgSizeSpeed() const; + double GetAvgCountSpeed() const; + + ESubOperationType GetSubOperationType() const { return m_eSubOperationType; } + void SetSubOperationType(ESubOperationType val) { m_eSubOperationType = val; } + + private: + double CalculateProgress() const; + + private: + bool m_bSubTaskIsRunning; + + // subtask size and size speed per second + unsigned long long m_ullTotalSize; + unsigned long long m_ullProcessedSize; + double m_dSizeSpeed; + + // subtask count of items and its speed per second + file_count_t m_fcTotalCount; + file_count_t m_fcProcessedCount; + double m_dCountSpeed; + + // current item size + unsigned long long m_ullCurrentItemTotalSize; + unsigned long long m_ullCurrentItemProcessedSize; + file_count_t m_fcCurrentIndex; + + ESubOperationType m_eSubOperationType; + + int m_iCurrentBufferIndex; + + TString m_strCurrentPath; // currently processed path + + unsigned long long m_timeElapsed; // time really elapsed for the subtask + }; + + typedef std::shared_ptr TSubTaskStatsSnapshotPtr; +} + +#endif Index: src/libchcore/TTaskBaseData.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskBaseData.cpp (.../TTaskBaseData.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TTaskBaseData.cpp (.../TTaskBaseData.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,140 +1,140 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TTaskBaseData.h" -#include "ISerializerRowData.h" -#include "ISerializerContainer.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -namespace chcore -{ - TTaskBaseData::TTaskBaseData() : - m_strTaskName(m_setChanges), - m_eCurrentState(m_setChanges), - m_pathLog(m_setChanges), - m_pathDestinationPath(m_setChanges) - { - m_setChanges[eMod_Added] = true; - } - - TTaskBaseData::~TTaskBaseData() - { - } - - TString TTaskBaseData::GetTaskName() const - { - return m_strTaskName; - } - - void TTaskBaseData::SetTaskName(const TString& strTaskName) - { - m_strTaskName = strTaskName; - } - - ETaskCurrentState TTaskBaseData::GetCurrentState() const - { - return m_eCurrentState; - } - - void TTaskBaseData::SetCurrentState(ETaskCurrentState eCurrentState) - { - m_eCurrentState = eCurrentState; - } - - TSmartPath TTaskBaseData::GetLogPath() const - { - return m_pathLog; - } - - void TTaskBaseData::SetLogPath(const TSmartPath& pathLog) - { - m_pathLog = pathLog; - } - - TSmartPath TTaskBaseData::GetDestinationPath() const - { - return m_pathDestinationPath; - } - - void TTaskBaseData::SetDestinationPath(const TSmartPath& pathDst) - { - m_pathDestinationPath = pathDst; - } - - void TTaskBaseData::Store(const ISerializerContainerPtr& spContainer) const - { - InitColumns(spContainer); - - // base data - if (m_setChanges.any()) - { - bool bAdded = m_setChanges[eMod_Added]; - - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - - if (bAdded || m_setChanges[eMod_TaskName]) - rRow.SetValue(_T("name"), m_strTaskName); - - if (bAdded || m_setChanges[eMod_LogPath]) - rRow.SetValue(_T("log_path"), m_pathLog); - - if (bAdded || m_setChanges[eMod_CurrentState]) - rRow.SetValue(_T("current_state"), m_eCurrentState); - - if (bAdded || m_setChanges[eMod_DstPath]) - rRow.SetValue(_T("destination_path"), m_pathDestinationPath); - - m_setChanges.reset(); - } - } - - void TTaskBaseData::Load(const ISerializerContainerPtr& spContainer) - { - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - bool bResult = spRowReader->Next(); - if (bResult) - { - spRowReader->GetValue(_T("name"), m_strTaskName.Modify()); - spRowReader->GetValue(_T("log_path"), m_pathLog.Modify()); - spRowReader->GetValue(_T("current_state"), *(int*)(ETaskCurrentState*)&m_eCurrentState.Modify()); - spRowReader->GetValue(_T("destination_path"), m_pathDestinationPath.Modify()); - } - else - throw TCoreException(eErr_SerializeLoadError, L"Reading next row failed", LOCATION); - - m_setChanges.reset(); - } - - void TTaskBaseData::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); - rColumns.AddColumn(_T("log_path"), IColumnsDefinition::eType_path); - rColumns.AddColumn(_T("current_state"), IColumnsDefinition::eType_int); - rColumns.AddColumn(_T("destination_path"), IColumnsDefinition::eType_path); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TTaskBaseData.h" +#include "ISerializerRowData.h" +#include "ISerializerContainer.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +namespace chcore +{ + TTaskBaseData::TTaskBaseData() : + m_strTaskName(m_setChanges), + m_eCurrentState(m_setChanges), + m_pathLog(m_setChanges), + m_pathDestinationPath(m_setChanges) + { + m_setChanges[eMod_Added] = true; + } + + TTaskBaseData::~TTaskBaseData() + { + } + + TString TTaskBaseData::GetTaskName() const + { + return m_strTaskName; + } + + void TTaskBaseData::SetTaskName(const TString& strTaskName) + { + m_strTaskName = strTaskName; + } + + ETaskCurrentState TTaskBaseData::GetCurrentState() const + { + return m_eCurrentState; + } + + void TTaskBaseData::SetCurrentState(ETaskCurrentState eCurrentState) + { + m_eCurrentState = eCurrentState; + } + + TSmartPath TTaskBaseData::GetLogPath() const + { + return m_pathLog; + } + + void TTaskBaseData::SetLogPath(const TSmartPath& pathLog) + { + m_pathLog = pathLog; + } + + TSmartPath TTaskBaseData::GetDestinationPath() const + { + return m_pathDestinationPath; + } + + void TTaskBaseData::SetDestinationPath(const TSmartPath& pathDst) + { + m_pathDestinationPath = pathDst; + } + + void TTaskBaseData::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); + + // base data + if (m_setChanges.any()) + { + bool bAdded = m_setChanges[eMod_Added]; + + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); + + if (bAdded || m_setChanges[eMod_TaskName]) + rRow.SetValue(_T("name"), m_strTaskName); + + if (bAdded || m_setChanges[eMod_LogPath]) + rRow.SetValue(_T("log_path"), m_pathLog); + + if (bAdded || m_setChanges[eMod_CurrentState]) + rRow.SetValue(_T("current_state"), m_eCurrentState); + + if (bAdded || m_setChanges[eMod_DstPath]) + rRow.SetValue(_T("destination_path"), m_pathDestinationPath); + + m_setChanges.reset(); + } + } + + void TTaskBaseData::Load(const ISerializerContainerPtr& spContainer) + { + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + bool bResult = spRowReader->Next(); + if (bResult) + { + spRowReader->GetValue(_T("name"), m_strTaskName.Modify()); + spRowReader->GetValue(_T("log_path"), m_pathLog.Modify()); + spRowReader->GetValue(_T("current_state"), *(int*)(ETaskCurrentState*)&m_eCurrentState.Modify()); + spRowReader->GetValue(_T("destination_path"), m_pathDestinationPath.Modify()); + } + else + throw TCoreException(eErr_SerializeLoadError, L"Reading next row failed", LOCATION); + + m_setChanges.reset(); + } + + void TTaskBaseData::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("name"), IColumnsDefinition::eType_string); + rColumns.AddColumn(_T("log_path"), IColumnsDefinition::eType_path); + rColumns.AddColumn(_T("current_state"), IColumnsDefinition::eType_int); + rColumns.AddColumn(_T("destination_path"), IColumnsDefinition::eType_path); + } + } +} Index: src/libchcore/TTaskBaseData.h =================================================================== diff -u -r6f8b891b60eb0f33199fd29db75d4d9f4a22c248 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskBaseData.h (.../TTaskBaseData.h) (revision 6f8b891b60eb0f33199fd29db75d4d9f4a22c248) +++ src/libchcore/TTaskBaseData.h (.../TTaskBaseData.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,84 +1,84 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TTASKBASEDATA_H__ -#define __TTASKBASEDATA_H__ - -#include "libchcore.h" -#include "ISerializerRowData.h" -#include -#include "TSharedModificationTracker.h" -#include "ETaskCurrentState.h" - -namespace chcore -{ - class LIBCHCORE_API TTaskBaseData - { -/* - private: - TTaskBaseData(const TTaskBaseData&); - TTaskBaseData& operator=(const TTaskBaseData&); -*/ - - public: - TTaskBaseData(); - ~TTaskBaseData(); - - TString GetTaskName() const; - void SetTaskName(const TString& strTaskName); - - ETaskCurrentState GetCurrentState() const; - void SetCurrentState(ETaskCurrentState eCurrentState); - - TSmartPath GetLogPath() const; - void SetLogPath(const TSmartPath& pathLog); - - TSmartPath GetDestinationPath() const; - void SetDestinationPath(const TSmartPath& pathDst); - - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - private: - enum EModifications - { - eMod_Added, - eMod_TaskName, - eMod_CurrentState, - eMod_LogPath, - eMod_DstPath, - - eMod_Last - }; - -#pragma warning(push) -#pragma warning(disable: 4251) - typedef std::bitset ModBitSet; - mutable ModBitSet m_setChanges; - - TSharedModificationTracker m_strTaskName; - TSharedModificationTracker m_eCurrentState; // current state of processing this task represents - TSharedModificationTracker m_pathLog; - TSharedModificationTracker m_pathDestinationPath; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TTASKBASEDATA_H__ +#define __TTASKBASEDATA_H__ + +#include "libchcore.h" +#include "ISerializerRowData.h" +#include +#include "TSharedModificationTracker.h" +#include "ETaskCurrentState.h" + +namespace chcore +{ + class LIBCHCORE_API TTaskBaseData + { +/* + private: + TTaskBaseData(const TTaskBaseData&); + TTaskBaseData& operator=(const TTaskBaseData&); +*/ + + public: + TTaskBaseData(); + ~TTaskBaseData(); + + TString GetTaskName() const; + void SetTaskName(const TString& strTaskName); + + ETaskCurrentState GetCurrentState() const; + void SetCurrentState(ETaskCurrentState eCurrentState); + + TSmartPath GetLogPath() const; + void SetLogPath(const TSmartPath& pathLog); + + TSmartPath GetDestinationPath() const; + void SetDestinationPath(const TSmartPath& pathDst); + + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + private: + enum EModifications + { + eMod_Added, + eMod_TaskName, + eMod_CurrentState, + eMod_LogPath, + eMod_DstPath, + + eMod_Last + }; + +#pragma warning(push) +#pragma warning(disable: 4251) + typedef std::bitset ModBitSet; + mutable ModBitSet m_setChanges; + + TSharedModificationTracker m_strTaskName; + TSharedModificationTracker m_eCurrentState; // current state of processing this task represents + TSharedModificationTracker m_pathLog; + TSharedModificationTracker m_pathDestinationPath; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TTaskConfigBufferSizes.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskConfigBufferSizes.cpp (.../TTaskConfigBufferSizes.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TTaskConfigBufferSizes.cpp (.../TTaskConfigBufferSizes.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,45 +1,45 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TTaskConfigBufferSizes.h" - -namespace chcore -{ - TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig) - { - return TBufferSizes(GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig), - GetTaskPropValue(rConfig)); - } - - void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes) - { - SetTaskPropValue(rConfig, rBufferSizes.IsOnlyDefault()); - SetTaskPropValue(rConfig, rBufferSizes.GetBufferCount()); - SetTaskPropValue(rConfig, rBufferSizes.GetDefaultSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetOneDiskSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetTwoDisksSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetCDSize()); - SetTaskPropValue(rConfig, rBufferSizes.GetLANSize()); - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TTaskConfigBufferSizes.h" + +namespace chcore +{ + TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig) + { + return TBufferSizes(GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig), + GetTaskPropValue(rConfig)); + } + + void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes) + { + SetTaskPropValue(rConfig, rBufferSizes.IsOnlyDefault()); + SetTaskPropValue(rConfig, rBufferSizes.GetBufferCount()); + SetTaskPropValue(rConfig, rBufferSizes.GetDefaultSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetOneDiskSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetTwoDisksSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetCDSize()); + SetTaskPropValue(rConfig, rBufferSizes.GetLANSize()); + } +} Index: src/libchcore/TTaskConfigBufferSizes.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskConfigBufferSizes.h (.../TTaskConfigBufferSizes.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TTaskConfigBufferSizes.h (.../TTaskConfigBufferSizes.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,33 +1,33 @@ -// ============================================================================ -// Copyright (C) 2001-2014 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TTASKCONFIGBUFFERSIZES_H__ -#define __TTASKCONFIGBUFFERSIZES_H__ - -#include "libchcore.h" -#include "TBufferSizes.h" -#include "TConfig.h" -#include "TTaskConfiguration.h" - -namespace chcore -{ - LIBCHCORE_API TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig); - LIBCHCORE_API void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes); -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2014 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TTASKCONFIGBUFFERSIZES_H__ +#define __TTASKCONFIGBUFFERSIZES_H__ + +#include "libchcore.h" +#include "TBufferSizes.h" +#include "TConfig.h" +#include "TTaskConfiguration.h" + +namespace chcore +{ + LIBCHCORE_API TBufferSizes GetTaskPropBufferSizes(const TConfig& rConfig); + LIBCHCORE_API void SetTaskPropBufferSizes(TConfig& rConfig, const TBufferSizes& rBufferSizes); +} + +#endif Index: src/libchcore/TTaskConfigTracker.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskConfigTracker.cpp (.../TTaskConfigTracker.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TTaskConfigTracker.cpp (.../TTaskConfigTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,256 +1,256 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskConfigTracker.cpp -/// @date 2010/10/04 -/// @brief Contains implementation of TTaskConfigTracker class. -// ============================================================================ -#include "stdafx.h" -#include "TTaskConfigTracker.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include "TStringSet.h" -#include - -namespace chcore -{ - TOptionsSet& TOptionsSet::operator%(ETaskOptions eOption) - { - m_setOptions.insert(eOption); - - return *this; - } - - std::set& TOptionsSet::Get() - { - return m_setOptions; - } - - TTaskConfigTracker::TTaskConfigTracker() - { - } - - TTaskConfigTracker::~TTaskConfigTracker() - { - } - - bool TTaskConfigTracker::IsModified() const - { - boost::shared_lock lock(m_lock); - return !m_setModified.empty(); - } - - bool TTaskConfigTracker::IsModified(ETaskOptions eOption) const - { - boost::shared_lock lock(m_lock); - return m_setModified.find(eOption) != m_setModified.end(); - } - - bool TTaskConfigTracker::IsModified(TOptionsSet setOptions) const - { - boost::shared_lock lock(m_lock); - - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - - return !setCommon.empty(); - } - - bool TTaskConfigTracker::IsModified(ETaskOptions eOption, bool bResetModificationState) - { - boost::upgrade_lock lock(m_lock); - - std::set::iterator iterOption = m_setModified.find(eOption); - bool bModified = (iterOption != m_setModified.end()); - if (bModified && bResetModificationState) - { - boost::upgrade_to_unique_lock upgraded_lock(lock); - m_setModified.erase(iterOption); - } - - return bModified; - } - - bool TTaskConfigTracker::IsModified(TOptionsSet setOptions, bool bResetModificationState) - { - boost::upgrade_lock lock(m_lock); - - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - - bool bModified = !setCommon.empty(); - if (bModified && bResetModificationState) - { - boost::upgrade_to_unique_lock upgraded_lock(lock); - std::set::iterator iterOption; - for(ETaskOptions eOption : setCommon) - { - iterOption = m_setModified.find(eOption); - if (iterOption != m_setModified.end()) - m_setModified.erase(iterOption); - } - } - - return bModified; - } - - void TTaskConfigTracker::AddModified(const TString& strModified) - { - ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); - - boost::unique_lock lock(m_lock); - - m_setModified.insert(eOption); - } - - void TTaskConfigTracker::AddModified(ETaskOptions eModified) - { - boost::unique_lock lock(m_lock); - m_setModified.insert(eModified); - } - - void TTaskConfigTracker::AddModified(TOptionsSet setOptions) - { - boost::unique_lock lock(m_lock); - m_setModified.insert(setOptions.Get().begin(), setOptions.Get().end()); - } - - void TTaskConfigTracker::AddModified(const TStringSet& setModified) - { - TStringSet::const_iterator iterBegin = setModified.Begin(); - TStringSet::const_iterator iterEnd = setModified.End(); - - for (; iterBegin != iterEnd; ++iterBegin) - { - AddModified(*iterBegin); - } - } - - void TTaskConfigTracker::AddModified(const std::set& setModified) - { - boost::unique_lock lock(m_lock); - - m_setModified.insert(setModified.begin(), setModified.end()); - } - - void TTaskConfigTracker::RemoveModification(ETaskOptions eModified) - { - boost::upgrade_lock lock(m_lock); - std::set::iterator iterOption = m_setModified.find(eModified); - if (iterOption != m_setModified.end()) - { - boost::upgrade_to_unique_lock upgraded_lock(lock); - m_setModified.erase(iterOption); - } - } - - void TTaskConfigTracker::RemoveModificationSet(TOptionsSet setOptions) - { - boost::unique_lock lock(m_lock); - - std::set setCommon; - std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); - - std::set::iterator iterOption; - for(ETaskOptions eOption : setCommon) - { - iterOption = m_setModified.find(eOption); - if (iterOption != m_setModified.end()) - m_setModified.erase(iterOption); - } - } - - void TTaskConfigTracker::RemoveModification(const TString& strModified) - { - ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); - RemoveModification(eOption); - } - - void TTaskConfigTracker::Clear() - { - boost::unique_lock lock(m_lock); - m_setModified.clear(); - } - - void TTaskConfigTracker::NotificationProc(const TStringSet& setModifications, void* pParam) - { - if (!pParam) - throw TCoreException(eErr_InvalidArgument, L"pParam", LOCATION); - - TTaskConfigTracker* pTracker = (TTaskConfigTracker*)pParam; - pTracker->AddModified(setModifications); - } - - ETaskOptions TTaskConfigTracker::GetOptionFromString(const TString& strOption) - { - if (strOption == TaskPropData::GetPropertyName()) - return eTO_UseOnlyDefaultBuffer; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DefaultBufferSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_OneDiskBufferSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_TwoDisksBufferSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_CDBufferSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_LANBufferSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DisableBuffering; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DisableBufferingMinSize; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_BufferQueueDepth; - - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_SetDestinationAttributes; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_SetDestinationDateTime; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_ProtectReadOnlyFiles; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_ScanDirectoriesBeforeBlocking; - else if(strOption == TaskPropData::GetPropertyName()) - return eTO_FastMoveBeforeBlocking; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_ThreadPriority; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DisablePriorityBoost; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_DeleteInSeparateSubTask; - - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_CreateEmptyFiles; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_CreateDirectoriesRelativeToRoot; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_IgnoreDirectories; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_AlternateFilenameFormatString_AfterFirst; - else if (strOption == TaskPropData::GetPropertyName()) - return eTO_AlternateFilenameFormatString_First; - else - { - BOOST_ASSERT(false); // unhandled case - throw TCoreException(eErr_UnhandledCase, L"Option name not supported", LOCATION); - } - - // add new elements before this one - BOOST_STATIC_ASSERT(eTO_Last == eTO_AlternateFilenameFormatString_AfterFirst + 1); - } -} +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskConfigTracker.cpp +/// @date 2010/10/04 +/// @brief Contains implementation of TTaskConfigTracker class. +// ============================================================================ +#include "stdafx.h" +#include "TTaskConfigTracker.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include "TStringSet.h" +#include + +namespace chcore +{ + TOptionsSet& TOptionsSet::operator%(ETaskOptions eOption) + { + m_setOptions.insert(eOption); + + return *this; + } + + std::set& TOptionsSet::Get() + { + return m_setOptions; + } + + TTaskConfigTracker::TTaskConfigTracker() + { + } + + TTaskConfigTracker::~TTaskConfigTracker() + { + } + + bool TTaskConfigTracker::IsModified() const + { + boost::shared_lock lock(m_lock); + return !m_setModified.empty(); + } + + bool TTaskConfigTracker::IsModified(ETaskOptions eOption) const + { + boost::shared_lock lock(m_lock); + return m_setModified.find(eOption) != m_setModified.end(); + } + + bool TTaskConfigTracker::IsModified(TOptionsSet setOptions) const + { + boost::shared_lock lock(m_lock); + + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); + + return !setCommon.empty(); + } + + bool TTaskConfigTracker::IsModified(ETaskOptions eOption, bool bResetModificationState) + { + boost::upgrade_lock lock(m_lock); + + std::set::iterator iterOption = m_setModified.find(eOption); + bool bModified = (iterOption != m_setModified.end()); + if (bModified && bResetModificationState) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + m_setModified.erase(iterOption); + } + + return bModified; + } + + bool TTaskConfigTracker::IsModified(TOptionsSet setOptions, bool bResetModificationState) + { + boost::upgrade_lock lock(m_lock); + + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); + + bool bModified = !setCommon.empty(); + if (bModified && bResetModificationState) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + std::set::iterator iterOption; + for(ETaskOptions eOption : setCommon) + { + iterOption = m_setModified.find(eOption); + if (iterOption != m_setModified.end()) + m_setModified.erase(iterOption); + } + } + + return bModified; + } + + void TTaskConfigTracker::AddModified(const TString& strModified) + { + ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); + + boost::unique_lock lock(m_lock); + + m_setModified.insert(eOption); + } + + void TTaskConfigTracker::AddModified(ETaskOptions eModified) + { + boost::unique_lock lock(m_lock); + m_setModified.insert(eModified); + } + + void TTaskConfigTracker::AddModified(TOptionsSet setOptions) + { + boost::unique_lock lock(m_lock); + m_setModified.insert(setOptions.Get().begin(), setOptions.Get().end()); + } + + void TTaskConfigTracker::AddModified(const TStringSet& setModified) + { + TStringSet::const_iterator iterBegin = setModified.Begin(); + TStringSet::const_iterator iterEnd = setModified.End(); + + for (; iterBegin != iterEnd; ++iterBegin) + { + AddModified(*iterBegin); + } + } + + void TTaskConfigTracker::AddModified(const std::set& setModified) + { + boost::unique_lock lock(m_lock); + + m_setModified.insert(setModified.begin(), setModified.end()); + } + + void TTaskConfigTracker::RemoveModification(ETaskOptions eModified) + { + boost::upgrade_lock lock(m_lock); + std::set::iterator iterOption = m_setModified.find(eModified); + if (iterOption != m_setModified.end()) + { + boost::upgrade_to_unique_lock upgraded_lock(lock); + m_setModified.erase(iterOption); + } + } + + void TTaskConfigTracker::RemoveModificationSet(TOptionsSet setOptions) + { + boost::unique_lock lock(m_lock); + + std::set setCommon; + std::set_intersection(setOptions.Get().begin(), setOptions.Get().end(), m_setModified.begin(), m_setModified.end(), std::inserter(setCommon, setCommon.begin())); + + std::set::iterator iterOption; + for(ETaskOptions eOption : setCommon) + { + iterOption = m_setModified.find(eOption); + if (iterOption != m_setModified.end()) + m_setModified.erase(iterOption); + } + } + + void TTaskConfigTracker::RemoveModification(const TString& strModified) + { + ETaskOptions eOption = TTaskConfigTracker::GetOptionFromString(strModified); + RemoveModification(eOption); + } + + void TTaskConfigTracker::Clear() + { + boost::unique_lock lock(m_lock); + m_setModified.clear(); + } + + void TTaskConfigTracker::NotificationProc(const TStringSet& setModifications, void* pParam) + { + if (!pParam) + throw TCoreException(eErr_InvalidArgument, L"pParam", LOCATION); + + TTaskConfigTracker* pTracker = (TTaskConfigTracker*)pParam; + pTracker->AddModified(setModifications); + } + + ETaskOptions TTaskConfigTracker::GetOptionFromString(const TString& strOption) + { + if (strOption == TaskPropData::GetPropertyName()) + return eTO_UseOnlyDefaultBuffer; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DefaultBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_OneDiskBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_TwoDisksBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CDBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_LANBufferSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisableBuffering; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisableBufferingMinSize; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_BufferQueueDepth; + + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_SetDestinationAttributes; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_SetDestinationDateTime; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_ProtectReadOnlyFiles; + else if(strOption == TaskPropData::GetPropertyName()) + return eTO_ScanDirectoriesBeforeBlocking; + else if(strOption == TaskPropData::GetPropertyName()) + return eTO_FastMoveBeforeBlocking; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_ThreadPriority; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DisablePriorityBoost; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_DeleteInSeparateSubTask; + + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CreateEmptyFiles; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_CreateDirectoriesRelativeToRoot; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_IgnoreDirectories; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_AlternateFilenameFormatString_AfterFirst; + else if (strOption == TaskPropData::GetPropertyName()) + return eTO_AlternateFilenameFormatString_First; + else + { + BOOST_ASSERT(false); // unhandled case + throw TCoreException(eErr_UnhandledCase, L"Option name not supported", LOCATION); + } + + // add new elements before this one + BOOST_STATIC_ASSERT(eTO_Last == eTO_AlternateFilenameFormatString_AfterFirst + 1); + } +} Index: src/libchcore/TTaskConfigTracker.h =================================================================== diff -u -r9d7b3c6ff296b15b68a94fdc8bfb23aad016f57a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskConfigTracker.h (.../TTaskConfigTracker.h) (revision 9d7b3c6ff296b15b68a94fdc8bfb23aad016f57a) +++ src/libchcore/TTaskConfigTracker.h (.../TTaskConfigTracker.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,82 +1,82 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TConfigTracker.h -/// @date 2010/10/04 -/// @brief Contains declaration of the TTaskConfigTracker class. -// ============================================================================ -#ifndef __TCONFIGTRACKER_H__ -#define __TCONFIGTRACKER_H__ - -#include "libchcore.h" -#include "TTaskConfiguration.h" - -namespace chcore -{ - class LIBCHCORE_API TOptionsSet - { - public: - TOptionsSet& operator%(ETaskOptions eOption); - - std::set& Get(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::set m_setOptions; -#pragma warning(pop) - }; - - class LIBCHCORE_API TTaskConfigTracker - { - public: - TTaskConfigTracker(); - ~TTaskConfigTracker(); - - bool IsModified() const; - bool IsModified(ETaskOptions eOption) const; - bool IsModified(TOptionsSet setOptions) const; - bool IsModified(ETaskOptions eOption, bool bResetModificationState); - bool IsModified(TOptionsSet setOptions, bool bResetModificationState); - - void AddModified(const TString& strModified); - void AddModified(ETaskOptions eModified); - void AddModified(TOptionsSet setOptions); - void AddModified(const TStringSet& setModified); - void AddModified(const std::set& setModified); - - void RemoveModification(ETaskOptions eModified); - void RemoveModificationSet(TOptionsSet setOptions); - void RemoveModification(const TString& strModified); - void Clear(); - - static void NotificationProc(const TStringSet& setModifications, void* pParam); - - protected: - static ETaskOptions GetOptionFromString(const TString& strOption); - - protected: -#pragma warning(push) -#pragma warning(disable: 4251) - std::set m_setModified; - mutable boost::shared_mutex m_lock; -#pragma warning(pop) - }; -} - -#endif // __TCONFIGTRACKER_H__ +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TConfigTracker.h +/// @date 2010/10/04 +/// @brief Contains declaration of the TTaskConfigTracker class. +// ============================================================================ +#ifndef __TCONFIGTRACKER_H__ +#define __TCONFIGTRACKER_H__ + +#include "libchcore.h" +#include "TTaskConfiguration.h" + +namespace chcore +{ + class LIBCHCORE_API TOptionsSet + { + public: + TOptionsSet& operator%(ETaskOptions eOption); + + std::set& Get(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::set m_setOptions; +#pragma warning(pop) + }; + + class LIBCHCORE_API TTaskConfigTracker + { + public: + TTaskConfigTracker(); + ~TTaskConfigTracker(); + + bool IsModified() const; + bool IsModified(ETaskOptions eOption) const; + bool IsModified(TOptionsSet setOptions) const; + bool IsModified(ETaskOptions eOption, bool bResetModificationState); + bool IsModified(TOptionsSet setOptions, bool bResetModificationState); + + void AddModified(const TString& strModified); + void AddModified(ETaskOptions eModified); + void AddModified(TOptionsSet setOptions); + void AddModified(const TStringSet& setModified); + void AddModified(const std::set& setModified); + + void RemoveModification(ETaskOptions eModified); + void RemoveModificationSet(TOptionsSet setOptions); + void RemoveModification(const TString& strModified); + void Clear(); + + static void NotificationProc(const TStringSet& setModifications, void* pParam); + + protected: + static ETaskOptions GetOptionFromString(const TString& strOption); + + protected: +#pragma warning(push) +#pragma warning(disable: 4251) + std::set m_setModified; + mutable boost::shared_mutex m_lock; +#pragma warning(pop) + }; +} + +#endif // __TCONFIGTRACKER_H__ Index: src/libchcore/TTaskConfiguration.h =================================================================== diff -u -rdcc6234ed612a75910b8900704c9d564096a037a -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskConfiguration.h (.../TTaskConfiguration.h) (revision dcc6234ed612a75910b8900704c9d564096a037a) +++ src/libchcore/TTaskConfiguration.h (.../TTaskConfiguration.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,178 +1,178 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskConfiguration.h -/// @date 2010/09/18 -/// @brief Contains class responsible for keeping task configuration. -// ============================================================================ -#ifndef __TTASKCONFIGURATION_H__ -#define __TTASKCONFIGURATION_H__ - -#include "TConfig.h" - -namespace chcore -{ - enum ETaskOptions - { - eTO_UseOnlyDefaultBuffer, - eTO_DefaultBufferSize, - eTO_OneDiskBufferSize, - eTO_TwoDisksBufferSize, - eTO_CDBufferSize, - eTO_LANBufferSize, - eTO_DisableBuffering, - eTO_DisableBufferingMinSize, - eTO_BufferQueueDepth, - - eTO_FeedbackGeneralFileError, - eTO_FeedbackFileAlreadyExists, - eTO_FeedbackNotEnoughSpace, - - eTO_SetDestinationAttributes, - eTO_SetDestinationDateTime, - eTO_ProtectReadOnlyFiles, - eTO_ScanDirectoriesBeforeBlocking, - eTO_FastMoveBeforeBlocking, - eTO_ThreadPriority, - eTO_DisablePriorityBoost, - eTO_DeleteInSeparateSubTask, - - eTO_CreateEmptyFiles, - eTO_CreateDirectoriesRelativeToRoot, - eTO_IgnoreDirectories, - - eTO_AlternateFilenameFormatString_First, - eTO_AlternateFilenameFormatString_AfterFirst, - - // add new elements before this one - eTO_Last - }; - - ///////////////////////////////////////////////////////////////////////////////////////////// - // Properties definitions - - template struct TaskPropData; - -#define TASK_PROPERTY(enum_id, val_type, val_name, def_value)\ - template<> struct TaskPropData\ -{\ - typedef val_type value_type;\ -\ - static value_type GetDefaultValue() { return def_value; }\ - static const wchar_t* GetPropertyName() { return val_name; }\ - static void ValidateRange(value_type&) {}\ -} - -#define TASK_PROPERTY_MINMAX(enum_id, val_type, val_name, def_value, min_val, max_val)\ - template<> struct TaskPropData\ -{\ - typedef val_type value_type;\ -\ - static value_type GetDefaultValue() { return def_value; }\ - static const wchar_t* GetPropertyName() { return val_name; }\ - static void ValidateRange(value_type& rValue)\ - {\ - if(rValue < (min_val))\ - rValue = (min_val);\ - else if(rValue > (max_val))\ - rValue = (max_val);\ - }\ -} - -#define TASK_PROPERTY_MIN(enum_id, val_type, val_name, def_value, min_val)\ - template<> struct TaskPropData\ -{\ - typedef val_type value_type;\ -\ - static value_type GetDefaultValue() { return def_value; }\ - static const wchar_t* GetPropertyName() { return val_name; }\ - static void ValidateRange(value_type& rValue)\ - {\ - if(rValue < (min_val))\ - rValue = (min_val);\ - }\ -} - - // Buffer settings - TASK_PROPERTY(eTO_UseOnlyDefaultBuffer, bool, _T("Buffer.UseOnlyDefaultBuffer"), false); - TASK_PROPERTY_MIN(eTO_DefaultBufferSize, unsigned int, _T("Buffer.DefaultBufferSize"), 131072, 1); - TASK_PROPERTY_MIN(eTO_OneDiskBufferSize, unsigned int, _T("Buffer.OnePhysicalDiskSize"), 2097152, 1); - TASK_PROPERTY_MIN(eTO_TwoDisksBufferSize, unsigned int, _T("Buffer.TwoPhysicalDisksSize"), 131072, 1); - TASK_PROPERTY_MIN(eTO_CDBufferSize, unsigned int, _T("Buffer.CDSize"), 131072, 1); - TASK_PROPERTY_MIN(eTO_LANBufferSize, unsigned int, _T("Buffer.LANSize"), 131072, 1); - TASK_PROPERTY_MINMAX(eTO_BufferQueueDepth, unsigned int, _T("Buffer.QueueDepth"), 8, 1, 1000); - - TASK_PROPERTY(eTO_DisableBuffering, bool, _T("Operation.Buffering.DisableBufferingForLargeFiles"), true); - TASK_PROPERTY_MIN(eTO_DisableBufferingMinSize, int, _T("Operation.Buffering.MinSizeOfFileToDisableBuffering"), 0, 1); - - TASK_PROPERTY(eTO_SetDestinationAttributes, bool, _T("Operation.SetDestinationAttributes"), true); - TASK_PROPERTY(eTO_SetDestinationDateTime, bool, _T("Operation.SetDestinationTime"), true); - TASK_PROPERTY(eTO_ProtectReadOnlyFiles, bool, _T("Operation.ProtectReadOnlyFiles"), false); - TASK_PROPERTY(eTO_ScanDirectoriesBeforeBlocking, bool, _T("Operation.ScanForFilesBeforeBlocking"), false); - TASK_PROPERTY(eTO_FastMoveBeforeBlocking, bool, _T("Operation.FastMoveBeforeBlocking"), false); - - // Thread settings - TASK_PROPERTY(eTO_ThreadPriority, int, _T("Operation.Thread.Priority"), THREAD_PRIORITY_NORMAL); - TASK_PROPERTY(eTO_DisablePriorityBoost, bool, _T("Operation.Thread.DisablePriorityBoost"), false); - - // Operation settings - TASK_PROPERTY(eTO_DeleteInSeparateSubTask, bool, _T("Operation.DeleteFilesInSeparateOperation"), true); - - TASK_PROPERTY(eTO_CreateEmptyFiles, bool, _T("Operation.CreateEmptyFiles"), false); - TASK_PROPERTY(eTO_CreateDirectoriesRelativeToRoot, bool, _T("Operation.CreateDirectoriesRelativeToRoot"), false); - TASK_PROPERTY(eTO_IgnoreDirectories, bool, _T("Operation.IgnoreDirectories"), false); - - // Naming settings - TASK_PROPERTY(eTO_AlternateFilenameFormatString_First, TString, _T("Naming.AlternateFilenameFormatFirst"), _T("%name - copy%ext")); - TASK_PROPERTY(eTO_AlternateFilenameFormatString_AfterFirst, TString, _T("Naming.AlternateFilenameFormatAfterFirst"), _T("%name - copy (%count)%ext")); - - ///////////////////////////////////////////////////////////////////////////////////////////// - // other properties names - //#define TASK_PROP_NAME_FILTERING _T("Filtering") - - ///////////////////////////////////////////////////////////////////////////////////////////// - // Properties retrieval - template - typename TaskPropData::value_type GetTaskPropValue(const TConfig& rConfig) - { - typename TaskPropData::value_type tValue; - bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), tValue); - if (!bResult) - tValue = TaskPropData::GetDefaultValue(); - - TaskPropData::ValidateRange(tValue); - return tValue; - } - - template - bool GetTaskPropValue(const TConfig& rConfig, typename TaskPropData::value_type& rValue) - { - bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); - if (bResult) - TaskPropData::ValidateRange(rValue); - return bResult; - } - - template - void SetTaskPropValue(TConfig& rConfig, const typename TaskPropData::value_type& rValue) - { - SetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskConfiguration.h +/// @date 2010/09/18 +/// @brief Contains class responsible for keeping task configuration. +// ============================================================================ +#ifndef __TTASKCONFIGURATION_H__ +#define __TTASKCONFIGURATION_H__ + +#include "TConfig.h" + +namespace chcore +{ + enum ETaskOptions + { + eTO_UseOnlyDefaultBuffer, + eTO_DefaultBufferSize, + eTO_OneDiskBufferSize, + eTO_TwoDisksBufferSize, + eTO_CDBufferSize, + eTO_LANBufferSize, + eTO_DisableBuffering, + eTO_DisableBufferingMinSize, + eTO_BufferQueueDepth, + + eTO_FeedbackGeneralFileError, + eTO_FeedbackFileAlreadyExists, + eTO_FeedbackNotEnoughSpace, + + eTO_SetDestinationAttributes, + eTO_SetDestinationDateTime, + eTO_ProtectReadOnlyFiles, + eTO_ScanDirectoriesBeforeBlocking, + eTO_FastMoveBeforeBlocking, + eTO_ThreadPriority, + eTO_DisablePriorityBoost, + eTO_DeleteInSeparateSubTask, + + eTO_CreateEmptyFiles, + eTO_CreateDirectoriesRelativeToRoot, + eTO_IgnoreDirectories, + + eTO_AlternateFilenameFormatString_First, + eTO_AlternateFilenameFormatString_AfterFirst, + + // add new elements before this one + eTO_Last + }; + + ///////////////////////////////////////////////////////////////////////////////////////////// + // Properties definitions + + template struct TaskPropData; + +#define TASK_PROPERTY(enum_id, val_type, val_name, def_value)\ + template<> struct TaskPropData\ +{\ + typedef val_type value_type;\ +\ + static value_type GetDefaultValue() { return def_value; }\ + static const wchar_t* GetPropertyName() { return val_name; }\ + static void ValidateRange(value_type&) {}\ +} + +#define TASK_PROPERTY_MINMAX(enum_id, val_type, val_name, def_value, min_val, max_val)\ + template<> struct TaskPropData\ +{\ + typedef val_type value_type;\ +\ + static value_type GetDefaultValue() { return def_value; }\ + static const wchar_t* GetPropertyName() { return val_name; }\ + static void ValidateRange(value_type& rValue)\ + {\ + if(rValue < (min_val))\ + rValue = (min_val);\ + else if(rValue > (max_val))\ + rValue = (max_val);\ + }\ +} + +#define TASK_PROPERTY_MIN(enum_id, val_type, val_name, def_value, min_val)\ + template<> struct TaskPropData\ +{\ + typedef val_type value_type;\ +\ + static value_type GetDefaultValue() { return def_value; }\ + static const wchar_t* GetPropertyName() { return val_name; }\ + static void ValidateRange(value_type& rValue)\ + {\ + if(rValue < (min_val))\ + rValue = (min_val);\ + }\ +} + + // Buffer settings + TASK_PROPERTY(eTO_UseOnlyDefaultBuffer, bool, _T("Buffer.UseOnlyDefaultBuffer"), false); + TASK_PROPERTY_MIN(eTO_DefaultBufferSize, unsigned int, _T("Buffer.DefaultBufferSize"), 131072, 1); + TASK_PROPERTY_MIN(eTO_OneDiskBufferSize, unsigned int, _T("Buffer.OnePhysicalDiskSize"), 2097152, 1); + TASK_PROPERTY_MIN(eTO_TwoDisksBufferSize, unsigned int, _T("Buffer.TwoPhysicalDisksSize"), 131072, 1); + TASK_PROPERTY_MIN(eTO_CDBufferSize, unsigned int, _T("Buffer.CDSize"), 131072, 1); + TASK_PROPERTY_MIN(eTO_LANBufferSize, unsigned int, _T("Buffer.LANSize"), 131072, 1); + TASK_PROPERTY_MINMAX(eTO_BufferQueueDepth, unsigned int, _T("Buffer.QueueDepth"), 8, 1, 1000); + + TASK_PROPERTY(eTO_DisableBuffering, bool, _T("Operation.Buffering.DisableBufferingForLargeFiles"), true); + TASK_PROPERTY_MIN(eTO_DisableBufferingMinSize, int, _T("Operation.Buffering.MinSizeOfFileToDisableBuffering"), 0, 1); + + TASK_PROPERTY(eTO_SetDestinationAttributes, bool, _T("Operation.SetDestinationAttributes"), true); + TASK_PROPERTY(eTO_SetDestinationDateTime, bool, _T("Operation.SetDestinationTime"), true); + TASK_PROPERTY(eTO_ProtectReadOnlyFiles, bool, _T("Operation.ProtectReadOnlyFiles"), false); + TASK_PROPERTY(eTO_ScanDirectoriesBeforeBlocking, bool, _T("Operation.ScanForFilesBeforeBlocking"), false); + TASK_PROPERTY(eTO_FastMoveBeforeBlocking, bool, _T("Operation.FastMoveBeforeBlocking"), false); + + // Thread settings + TASK_PROPERTY(eTO_ThreadPriority, int, _T("Operation.Thread.Priority"), THREAD_PRIORITY_NORMAL); + TASK_PROPERTY(eTO_DisablePriorityBoost, bool, _T("Operation.Thread.DisablePriorityBoost"), false); + + // Operation settings + TASK_PROPERTY(eTO_DeleteInSeparateSubTask, bool, _T("Operation.DeleteFilesInSeparateOperation"), true); + + TASK_PROPERTY(eTO_CreateEmptyFiles, bool, _T("Operation.CreateEmptyFiles"), false); + TASK_PROPERTY(eTO_CreateDirectoriesRelativeToRoot, bool, _T("Operation.CreateDirectoriesRelativeToRoot"), false); + TASK_PROPERTY(eTO_IgnoreDirectories, bool, _T("Operation.IgnoreDirectories"), false); + + // Naming settings + TASK_PROPERTY(eTO_AlternateFilenameFormatString_First, TString, _T("Naming.AlternateFilenameFormatFirst"), _T("%name - copy%ext")); + TASK_PROPERTY(eTO_AlternateFilenameFormatString_AfterFirst, TString, _T("Naming.AlternateFilenameFormatAfterFirst"), _T("%name - copy (%count)%ext")); + + ///////////////////////////////////////////////////////////////////////////////////////////// + // other properties names + //#define TASK_PROP_NAME_FILTERING _T("Filtering") + + ///////////////////////////////////////////////////////////////////////////////////////////// + // Properties retrieval + template + typename TaskPropData::value_type GetTaskPropValue(const TConfig& rConfig) + { + typename TaskPropData::value_type tValue; + bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), tValue); + if (!bResult) + tValue = TaskPropData::GetDefaultValue(); + + TaskPropData::ValidateRange(tValue); + return tValue; + } + + template + bool GetTaskPropValue(const TConfig& rConfig, typename TaskPropData::value_type& rValue) + { + bool bResult = GetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); + if (bResult) + TaskPropData::ValidateRange(rValue); + return bResult; + } + + template + void SetTaskPropValue(TConfig& rConfig, const typename TaskPropData::value_type& rValue) + { + SetConfigValue(rConfig, TaskPropData::GetPropertyName(), rValue); + } +} + +#endif Index: src/libchcore/TTaskDefinition.cpp =================================================================== diff -u -re8f31b0f922b402878356e130c866c4f3682a7f5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskDefinition.cpp (.../TTaskDefinition.cpp) (revision e8f31b0f922b402878356e130c866c4f3682a7f5) +++ src/libchcore/TTaskDefinition.cpp (.../TTaskDefinition.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,300 +1,300 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskDefinition.cpp -/// @date 2010/09/18 -/// @brief Contains implementation of class representing task input data. -// ============================================================================ -#include "stdafx.h" -#include "..\common\version.h" -#include -#include -#include -#include -#include "TTaskDefinition.h" -#include "TCoreException.h" -#include "ErrorCodes.h" - -#define CURRENT_TASK_VERSION 1 - -namespace chcore -{ - TTaskDefinition::TTaskDefinition() : - m_bModified(false), - m_strTaskName(), - m_ullTaskVersion(CURRENT_TASK_VERSION) - { - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - m_strTaskName = boost::lexical_cast(u).c_str(); - } - - TTaskDefinition::TTaskDefinition(const TTaskDefinition& rSrc) : - m_strTaskName(rSrc.m_strTaskName), - m_vSourcePaths(rSrc.m_vSourcePaths), - m_afFilters(rSrc.m_afFilters), - m_pathDestinationPath(rSrc.m_pathDestinationPath), - m_tOperationPlan(rSrc.m_tOperationPlan), - m_ullTaskVersion(rSrc.m_ullTaskVersion), - m_tConfiguration(rSrc.m_tConfiguration), - m_bModified(rSrc.m_bModified) - { - } - - TTaskDefinition::~TTaskDefinition() - { - } - - TTaskDefinition& TTaskDefinition::operator=(const TTaskDefinition& rSrc) - { - if (this != &rSrc) - { - m_strTaskName = rSrc.m_strTaskName; - m_vSourcePaths = rSrc.m_vSourcePaths; - m_afFilters = rSrc.m_afFilters; - m_pathDestinationPath = rSrc.m_pathDestinationPath; - m_tOperationPlan = rSrc.m_tOperationPlan; - m_ullTaskVersion = rSrc.m_ullTaskVersion; - m_tConfiguration = rSrc.m_tConfiguration; - m_bModified = rSrc.m_bModified; - } - - return *this; - } - - // Task unique id - TString TTaskDefinition::GetTaskName() const - { - return m_strTaskName; - } - - // Source paths - // initialize object with data (get/set, from cfg file?, from string(cmd line options)) - void TTaskDefinition::AddSourcePath(const TSmartPath& tPath) - { - m_vSourcePaths.Add(tPath); - m_bModified = true; - } - - TSmartPath TTaskDefinition::GetSourcePathAt(size_t stIndex) const - { - return m_vSourcePaths.GetAt(stIndex); - } - - size_t TTaskDefinition::GetSourcePathCount() const - { - return m_vSourcePaths.GetCount(); - } - - void TTaskDefinition::ClearSourcePaths() - { - m_vSourcePaths.Clear(); - m_bModified = true; - } - - void TTaskDefinition::SetSourcePaths(const TPathContainer& rvPaths) - { - m_vSourcePaths = rvPaths; - } - - const TPathContainer& TTaskDefinition::GetSourcePaths() const - { - return m_vSourcePaths; - } - - // Destination path - void TTaskDefinition::SetDestinationPath(const TSmartPath& pathDestination) - { - m_pathDestinationPath = pathDestination; - if (!m_pathDestinationPath.IsEmpty()) - m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); - m_bModified = true; - } - - TSmartPath TTaskDefinition::GetDestinationPath() const - { - return m_pathDestinationPath; - } - - // Operation type - void TTaskDefinition::SetOperationType(EOperationType eOperation) - { - m_tOperationPlan.SetOperationType(eOperation); - m_bModified = true; - } - - EOperationType TTaskDefinition::GetOperationType() const - { - return m_tOperationPlan.GetOperationType(); - } - - const TOperationPlan& TTaskDefinition::GetOperationPlan() const - { - return m_tOperationPlan; - } - - // Task configuration - void TTaskDefinition::SetConfiguration(const TConfig& rConfig) - { - m_tConfiguration = rConfig; - m_bModified = true; - } - - TConfig& TTaskDefinition::GetConfiguration() - { - return m_tConfiguration; - } - - const TConfig& TTaskDefinition::GetConfiguration() const - { - return m_tConfiguration; - } - - // Serialization - void TTaskDefinition::Load(const TSmartPath& strPath) - { - // read everything - TConfig tTaskInfo; - tTaskInfo.Read(strPath.ToString()); - - Load(tTaskInfo, false); - } - - void TTaskDefinition::Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath) - { - // clear everything - m_strTaskName.Clear(); - m_vSourcePaths.Clear(); - m_pathDestinationPath.Clear(); - m_afFilters.Clear(); - - m_tConfiguration.Clear(); - - m_bModified = false; - - // get information from config file - // NOTE: task unique id is not read from the config by design; - // by using the value, CH tried to re-use the task DB causing problems. - // So now, always a new identifier is generated. - boost::uuids::random_generator gen; - boost::uuids::uuid u = gen(); - m_strTaskName = boost::lexical_cast(u).c_str(); - - // basic information - // source paths to be processed - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths) || m_vSourcePaths.IsEmpty()) - throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.SourcePaths.Path", LOCATION); - - GetConfigValue(rDataSrc, _T("TaskDefinition.Filters"), m_afFilters); - - // destination path - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath) || (!bAllowEmptyDstPath && m_pathDestinationPath.IsEmpty())) - throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.DestinationPath", LOCATION); - - // append separator only if destination path is already specified; otherwise there are problems handling chext requests with no destination path - if (!m_pathDestinationPath.IsEmpty()) - m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); - - // type of the operation - int iOperation = eOperation_None; - if (!rDataSrc.GetValue(_T("TaskDefinition.OperationType"), iOperation)) - throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.OperationType", LOCATION); - - m_tOperationPlan.SetOperationType((EOperationType)iOperation); - - // and version of the task - if (!GetConfigValue(rDataSrc, _T("TaskDefinition.Version"), m_ullTaskVersion)) - throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.Version", LOCATION); - - if (m_ullTaskVersion < CURRENT_TASK_VERSION) - { - // migrate the task to the newer version - // (nothing to migrate at this point, since 1.40 is the first release with xml-based tasks). - - // then mark it as a newest version task - m_ullTaskVersion = CURRENT_TASK_VERSION; - m_bModified = true; - } - else if (m_ullTaskVersion > CURRENT_TASK_VERSION) - throw TCoreException(eErr_UnsupportedVersion, L"Task version unsupported", LOCATION); - - rDataSrc.ExtractSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); - } - - void TTaskDefinition::LoadFromString(const TString& strInput, bool bAllowEmptyDstPath) - { - // read everything - TConfig tTaskInfo; - tTaskInfo.ReadFromString(strInput); - - Load(tTaskInfo, bAllowEmptyDstPath); - } - - void TTaskDefinition::StoreInString(TString& strOutput) - { - TConfig tTaskInfo; - Store(tTaskInfo); - - tTaskInfo.WriteToString(strOutput); - } - - void TTaskDefinition::Store(const TSmartPath& strPath) const - { - TConfig tTaskInfo; - Store(tTaskInfo); - - tTaskInfo.SetFilePath(strPath.ToString()); - tTaskInfo.Write(); - } - - void TTaskDefinition::Store(TConfig& rConfig) const - { - // get information from config file - // task unique id - use if provided, generate otherwise - // NOTE: not storing the task ID is by design. Loading same task twice caused problems - // when importing and was disabled. With that, storing was no longer needed. - - // basic information - SetConfigValue(rConfig, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths); - SetConfigValue(rConfig, _T("TaskDefinition.Filters"), m_afFilters); - SetConfigValue(rConfig, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath); - - int iOperation = m_tOperationPlan.GetOperationType(); - SetConfigValue(rConfig, _T("TaskDefinition.OperationType"), iOperation); - - SetConfigValue(rConfig, _T("TaskDefinition.Version"), m_ullTaskVersion); - - rConfig.PutSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); - } - - - const TFileFiltersArray& TTaskDefinition::GetFilters() const - { - return m_afFilters; - } - - TFileFiltersArray& TTaskDefinition::GetFilters() - { - return m_afFilters; - } - - void TTaskDefinition::SetFilters(const TFileFiltersArray& rFilters) - { - m_afFilters = rFilters; - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskDefinition.cpp +/// @date 2010/09/18 +/// @brief Contains implementation of class representing task input data. +// ============================================================================ +#include "stdafx.h" +#include "..\common\version.h" +#include +#include +#include +#include +#include "TTaskDefinition.h" +#include "TCoreException.h" +#include "ErrorCodes.h" + +#define CURRENT_TASK_VERSION 1 + +namespace chcore +{ + TTaskDefinition::TTaskDefinition() : + m_bModified(false), + m_strTaskName(), + m_ullTaskVersion(CURRENT_TASK_VERSION) + { + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + m_strTaskName = boost::lexical_cast(u).c_str(); + } + + TTaskDefinition::TTaskDefinition(const TTaskDefinition& rSrc) : + m_strTaskName(rSrc.m_strTaskName), + m_vSourcePaths(rSrc.m_vSourcePaths), + m_afFilters(rSrc.m_afFilters), + m_pathDestinationPath(rSrc.m_pathDestinationPath), + m_tOperationPlan(rSrc.m_tOperationPlan), + m_ullTaskVersion(rSrc.m_ullTaskVersion), + m_tConfiguration(rSrc.m_tConfiguration), + m_bModified(rSrc.m_bModified) + { + } + + TTaskDefinition::~TTaskDefinition() + { + } + + TTaskDefinition& TTaskDefinition::operator=(const TTaskDefinition& rSrc) + { + if (this != &rSrc) + { + m_strTaskName = rSrc.m_strTaskName; + m_vSourcePaths = rSrc.m_vSourcePaths; + m_afFilters = rSrc.m_afFilters; + m_pathDestinationPath = rSrc.m_pathDestinationPath; + m_tOperationPlan = rSrc.m_tOperationPlan; + m_ullTaskVersion = rSrc.m_ullTaskVersion; + m_tConfiguration = rSrc.m_tConfiguration; + m_bModified = rSrc.m_bModified; + } + + return *this; + } + + // Task unique id + TString TTaskDefinition::GetTaskName() const + { + return m_strTaskName; + } + + // Source paths + // initialize object with data (get/set, from cfg file?, from string(cmd line options)) + void TTaskDefinition::AddSourcePath(const TSmartPath& tPath) + { + m_vSourcePaths.Add(tPath); + m_bModified = true; + } + + TSmartPath TTaskDefinition::GetSourcePathAt(size_t stIndex) const + { + return m_vSourcePaths.GetAt(stIndex); + } + + size_t TTaskDefinition::GetSourcePathCount() const + { + return m_vSourcePaths.GetCount(); + } + + void TTaskDefinition::ClearSourcePaths() + { + m_vSourcePaths.Clear(); + m_bModified = true; + } + + void TTaskDefinition::SetSourcePaths(const TPathContainer& rvPaths) + { + m_vSourcePaths = rvPaths; + } + + const TPathContainer& TTaskDefinition::GetSourcePaths() const + { + return m_vSourcePaths; + } + + // Destination path + void TTaskDefinition::SetDestinationPath(const TSmartPath& pathDestination) + { + m_pathDestinationPath = pathDestination; + if (!m_pathDestinationPath.IsEmpty()) + m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); + m_bModified = true; + } + + TSmartPath TTaskDefinition::GetDestinationPath() const + { + return m_pathDestinationPath; + } + + // Operation type + void TTaskDefinition::SetOperationType(EOperationType eOperation) + { + m_tOperationPlan.SetOperationType(eOperation); + m_bModified = true; + } + + EOperationType TTaskDefinition::GetOperationType() const + { + return m_tOperationPlan.GetOperationType(); + } + + const TOperationPlan& TTaskDefinition::GetOperationPlan() const + { + return m_tOperationPlan; + } + + // Task configuration + void TTaskDefinition::SetConfiguration(const TConfig& rConfig) + { + m_tConfiguration = rConfig; + m_bModified = true; + } + + TConfig& TTaskDefinition::GetConfiguration() + { + return m_tConfiguration; + } + + const TConfig& TTaskDefinition::GetConfiguration() const + { + return m_tConfiguration; + } + + // Serialization + void TTaskDefinition::Load(const TSmartPath& strPath) + { + // read everything + TConfig tTaskInfo; + tTaskInfo.Read(strPath.ToString()); + + Load(tTaskInfo, false); + } + + void TTaskDefinition::Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath) + { + // clear everything + m_strTaskName.Clear(); + m_vSourcePaths.Clear(); + m_pathDestinationPath.Clear(); + m_afFilters.Clear(); + + m_tConfiguration.Clear(); + + m_bModified = false; + + // get information from config file + // NOTE: task unique id is not read from the config by design; + // by using the value, CH tried to re-use the task DB causing problems. + // So now, always a new identifier is generated. + boost::uuids::random_generator gen; + boost::uuids::uuid u = gen(); + m_strTaskName = boost::lexical_cast(u).c_str(); + + // basic information + // source paths to be processed + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths) || m_vSourcePaths.IsEmpty()) + throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.SourcePaths.Path", LOCATION); + + GetConfigValue(rDataSrc, _T("TaskDefinition.Filters"), m_afFilters); + + // destination path + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath) || (!bAllowEmptyDstPath && m_pathDestinationPath.IsEmpty())) + throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.DestinationPath", LOCATION); + + // append separator only if destination path is already specified; otherwise there are problems handling chext requests with no destination path + if (!m_pathDestinationPath.IsEmpty()) + m_pathDestinationPath.AppendSeparatorIfDoesNotExist(); + + // type of the operation + int iOperation = eOperation_None; + if (!rDataSrc.GetValue(_T("TaskDefinition.OperationType"), iOperation)) + throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.OperationType", LOCATION); + + m_tOperationPlan.SetOperationType((EOperationType)iOperation); + + // and version of the task + if (!GetConfigValue(rDataSrc, _T("TaskDefinition.Version"), m_ullTaskVersion)) + throw TCoreException(eErr_MissingXmlData, L"Missing TaskDefinition.Version", LOCATION); + + if (m_ullTaskVersion < CURRENT_TASK_VERSION) + { + // migrate the task to the newer version + // (nothing to migrate at this point, since 1.40 is the first release with xml-based tasks). + + // then mark it as a newest version task + m_ullTaskVersion = CURRENT_TASK_VERSION; + m_bModified = true; + } + else if (m_ullTaskVersion > CURRENT_TASK_VERSION) + throw TCoreException(eErr_UnsupportedVersion, L"Task version unsupported", LOCATION); + + rDataSrc.ExtractSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); + } + + void TTaskDefinition::LoadFromString(const TString& strInput, bool bAllowEmptyDstPath) + { + // read everything + TConfig tTaskInfo; + tTaskInfo.ReadFromString(strInput); + + Load(tTaskInfo, bAllowEmptyDstPath); + } + + void TTaskDefinition::StoreInString(TString& strOutput) + { + TConfig tTaskInfo; + Store(tTaskInfo); + + tTaskInfo.WriteToString(strOutput); + } + + void TTaskDefinition::Store(const TSmartPath& strPath) const + { + TConfig tTaskInfo; + Store(tTaskInfo); + + tTaskInfo.SetFilePath(strPath.ToString()); + tTaskInfo.Write(); + } + + void TTaskDefinition::Store(TConfig& rConfig) const + { + // get information from config file + // task unique id - use if provided, generate otherwise + // NOTE: not storing the task ID is by design. Loading same task twice caused problems + // when importing and was disabled. With that, storing was no longer needed. + + // basic information + SetConfigValue(rConfig, _T("TaskDefinition.SourcePaths.Path"), m_vSourcePaths); + SetConfigValue(rConfig, _T("TaskDefinition.Filters"), m_afFilters); + SetConfigValue(rConfig, _T("TaskDefinition.DestinationPath"), m_pathDestinationPath); + + int iOperation = m_tOperationPlan.GetOperationType(); + SetConfigValue(rConfig, _T("TaskDefinition.OperationType"), iOperation); + + SetConfigValue(rConfig, _T("TaskDefinition.Version"), m_ullTaskVersion); + + rConfig.PutSubConfig(_T("TaskDefinition.TaskSettings"), m_tConfiguration); + } + + + const TFileFiltersArray& TTaskDefinition::GetFilters() const + { + return m_afFilters; + } + + TFileFiltersArray& TTaskDefinition::GetFilters() + { + return m_afFilters; + } + + void TTaskDefinition::SetFilters(const TFileFiltersArray& rFilters) + { + m_afFilters = rFilters; + } +} Index: src/libchcore/TTaskDefinition.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskDefinition.h (.../TTaskDefinition.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TTaskDefinition.h (.../TTaskDefinition.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,107 +1,107 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskDefinition.h -/// @date 2010/09/18 -/// @brief Contains declaration of class representing task input data. -// ============================================================================ -#ifndef __TTASKDEFINITION_H__ -#define __TTASKDEFINITION_H__ - -#include "TTaskOperationPlan.h" -#include "TConfig.h" -#include "TPath.h" -#include "TPathContainer.h" -#include "TFileFiltersArray.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - // TTaskDefinition - - class LIBCHCORE_API TTaskDefinition - { - public: - TTaskDefinition(); - TTaskDefinition(const TTaskDefinition& rSrc); - ~TTaskDefinition(); - - TTaskDefinition& operator=(const TTaskDefinition& rSrc); - - // Task unique ID - TString GetTaskName() const; - - // Source paths - void AddSourcePath(const TSmartPath& tPath); - TSmartPath GetSourcePathAt(size_t stIndex) const; - size_t GetSourcePathCount() const; - void SetSourcePaths(const TPathContainer& rvPaths); - const TPathContainer& GetSourcePaths() const; - - void ClearSourcePaths(); - - // filters - const TFileFiltersArray& GetFilters() const; - TFileFiltersArray& GetFilters(); - void SetFilters(const TFileFiltersArray& rFilters); - - // Destination path - void SetDestinationPath(const TSmartPath& pathDestination); - TSmartPath GetDestinationPath() const; - - // Operation type - void SetOperationType(EOperationType eOperation); - EOperationType GetOperationType() const; - const TOperationPlan& GetOperationPlan() const; - - // Task configuration - void SetConfiguration(const TConfig& rConfig); - TConfig& GetConfiguration(); - const TConfig& GetConfiguration() const; - - // Serialization - void Load(const TSmartPath& strPath); - void Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath); - void LoadFromString(const TString& strInput, bool bAllowEmptyDstPath = false); - - void Store(const TSmartPath& strPath) const; - void Store(TConfig& rConfig) const; - void StoreInString(TString& strInput); - - private: - TString m_strTaskName; ///< Unique ID of the task that will process this request (generated automatically) - - // basic information - TPathContainer m_vSourcePaths; - TSmartPath m_pathDestinationPath; - TFileFiltersArray m_afFilters; - - TOperationPlan m_tOperationPlan; ///< Describes the operation along with sub-operations to be performed on the task input data - - // Task version - unsigned long long m_ullTaskVersion; - - // Global task settings - TConfig m_tConfiguration; - - // Other info (volatile, not to be saved to xml) - mutable bool m_bModified; ///< Some parameters has been modified and this object needs to be serialized again - }; -} - -#endif // __TTASKDEFINITION_H__ +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskDefinition.h +/// @date 2010/09/18 +/// @brief Contains declaration of class representing task input data. +// ============================================================================ +#ifndef __TTASKDEFINITION_H__ +#define __TTASKDEFINITION_H__ + +#include "TTaskOperationPlan.h" +#include "TConfig.h" +#include "TPath.h" +#include "TPathContainer.h" +#include "TFileFiltersArray.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + // TTaskDefinition + + class LIBCHCORE_API TTaskDefinition + { + public: + TTaskDefinition(); + TTaskDefinition(const TTaskDefinition& rSrc); + ~TTaskDefinition(); + + TTaskDefinition& operator=(const TTaskDefinition& rSrc); + + // Task unique ID + TString GetTaskName() const; + + // Source paths + void AddSourcePath(const TSmartPath& tPath); + TSmartPath GetSourcePathAt(size_t stIndex) const; + size_t GetSourcePathCount() const; + void SetSourcePaths(const TPathContainer& rvPaths); + const TPathContainer& GetSourcePaths() const; + + void ClearSourcePaths(); + + // filters + const TFileFiltersArray& GetFilters() const; + TFileFiltersArray& GetFilters(); + void SetFilters(const TFileFiltersArray& rFilters); + + // Destination path + void SetDestinationPath(const TSmartPath& pathDestination); + TSmartPath GetDestinationPath() const; + + // Operation type + void SetOperationType(EOperationType eOperation); + EOperationType GetOperationType() const; + const TOperationPlan& GetOperationPlan() const; + + // Task configuration + void SetConfiguration(const TConfig& rConfig); + TConfig& GetConfiguration(); + const TConfig& GetConfiguration() const; + + // Serialization + void Load(const TSmartPath& strPath); + void Load(const TConfig& rDataSrc, bool bAllowEmptyDstPath); + void LoadFromString(const TString& strInput, bool bAllowEmptyDstPath = false); + + void Store(const TSmartPath& strPath) const; + void Store(TConfig& rConfig) const; + void StoreInString(TString& strInput); + + private: + TString m_strTaskName; ///< Unique ID of the task that will process this request (generated automatically) + + // basic information + TPathContainer m_vSourcePaths; + TSmartPath m_pathDestinationPath; + TFileFiltersArray m_afFilters; + + TOperationPlan m_tOperationPlan; ///< Describes the operation along with sub-operations to be performed on the task input data + + // Task version + unsigned long long m_ullTaskVersion; + + // Global task settings + TConfig m_tConfiguration; + + // Other info (volatile, not to be saved to xml) + mutable bool m_bModified; ///< Some parameters has been modified and this object needs to be serialized again + }; +} + +#endif // __TTASKDEFINITION_H__ Index: src/libchcore/TTaskInfo.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskInfo.cpp (.../TTaskInfo.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TTaskInfo.cpp (.../TTaskInfo.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,267 +1,267 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TTaskInfo.h" -#include "TCoreException.h" -#include "ISerializerRowData.h" -#include "ISerializerRowReader.h" - -namespace chcore -{ - TTaskInfoEntry::TTaskInfoEntry() : - m_iOrder(m_setModifications, 0), - m_pathSerializeLocation(m_setModifications), - m_oidObjectID(0) - { - m_setModifications[eMod_Added] = true; - } - - TTaskInfoEntry::TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) : - m_oidObjectID(oidTaskID), - m_pathSerializeLocation(m_setModifications, pathTask), - m_iOrder(m_setModifications, iOrder), - m_spTask(spTask) - { - m_setModifications[eMod_Added] = true; - } - - TTaskInfoEntry::TTaskInfoEntry(const TTaskInfoEntry& rSrc) : - m_oidObjectID(rSrc.m_oidObjectID), - m_pathSerializeLocation(m_setModifications, rSrc.m_pathSerializeLocation), - m_iOrder(m_setModifications, rSrc.m_iOrder), - m_spTask(rSrc.m_spTask), - m_setModifications(rSrc.m_setModifications) - { - } - - TTaskInfoEntry& TTaskInfoEntry::operator=(const TTaskInfoEntry& rSrc) - { - if (this != &rSrc) - { - m_oidObjectID = rSrc.m_oidObjectID; - m_pathSerializeLocation = rSrc.m_pathSerializeLocation; - m_iOrder = rSrc.m_iOrder; - m_spTask = rSrc.m_spTask; - m_setModifications = rSrc.m_setModifications; - } - - return *this; - } - - TSmartPath TTaskInfoEntry::GetTaskSerializeLocation() const - { - return m_pathSerializeLocation; - } - - void TTaskInfoEntry::SetTaskSerializeLocation(const TSmartPath& strTaskPath) - { - m_pathSerializeLocation = strTaskPath; - } - - TTaskPtr TTaskInfoEntry::GetTask() const - { - return m_spTask; - } - - void TTaskInfoEntry::SetTask(const TTaskPtr& spTask) - { - m_spTask = spTask; - } - - int TTaskInfoEntry::GetOrder() const - { - return m_iOrder; - } - - void TTaskInfoEntry::SetOrder(int iOrder) - { - m_iOrder = iOrder; - } - - void TTaskInfoEntry::Store(const ISerializerContainerPtr& spContainer) const - { - if (!m_setModifications.any()) - return; - - bool bAdded = m_setModifications[eMod_Added]; - ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); - - if (bAdded || m_setModifications[eMod_TaskPath]) - rRow.SetValue(_T("path"), m_pathSerializeLocation); - if (bAdded || m_setModifications[eMod_Order]) - rRow.SetValue(_T("task_order"), m_iOrder); - - m_setModifications.reset(); - } - - void TTaskInfoEntry::Load(const ISerializerRowReaderPtr& spRowReader) - { - spRowReader->GetValue(_T("id"), m_oidObjectID); - spRowReader->GetValue(_T("path"), m_pathSerializeLocation.Modify()); - spRowReader->GetValue(_T("task_order"), m_iOrder.Modify()); - - m_setModifications.reset(); - } - - void TTaskInfoEntry::InitColumns(IColumnsDefinition& rColumnDefs) - { - rColumnDefs.AddColumn(_T("id"), ColumnType::value); - rColumnDefs.AddColumn(_T("path"), IColumnsDefinition::eType_path); - rColumnDefs.AddColumn(_T("task_order"), IColumnsDefinition::eType_int); - } - - object_id_t TTaskInfoEntry::GetObjectID() const - { - return m_oidObjectID; - } - - void TTaskInfoEntry::ResetModifications() - { - m_setModifications.reset(); - } - - /////////////////////////////////////////////////////////////////////////// - TTaskInfoContainer::TTaskInfoContainer() : - m_oidLastObjectID(0) - { - } - - void TTaskInfoContainer::Add(const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) - { - m_vTaskInfos.push_back(TTaskInfoEntry(++m_oidLastObjectID, pathTask, iOrder, spTask)); - } - - void TTaskInfoContainer::RemoveAt(size_t stIndex) - { - if (stIndex >= m_vTaskInfos.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - std::vector::iterator iter = m_vTaskInfos.begin() + stIndex; - object_id_t oidTaskID = (*iter).GetObjectID(); - m_vTaskInfos.erase(m_vTaskInfos.begin() + stIndex); - m_setRemovedTasks.Add(oidTaskID); - } - - void TTaskInfoContainer::Clear() - { - for(TTaskInfoEntry& rEntry : m_vTaskInfos) - { - m_setRemovedTasks.Add(rEntry.GetObjectID()); - } - m_vTaskInfos.clear(); - } - - TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) - { - if (stIndex >= m_vTaskInfos.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vTaskInfos[stIndex]; - } - - const TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) const - { - if (stIndex >= m_vTaskInfos.size()) - throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); - - return m_vTaskInfos[stIndex]; - } - - size_t TTaskInfoContainer::GetCount() const - { - return m_vTaskInfos.size(); - } - - bool TTaskInfoContainer::GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const - { - for (std::vector::const_iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) - { - if ((*iter).GetObjectID() == tTaskID) - { - rInfo = *iter; - return true; - } - } - - return false; - } - - bool TTaskInfoContainer::IsEmpty() const - { - return m_vTaskInfos.empty(); - } - - void TTaskInfoContainer::ClearModifications() - { - m_setRemovedTasks.Clear(); - - for(TTaskInfoEntry& rEntry : m_vTaskInfos) - { - // if marked as added, we don't consider it modified anymore - rEntry.ResetModifications(); - } - } - - void TTaskInfoContainer::Store(const ISerializerContainerPtr& spContainer) const - { - InitColumns(spContainer); - - spContainer->DeleteRows(m_setRemovedTasks); - m_setRemovedTasks.Clear(); - - for(const TTaskInfoEntry& rEntry : m_vTaskInfos) - { - rEntry.Store(spContainer); - } - } - - void TTaskInfoContainer::Load(const ISerializerContainerPtr& spContainer) - { - InitColumns(spContainer); - - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - - TTaskInfoEntry tEntry; - while (spRowReader->Next()) - { - tEntry.Load(spRowReader); - - m_vTaskInfos.push_back(tEntry); - m_oidLastObjectID = std::max(m_oidLastObjectID, tEntry.GetObjectID()); - } - } - - TTaskInfoEntry& TTaskInfoContainer::GetAtOid(object_id_t oidObjectID) - { - for (std::vector::iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) - { - if ((*iter).GetObjectID() == oidObjectID) - return *iter; - } - - throw TCoreException(eErr_InvalidArgument, L"Object id does not exist", LOCATION); - } - - void TTaskInfoContainer::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - TTaskInfoEntry::InitColumns(rColumns); - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TTaskInfo.h" +#include "TCoreException.h" +#include "ISerializerRowData.h" +#include "ISerializerRowReader.h" + +namespace chcore +{ + TTaskInfoEntry::TTaskInfoEntry() : + m_iOrder(m_setModifications, 0), + m_pathSerializeLocation(m_setModifications), + m_oidObjectID(0) + { + m_setModifications[eMod_Added] = true; + } + + TTaskInfoEntry::TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) : + m_oidObjectID(oidTaskID), + m_pathSerializeLocation(m_setModifications, pathTask), + m_iOrder(m_setModifications, iOrder), + m_spTask(spTask) + { + m_setModifications[eMod_Added] = true; + } + + TTaskInfoEntry::TTaskInfoEntry(const TTaskInfoEntry& rSrc) : + m_oidObjectID(rSrc.m_oidObjectID), + m_pathSerializeLocation(m_setModifications, rSrc.m_pathSerializeLocation), + m_iOrder(m_setModifications, rSrc.m_iOrder), + m_spTask(rSrc.m_spTask), + m_setModifications(rSrc.m_setModifications) + { + } + + TTaskInfoEntry& TTaskInfoEntry::operator=(const TTaskInfoEntry& rSrc) + { + if (this != &rSrc) + { + m_oidObjectID = rSrc.m_oidObjectID; + m_pathSerializeLocation = rSrc.m_pathSerializeLocation; + m_iOrder = rSrc.m_iOrder; + m_spTask = rSrc.m_spTask; + m_setModifications = rSrc.m_setModifications; + } + + return *this; + } + + TSmartPath TTaskInfoEntry::GetTaskSerializeLocation() const + { + return m_pathSerializeLocation; + } + + void TTaskInfoEntry::SetTaskSerializeLocation(const TSmartPath& strTaskPath) + { + m_pathSerializeLocation = strTaskPath; + } + + TTaskPtr TTaskInfoEntry::GetTask() const + { + return m_spTask; + } + + void TTaskInfoEntry::SetTask(const TTaskPtr& spTask) + { + m_spTask = spTask; + } + + int TTaskInfoEntry::GetOrder() const + { + return m_iOrder; + } + + void TTaskInfoEntry::SetOrder(int iOrder) + { + m_iOrder = iOrder; + } + + void TTaskInfoEntry::Store(const ISerializerContainerPtr& spContainer) const + { + if (!m_setModifications.any()) + return; + + bool bAdded = m_setModifications[eMod_Added]; + ISerializerRowData& rRow = spContainer->GetRow(m_oidObjectID, bAdded); + + if (bAdded || m_setModifications[eMod_TaskPath]) + rRow.SetValue(_T("path"), m_pathSerializeLocation); + if (bAdded || m_setModifications[eMod_Order]) + rRow.SetValue(_T("task_order"), m_iOrder); + + m_setModifications.reset(); + } + + void TTaskInfoEntry::Load(const ISerializerRowReaderPtr& spRowReader) + { + spRowReader->GetValue(_T("id"), m_oidObjectID); + spRowReader->GetValue(_T("path"), m_pathSerializeLocation.Modify()); + spRowReader->GetValue(_T("task_order"), m_iOrder.Modify()); + + m_setModifications.reset(); + } + + void TTaskInfoEntry::InitColumns(IColumnsDefinition& rColumnDefs) + { + rColumnDefs.AddColumn(_T("id"), ColumnType::value); + rColumnDefs.AddColumn(_T("path"), IColumnsDefinition::eType_path); + rColumnDefs.AddColumn(_T("task_order"), IColumnsDefinition::eType_int); + } + + object_id_t TTaskInfoEntry::GetObjectID() const + { + return m_oidObjectID; + } + + void TTaskInfoEntry::ResetModifications() + { + m_setModifications.reset(); + } + + /////////////////////////////////////////////////////////////////////////// + TTaskInfoContainer::TTaskInfoContainer() : + m_oidLastObjectID(0) + { + } + + void TTaskInfoContainer::Add(const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask) + { + m_vTaskInfos.push_back(TTaskInfoEntry(++m_oidLastObjectID, pathTask, iOrder, spTask)); + } + + void TTaskInfoContainer::RemoveAt(size_t stIndex) + { + if (stIndex >= m_vTaskInfos.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + std::vector::iterator iter = m_vTaskInfos.begin() + stIndex; + object_id_t oidTaskID = (*iter).GetObjectID(); + m_vTaskInfos.erase(m_vTaskInfos.begin() + stIndex); + m_setRemovedTasks.Add(oidTaskID); + } + + void TTaskInfoContainer::Clear() + { + for(TTaskInfoEntry& rEntry : m_vTaskInfos) + { + m_setRemovedTasks.Add(rEntry.GetObjectID()); + } + m_vTaskInfos.clear(); + } + + TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) + { + if (stIndex >= m_vTaskInfos.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vTaskInfos[stIndex]; + } + + const TTaskInfoEntry& TTaskInfoContainer::GetAt(size_t stIndex) const + { + if (stIndex >= m_vTaskInfos.size()) + throw TCoreException(eErr_BoundsExceeded, L"stIndex", LOCATION); + + return m_vTaskInfos[stIndex]; + } + + size_t TTaskInfoContainer::GetCount() const + { + return m_vTaskInfos.size(); + } + + bool TTaskInfoContainer::GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const + { + for (std::vector::const_iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) + { + if ((*iter).GetObjectID() == tTaskID) + { + rInfo = *iter; + return true; + } + } + + return false; + } + + bool TTaskInfoContainer::IsEmpty() const + { + return m_vTaskInfos.empty(); + } + + void TTaskInfoContainer::ClearModifications() + { + m_setRemovedTasks.Clear(); + + for(TTaskInfoEntry& rEntry : m_vTaskInfos) + { + // if marked as added, we don't consider it modified anymore + rEntry.ResetModifications(); + } + } + + void TTaskInfoContainer::Store(const ISerializerContainerPtr& spContainer) const + { + InitColumns(spContainer); + + spContainer->DeleteRows(m_setRemovedTasks); + m_setRemovedTasks.Clear(); + + for(const TTaskInfoEntry& rEntry : m_vTaskInfos) + { + rEntry.Store(spContainer); + } + } + + void TTaskInfoContainer::Load(const ISerializerContainerPtr& spContainer) + { + InitColumns(spContainer); + + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + + TTaskInfoEntry tEntry; + while (spRowReader->Next()) + { + tEntry.Load(spRowReader); + + m_vTaskInfos.push_back(tEntry); + m_oidLastObjectID = std::max(m_oidLastObjectID, tEntry.GetObjectID()); + } + } + + TTaskInfoEntry& TTaskInfoContainer::GetAtOid(object_id_t oidObjectID) + { + for (std::vector::iterator iter = m_vTaskInfos.begin(); iter != m_vTaskInfos.end(); ++iter) + { + if ((*iter).GetObjectID() == oidObjectID) + return *iter; + } + + throw TCoreException(eErr_InvalidArgument, L"Object id does not exist", LOCATION); + } + + void TTaskInfoContainer::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + TTaskInfoEntry::InitColumns(rColumns); + } +} Index: src/libchcore/TTaskInfo.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskInfo.h (.../TTaskInfo.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TTaskInfo.h (.../TTaskInfo.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,123 +1,123 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TTASKINFO_H__ -#define __TTASKINFO_H__ - -#include "libchcore.h" -#include "TPath.h" -#include "TaskID.h" -#include "ISerializerContainer.h" -#include "TRemovedObjects.h" -#include -#include "TSharedModificationTracker.h" - -namespace chcore -{ - class TTask; - typedef std::shared_ptr TTaskPtr; - - class LIBCHCORE_API TTaskInfoEntry - { - public: - enum EModifications - { - eMod_None = 0, - eMod_Added, - eMod_TaskPath, - eMod_Order, - - eMod_Last - }; - - public: - TTaskInfoEntry(); - TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask); - TTaskInfoEntry(const TTaskInfoEntry& rSrc); - - TTaskInfoEntry& operator=(const TTaskInfoEntry& rSrc); - - object_id_t GetObjectID() const; - - TSmartPath GetTaskSerializeLocation() const; - void SetTaskSerializeLocation(const TSmartPath& pathTask); - - TTaskPtr GetTask() const; - void SetTask(const TTaskPtr& spTask); - - int GetOrder() const; - void SetOrder(int iOrder); - - void Store(const ISerializerContainerPtr& spContainer) const; - static void InitColumns(IColumnsDefinition& rColumnDefs); - void Load(const ISerializerRowReaderPtr& spRowReader); - - void ResetModifications(); - - private: -#pragma warning(push) -#pragma warning(disable:4251) - object_id_t m_oidObjectID; - typedef std::bitset Bitset; - mutable std::bitset m_setModifications; - TSharedModificationTracker m_pathSerializeLocation; - TSharedModificationTracker m_iOrder; - - TTaskPtr m_spTask; -#pragma warning(pop) - }; - - class LIBCHCORE_API TTaskInfoContainer - { - public: - TTaskInfoContainer(); - - void Add(const TSmartPath& strPath, int iOrder, const TTaskPtr& spTask); - void RemoveAt(size_t stIndex); - - TTaskInfoEntry& GetAt(size_t stIndex); - const TTaskInfoEntry& GetAt(size_t stIndex) const; - - TTaskInfoEntry& GetAtOid(object_id_t oidObjectID); - - bool GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const; - - size_t GetCount() const; - bool IsEmpty() const; - - void Clear(); - - // modifications management - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - void ClearModifications(); - - private: -#pragma warning(push) -#pragma warning(disable:4251) - std::vector m_vTaskInfos; - mutable TRemovedObjects m_setRemovedTasks; -#pragma warning(pop) - object_id_t m_oidLastObjectID; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TTASKINFO_H__ +#define __TTASKINFO_H__ + +#include "libchcore.h" +#include "TPath.h" +#include "TaskID.h" +#include "ISerializerContainer.h" +#include "TRemovedObjects.h" +#include +#include "TSharedModificationTracker.h" + +namespace chcore +{ + class TTask; + typedef std::shared_ptr TTaskPtr; + + class LIBCHCORE_API TTaskInfoEntry + { + public: + enum EModifications + { + eMod_None = 0, + eMod_Added, + eMod_TaskPath, + eMod_Order, + + eMod_Last + }; + + public: + TTaskInfoEntry(); + TTaskInfoEntry(object_id_t oidTaskID, const TSmartPath& pathTask, int iOrder, const TTaskPtr& spTask); + TTaskInfoEntry(const TTaskInfoEntry& rSrc); + + TTaskInfoEntry& operator=(const TTaskInfoEntry& rSrc); + + object_id_t GetObjectID() const; + + TSmartPath GetTaskSerializeLocation() const; + void SetTaskSerializeLocation(const TSmartPath& pathTask); + + TTaskPtr GetTask() const; + void SetTask(const TTaskPtr& spTask); + + int GetOrder() const; + void SetOrder(int iOrder); + + void Store(const ISerializerContainerPtr& spContainer) const; + static void InitColumns(IColumnsDefinition& rColumnDefs); + void Load(const ISerializerRowReaderPtr& spRowReader); + + void ResetModifications(); + + private: +#pragma warning(push) +#pragma warning(disable:4251) + object_id_t m_oidObjectID; + typedef std::bitset Bitset; + mutable std::bitset m_setModifications; + TSharedModificationTracker m_pathSerializeLocation; + TSharedModificationTracker m_iOrder; + + TTaskPtr m_spTask; +#pragma warning(pop) + }; + + class LIBCHCORE_API TTaskInfoContainer + { + public: + TTaskInfoContainer(); + + void Add(const TSmartPath& strPath, int iOrder, const TTaskPtr& spTask); + void RemoveAt(size_t stIndex); + + TTaskInfoEntry& GetAt(size_t stIndex); + const TTaskInfoEntry& GetAt(size_t stIndex) const; + + TTaskInfoEntry& GetAtOid(object_id_t oidObjectID); + + bool GetByTaskID(taskid_t tTaskID, TTaskInfoEntry& rInfo) const; + + size_t GetCount() const; + bool IsEmpty() const; + + void Clear(); + + // modifications management + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + void ClearModifications(); + + private: +#pragma warning(push) +#pragma warning(disable:4251) + std::vector m_vTaskInfos; + mutable TRemovedObjects m_setRemovedTasks; +#pragma warning(pop) + object_id_t m_oidLastObjectID; + }; +} + +#endif Index: src/libchcore/TTaskLocalStats.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskLocalStats.cpp (.../TTaskLocalStats.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TTaskLocalStats.cpp (.../TTaskLocalStats.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,143 +1,143 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskLocalStatsInfo.cpp -/// @date 2011/03/28 -/// @brief Contains implementation of classes responsible for maintaining local task stats. -// ============================================================================ -#include "stdafx.h" -#include "TTaskLocalStats.h" -#include "TSubTaskStatsInfo.h" -#include -#include "TTaskStatsSnapshot.h" -#include "ISerializerContainer.h" -#include "ISerializerRowData.h" -#include - -namespace chcore -{ - //////////////////////////////////////////////////////////////////////////////// - // TTasksGlobalStats members - TTaskLocalStatsInfo::TTaskLocalStatsInfo() : - m_tTimer(m_setModifications), - m_bTaskIsRunning(false) - { - m_setModifications[eMod_Added] = true; - } - - TTaskLocalStatsInfo::~TTaskLocalStatsInfo() - { - } - - void TTaskLocalStatsInfo::Clear() - { - m_bTaskIsRunning = false; - m_tTimer.Modify().Reset(); - } - - void TTaskLocalStatsInfo::GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const - { - boost::upgrade_lock lock(m_lock); - UpdateTime(lock); - spSnapshot->SetTaskRunning(m_bTaskIsRunning); - spSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); - } - - void TTaskLocalStatsInfo::MarkAsRunning() - { - boost::unique_lock lock(m_lock); - m_bTaskIsRunning = true; - } - - void TTaskLocalStatsInfo::MarkAsNotRunning() - { - boost::unique_lock lock(m_lock); - m_bTaskIsRunning = false; - } - - bool TTaskLocalStatsInfo::IsRunning() const - { - boost::shared_lock lock(m_lock); - return m_bTaskIsRunning; - } - - void TTaskLocalStatsInfo::EnableTimeTracking() - { - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Start(); - } - - void TTaskLocalStatsInfo::DisableTimeTracking() - { - boost::unique_lock lock(m_lock); - m_tTimer.Modify().Stop(); - } - - void TTaskLocalStatsInfo::UpdateTime(boost::upgrade_lock& lock) const - { - // if the timer is not running then there is no point modifying timer object - if (m_tTimer.Get().IsRunning()) - { - boost::upgrade_to_unique_lock lock_upgraded(lock); - m_tTimer.Modify().Tick(); - } - } - - void TTaskLocalStatsInfo::Store(const ISerializerContainerPtr& spContainer) const - { - boost::shared_lock lock(m_lock); - InitColumns(spContainer); - - bool bAdded = m_setModifications[eMod_Added]; - if (m_setModifications.any()) - { - ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); - if (bAdded || m_setModifications[eMod_Timer]) - { - rRow.SetValue(_T("elapsed_time"), m_tTimer.Get().GetTotalTime()); - m_setModifications.reset(); - } - } - } - - void TTaskLocalStatsInfo::Load(const ISerializerContainerPtr& spContainer) - { - boost::unique_lock lock(m_lock); - - InitColumns(spContainer); - ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); - if (spRowReader->Next()) - { - unsigned long long ullTime = 0; - spRowReader->GetValue(_T("elapsed_time"), ullTime); - m_tTimer.Modify().Init(ullTime); - - m_setModifications.reset(); - } - } - - void TTaskLocalStatsInfo::InitColumns(const ISerializerContainerPtr& spContainer) const - { - IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); - if (rColumns.IsEmpty()) - { - rColumns.AddColumn(_T("id"), ColumnType::value); - rColumns.AddColumn(_T("elapsed_time"), IColumnsDefinition::eType_ulonglong); - } - } -} +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskLocalStatsInfo.cpp +/// @date 2011/03/28 +/// @brief Contains implementation of classes responsible for maintaining local task stats. +// ============================================================================ +#include "stdafx.h" +#include "TTaskLocalStats.h" +#include "TSubTaskStatsInfo.h" +#include +#include "TTaskStatsSnapshot.h" +#include "ISerializerContainer.h" +#include "ISerializerRowData.h" +#include + +namespace chcore +{ + //////////////////////////////////////////////////////////////////////////////// + // TTasksGlobalStats members + TTaskLocalStatsInfo::TTaskLocalStatsInfo() : + m_tTimer(m_setModifications), + m_bTaskIsRunning(false) + { + m_setModifications[eMod_Added] = true; + } + + TTaskLocalStatsInfo::~TTaskLocalStatsInfo() + { + } + + void TTaskLocalStatsInfo::Clear() + { + m_bTaskIsRunning = false; + m_tTimer.Modify().Reset(); + } + + void TTaskLocalStatsInfo::GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const + { + boost::upgrade_lock lock(m_lock); + UpdateTime(lock); + spSnapshot->SetTaskRunning(m_bTaskIsRunning); + spSnapshot->SetTimeElapsed(m_tTimer.Get().GetTotalTime()); + } + + void TTaskLocalStatsInfo::MarkAsRunning() + { + boost::unique_lock lock(m_lock); + m_bTaskIsRunning = true; + } + + void TTaskLocalStatsInfo::MarkAsNotRunning() + { + boost::unique_lock lock(m_lock); + m_bTaskIsRunning = false; + } + + bool TTaskLocalStatsInfo::IsRunning() const + { + boost::shared_lock lock(m_lock); + return m_bTaskIsRunning; + } + + void TTaskLocalStatsInfo::EnableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Start(); + } + + void TTaskLocalStatsInfo::DisableTimeTracking() + { + boost::unique_lock lock(m_lock); + m_tTimer.Modify().Stop(); + } + + void TTaskLocalStatsInfo::UpdateTime(boost::upgrade_lock& lock) const + { + // if the timer is not running then there is no point modifying timer object + if (m_tTimer.Get().IsRunning()) + { + boost::upgrade_to_unique_lock lock_upgraded(lock); + m_tTimer.Modify().Tick(); + } + } + + void TTaskLocalStatsInfo::Store(const ISerializerContainerPtr& spContainer) const + { + boost::shared_lock lock(m_lock); + InitColumns(spContainer); + + bool bAdded = m_setModifications[eMod_Added]; + if (m_setModifications.any()) + { + ISerializerRowData& rRow = spContainer->GetRow(0, bAdded); + if (bAdded || m_setModifications[eMod_Timer]) + { + rRow.SetValue(_T("elapsed_time"), m_tTimer.Get().GetTotalTime()); + m_setModifications.reset(); + } + } + } + + void TTaskLocalStatsInfo::Load(const ISerializerContainerPtr& spContainer) + { + boost::unique_lock lock(m_lock); + + InitColumns(spContainer); + ISerializerRowReaderPtr spRowReader = spContainer->GetRowReader(); + if (spRowReader->Next()) + { + unsigned long long ullTime = 0; + spRowReader->GetValue(_T("elapsed_time"), ullTime); + m_tTimer.Modify().Init(ullTime); + + m_setModifications.reset(); + } + } + + void TTaskLocalStatsInfo::InitColumns(const ISerializerContainerPtr& spContainer) const + { + IColumnsDefinition& rColumns = spContainer->GetColumnsDefinition(); + if (rColumns.IsEmpty()) + { + rColumns.AddColumn(_T("id"), ColumnType::value); + rColumns.AddColumn(_T("elapsed_time"), IColumnsDefinition::eType_ulonglong); + } + } +} Index: src/libchcore/TTaskLocalStats.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskLocalStats.h (.../TTaskLocalStats.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TTaskLocalStats.h (.../TTaskLocalStats.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,95 +1,95 @@ -// ============================================================================ -// Copyright (C) 2001-2011 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskLocalStatsInfo.h -/// @date 2011/03/28 -/// @brief Contains classes responsible for maintaining local task stats. -// ============================================================================ -#ifndef __TTASKLOCALSTATS_H__ -#define __TTASKLOCALSTATS_H__ - -#include "TSubTaskStatsInfo.h" -#include "TTaskStatsSnapshot.h" -#include "TSharedModificationTracker.h" -#include "IRunningTimeControl.h" - -namespace chcore -{ - class TTaskLocalStatsInfo; - class TTaskStatsSnapshot; - - class TTaskLocalStatsInfo : public IRunningTimeControl - { - public: - TTaskLocalStatsInfo(); - ~TTaskLocalStatsInfo(); - - void Clear(); - void GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const; - - bool IsRunning() const; - - void Store(const ISerializerContainerPtr& spContainer) const; - void Load(const ISerializerContainerPtr& spContainer); - - void InitColumns(const ISerializerContainerPtr& spContainer) const; - - protected: - // running/not running state - virtual void MarkAsRunning() override; - virtual void MarkAsNotRunning() override; - - // time tracking - virtual void EnableTimeTracking() override; - virtual void DisableTimeTracking() override; - -#pragma warning(push) -#pragma warning(disable: 4251) - void UpdateTime(boost::upgrade_lock& lock) const; -#pragma warning(pop) - - private: - TTaskLocalStatsInfo(const TTaskLocalStatsInfo&); - TTaskLocalStatsInfo& operator=(const TTaskLocalStatsInfo&); - - private: - enum EModifications - { - eMod_Added, - eMod_Timer, - - eMod_Last - }; - - typedef std::bitset Bitset; - mutable Bitset m_setModifications; - - volatile bool m_bTaskIsRunning; - - mutable TSharedModificationTracker m_tTimer; - -#pragma warning(push) -#pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; -#pragma warning(pop) - - friend class TScopedRunningTimeTracker; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2011 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskLocalStatsInfo.h +/// @date 2011/03/28 +/// @brief Contains classes responsible for maintaining local task stats. +// ============================================================================ +#ifndef __TTASKLOCALSTATS_H__ +#define __TTASKLOCALSTATS_H__ + +#include "TSubTaskStatsInfo.h" +#include "TTaskStatsSnapshot.h" +#include "TSharedModificationTracker.h" +#include "IRunningTimeControl.h" + +namespace chcore +{ + class TTaskLocalStatsInfo; + class TTaskStatsSnapshot; + + class TTaskLocalStatsInfo : public IRunningTimeControl + { + public: + TTaskLocalStatsInfo(); + ~TTaskLocalStatsInfo(); + + void Clear(); + void GetSnapshot(TTaskStatsSnapshotPtr& spSnapshot) const; + + bool IsRunning() const; + + void Store(const ISerializerContainerPtr& spContainer) const; + void Load(const ISerializerContainerPtr& spContainer); + + void InitColumns(const ISerializerContainerPtr& spContainer) const; + + protected: + // running/not running state + virtual void MarkAsRunning() override; + virtual void MarkAsNotRunning() override; + + // time tracking + virtual void EnableTimeTracking() override; + virtual void DisableTimeTracking() override; + +#pragma warning(push) +#pragma warning(disable: 4251) + void UpdateTime(boost::upgrade_lock& lock) const; +#pragma warning(pop) + + private: + TTaskLocalStatsInfo(const TTaskLocalStatsInfo&); + TTaskLocalStatsInfo& operator=(const TTaskLocalStatsInfo&); + + private: + enum EModifications + { + eMod_Added, + eMod_Timer, + + eMod_Last + }; + + typedef std::bitset Bitset; + mutable Bitset m_setModifications; + + volatile bool m_bTaskIsRunning; + + mutable TSharedModificationTracker m_tTimer; + +#pragma warning(push) +#pragma warning(disable: 4251) + mutable boost::shared_mutex m_lock; +#pragma warning(pop) + + friend class TScopedRunningTimeTracker; + }; +} + +#endif Index: src/libchcore/TTaskManagerStatsSnapshot.cpp =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskManagerStatsSnapshot.cpp (.../TTaskManagerStatsSnapshot.cpp) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TTaskManagerStatsSnapshot.cpp (.../TTaskManagerStatsSnapshot.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,215 +1,215 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskManagerStatsSnapshot.cpp -/// @date 2012/2/26 -/// @brief Contains class responsible for holding task manager stats. -// ============================================================================ -#include "stdafx.h" -#include "TTaskManagerStatsSnapshot.h" -#include "MathFunctions.h" -#include "EngineConstants.h" - -namespace chcore -{ - //////////////////////////////////////////////////////////////////////////////// - // class TTaskManagerStatsSnapshot - - TTaskManagerStatsSnapshot::TTaskManagerStatsSnapshot() : - m_stRunningTasks(0), - m_bCacheFilled(false), - m_ullProcessedCount(0), - m_ullTotalCount(0), - m_ullProcessedSize(0), - m_ullTotalSize(0), - m_dCountSpeed(0.0), - m_dSizeSpeed(0.0), - m_dCombinedProgress(0.0), - m_dAvgCountSpeed(0.0), - m_dAvgSizeSpeed(0.0) - { - } - - void TTaskManagerStatsSnapshot::Clear() - { - m_stRunningTasks = 0; - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dCountSpeed = 0.0; - m_dSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_dAvgCountSpeed = 0.0; - m_dAvgSizeSpeed = 0.0; - - m_vTasksSnapshots.clear(); - } - - void TTaskManagerStatsSnapshot::AddTaskStats(const TTaskStatsSnapshotPtr& spStats) - { - m_vTasksSnapshots.push_back(spStats); - } - - size_t TTaskManagerStatsSnapshot::GetTaskStatsCount() const - { - return m_vTasksSnapshots.size(); - } - - TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsAt(size_t stIndex) const - { - if (stIndex >= m_vTasksSnapshots.size()) - return TTaskStatsSnapshotPtr(); - - return m_vTasksSnapshots[stIndex]; - } - - TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsForTaskID(taskid_t tTaskID) const - { - for(TTaskStatsSnapshotPtr spStats : m_vTasksSnapshots) - { - if (spStats->GetTaskID() == tTaskID) - return spStats; - } - - return TTaskStatsSnapshotPtr(); - } - - - void TTaskManagerStatsSnapshot::CalculateProgressAndSpeeds() const - { - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dCountSpeed = 0.0; - m_dSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_dAvgCountSpeed = 0.0; - m_dAvgSizeSpeed = 0.0; - - for(TTaskStatsSnapshotPtr spTaskStats : m_vTasksSnapshots) - { - m_ullProcessedCount += spTaskStats->GetProcessedCount(); - m_ullTotalCount += spTaskStats->GetTotalCount(); - - m_ullProcessedSize += spTaskStats->GetProcessedSize(); - m_ullTotalSize += spTaskStats->GetTotalSize(); - - if(spTaskStats->IsTaskRunning()) - { - m_dCountSpeed += spTaskStats->GetCountSpeed(); - m_dSizeSpeed += spTaskStats->GetSizeSpeed(); - } - - m_dAvgCountSpeed += spTaskStats->GetAvgCountSpeed(); - m_dAvgSizeSpeed += spTaskStats->GetAvgSizeSpeed(); - } - - if(!m_vTasksSnapshots.empty()) - { - m_dAvgCountSpeed /= m_vTasksSnapshots.size(); - m_dAvgSizeSpeed /= m_vTasksSnapshots.size(); - } - - // we're treating each of the items as 4k object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = AssumedFileMinDataSize * m_ullProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = AssumedFileMinDataSize * m_ullTotalCount + m_ullTotalSize; - - if (ullTotal != 0) - m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); - - m_bCacheFilled = true; - } - - unsigned long long TTaskManagerStatsSnapshot::GetProcessedCount() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullProcessedCount; - } - - unsigned long long TTaskManagerStatsSnapshot::GetTotalCount() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullTotalCount; - } - - unsigned long long TTaskManagerStatsSnapshot::GetProcessedSize() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullProcessedSize; - } - - unsigned long long TTaskManagerStatsSnapshot::GetTotalSize() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullTotalSize; - } - - double TTaskManagerStatsSnapshot::GetCountSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dCountSpeed; - } - - double TTaskManagerStatsSnapshot::GetSizeSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dSizeSpeed; - } - - double TTaskManagerStatsSnapshot::GetCombinedProgress() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dCombinedProgress; - } - - double TTaskManagerStatsSnapshot::GetAvgCountSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dAvgCountSpeed; - } - - double TTaskManagerStatsSnapshot::GetAvgSizeSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dAvgSizeSpeed; - } -} +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskManagerStatsSnapshot.cpp +/// @date 2012/2/26 +/// @brief Contains class responsible for holding task manager stats. +// ============================================================================ +#include "stdafx.h" +#include "TTaskManagerStatsSnapshot.h" +#include "MathFunctions.h" +#include "EngineConstants.h" + +namespace chcore +{ + //////////////////////////////////////////////////////////////////////////////// + // class TTaskManagerStatsSnapshot + + TTaskManagerStatsSnapshot::TTaskManagerStatsSnapshot() : + m_stRunningTasks(0), + m_bCacheFilled(false), + m_ullProcessedCount(0), + m_ullTotalCount(0), + m_ullProcessedSize(0), + m_ullTotalSize(0), + m_dCountSpeed(0.0), + m_dSizeSpeed(0.0), + m_dCombinedProgress(0.0), + m_dAvgCountSpeed(0.0), + m_dAvgSizeSpeed(0.0) + { + } + + void TTaskManagerStatsSnapshot::Clear() + { + m_stRunningTasks = 0; + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dCountSpeed = 0.0; + m_dSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_dAvgCountSpeed = 0.0; + m_dAvgSizeSpeed = 0.0; + + m_vTasksSnapshots.clear(); + } + + void TTaskManagerStatsSnapshot::AddTaskStats(const TTaskStatsSnapshotPtr& spStats) + { + m_vTasksSnapshots.push_back(spStats); + } + + size_t TTaskManagerStatsSnapshot::GetTaskStatsCount() const + { + return m_vTasksSnapshots.size(); + } + + TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsAt(size_t stIndex) const + { + if (stIndex >= m_vTasksSnapshots.size()) + return TTaskStatsSnapshotPtr(); + + return m_vTasksSnapshots[stIndex]; + } + + TTaskStatsSnapshotPtr TTaskManagerStatsSnapshot::GetTaskStatsForTaskID(taskid_t tTaskID) const + { + for(TTaskStatsSnapshotPtr spStats : m_vTasksSnapshots) + { + if (spStats->GetTaskID() == tTaskID) + return spStats; + } + + return TTaskStatsSnapshotPtr(); + } + + + void TTaskManagerStatsSnapshot::CalculateProgressAndSpeeds() const + { + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dCountSpeed = 0.0; + m_dSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_dAvgCountSpeed = 0.0; + m_dAvgSizeSpeed = 0.0; + + for(TTaskStatsSnapshotPtr spTaskStats : m_vTasksSnapshots) + { + m_ullProcessedCount += spTaskStats->GetProcessedCount(); + m_ullTotalCount += spTaskStats->GetTotalCount(); + + m_ullProcessedSize += spTaskStats->GetProcessedSize(); + m_ullTotalSize += spTaskStats->GetTotalSize(); + + if(spTaskStats->IsTaskRunning()) + { + m_dCountSpeed += spTaskStats->GetCountSpeed(); + m_dSizeSpeed += spTaskStats->GetSizeSpeed(); + } + + m_dAvgCountSpeed += spTaskStats->GetAvgCountSpeed(); + m_dAvgSizeSpeed += spTaskStats->GetAvgSizeSpeed(); + } + + if(!m_vTasksSnapshots.empty()) + { + m_dAvgCountSpeed /= m_vTasksSnapshots.size(); + m_dAvgSizeSpeed /= m_vTasksSnapshots.size(); + } + + // we're treating each of the items as 4k object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = AssumedFileMinDataSize * m_ullProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = AssumedFileMinDataSize * m_ullTotalCount + m_ullTotalSize; + + if (ullTotal != 0) + m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); + + m_bCacheFilled = true; + } + + unsigned long long TTaskManagerStatsSnapshot::GetProcessedCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullProcessedCount; + } + + unsigned long long TTaskManagerStatsSnapshot::GetTotalCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullTotalCount; + } + + unsigned long long TTaskManagerStatsSnapshot::GetProcessedSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullProcessedSize; + } + + unsigned long long TTaskManagerStatsSnapshot::GetTotalSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullTotalSize; + } + + double TTaskManagerStatsSnapshot::GetCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dCountSpeed; + } + + double TTaskManagerStatsSnapshot::GetSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dSizeSpeed; + } + + double TTaskManagerStatsSnapshot::GetCombinedProgress() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dCombinedProgress; + } + + double TTaskManagerStatsSnapshot::GetAvgCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dAvgCountSpeed; + } + + double TTaskManagerStatsSnapshot::GetAvgSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dAvgSizeSpeed; + } +} Index: src/libchcore/TTaskManagerStatsSnapshot.h =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskManagerStatsSnapshot.h (.../TTaskManagerStatsSnapshot.h) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TTaskManagerStatsSnapshot.h (.../TTaskManagerStatsSnapshot.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,91 +1,91 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskManagerStatsSnapshot.h -/// @date 2012/2/26 -/// @brief Contains class responsible for holding task manager stats. -// ============================================================================ -#ifndef __TTASKMANAGERSTATSSNAPSHOT_H__ -#define __TTASKMANAGERSTATSSNAPSHOT_H__ - -#include "libchcore.h" -#include "TTaskStatsSnapshot.h" - -namespace chcore -{ - class LIBCHCORE_API TTaskManagerStatsSnapshot - { - public: - TTaskManagerStatsSnapshot(); - TTaskManagerStatsSnapshot(const TTaskManagerStatsSnapshot& rSrc) = delete; - - TTaskManagerStatsSnapshot& operator=(const TTaskManagerStatsSnapshot& rSrc) = delete; - - void Clear(); - - void AddTaskStats(const TTaskStatsSnapshotPtr& spStats); - size_t GetTaskStatsCount() const; - TTaskStatsSnapshotPtr GetTaskStatsAt(size_t stIndex) const; - TTaskStatsSnapshotPtr GetTaskStatsForTaskID(taskid_t tTaskID) const; - - size_t GetRunningTasks() const { return m_stRunningTasks; } - void SetRunningTasks(size_t stRunningTasks) { m_stRunningTasks = stRunningTasks; } - - unsigned long long GetProcessedCount() const; - unsigned long long GetTotalCount() const; - unsigned long long GetProcessedSize() const; - unsigned long long GetTotalSize() const; - - double GetCountSpeed() const; - double GetAvgCountSpeed() const; - double GetSizeSpeed() const; - double GetAvgSizeSpeed() const; - - double GetCombinedProgress() const; - - private: - void CalculateProgressAndSpeeds() const; - - private: - size_t m_stRunningTasks; - -#pragma warning(push) -#pragma warning(disable: 4251) - std::vector m_vTasksSnapshots; -#pragma warning(pop) - - // cache for items calculated on-demand - mutable bool m_bCacheFilled; - mutable unsigned long long m_ullProcessedCount; - mutable unsigned long long m_ullTotalCount; - mutable unsigned long long m_ullProcessedSize; - mutable unsigned long long m_ullTotalSize; - - mutable double m_dCountSpeed; - mutable double m_dSizeSpeed; - - mutable double m_dAvgCountSpeed; - mutable double m_dAvgSizeSpeed; - - mutable double m_dCombinedProgress; - }; - - typedef std::shared_ptr TTaskManagerStatsSnapshotPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskManagerStatsSnapshot.h +/// @date 2012/2/26 +/// @brief Contains class responsible for holding task manager stats. +// ============================================================================ +#ifndef __TTASKMANAGERSTATSSNAPSHOT_H__ +#define __TTASKMANAGERSTATSSNAPSHOT_H__ + +#include "libchcore.h" +#include "TTaskStatsSnapshot.h" + +namespace chcore +{ + class LIBCHCORE_API TTaskManagerStatsSnapshot + { + public: + TTaskManagerStatsSnapshot(); + TTaskManagerStatsSnapshot(const TTaskManagerStatsSnapshot& rSrc) = delete; + + TTaskManagerStatsSnapshot& operator=(const TTaskManagerStatsSnapshot& rSrc) = delete; + + void Clear(); + + void AddTaskStats(const TTaskStatsSnapshotPtr& spStats); + size_t GetTaskStatsCount() const; + TTaskStatsSnapshotPtr GetTaskStatsAt(size_t stIndex) const; + TTaskStatsSnapshotPtr GetTaskStatsForTaskID(taskid_t tTaskID) const; + + size_t GetRunningTasks() const { return m_stRunningTasks; } + void SetRunningTasks(size_t stRunningTasks) { m_stRunningTasks = stRunningTasks; } + + unsigned long long GetProcessedCount() const; + unsigned long long GetTotalCount() const; + unsigned long long GetProcessedSize() const; + unsigned long long GetTotalSize() const; + + double GetCountSpeed() const; + double GetAvgCountSpeed() const; + double GetSizeSpeed() const; + double GetAvgSizeSpeed() const; + + double GetCombinedProgress() const; + + private: + void CalculateProgressAndSpeeds() const; + + private: + size_t m_stRunningTasks; + +#pragma warning(push) +#pragma warning(disable: 4251) + std::vector m_vTasksSnapshots; +#pragma warning(pop) + + // cache for items calculated on-demand + mutable bool m_bCacheFilled; + mutable unsigned long long m_ullProcessedCount; + mutable unsigned long long m_ullTotalCount; + mutable unsigned long long m_ullProcessedSize; + mutable unsigned long long m_ullTotalSize; + + mutable double m_dCountSpeed; + mutable double m_dSizeSpeed; + + mutable double m_dAvgCountSpeed; + mutable double m_dAvgSizeSpeed; + + mutable double m_dCombinedProgress; + }; + + typedef std::shared_ptr TTaskManagerStatsSnapshotPtr; +} + +#endif Index: src/libchcore/TTaskOperationPlan.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskOperationPlan.cpp (.../TTaskOperationPlan.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TTaskOperationPlan.cpp (.../TTaskOperationPlan.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,68 +1,68 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskOperationPlan.cpp -/// @date 2010/09/18 -/// @brief File contains implementation of class handling planning of the entire operation -// ============================================================================ -#include "stdafx.h" -#include "TTaskOperationPlan.h" -#include "TCoreException.h" -#include "ErrorCodes.h" -#include - -namespace chcore -{ - //////////////////////////////////////////////////////////////////////////// - // class TOperationPlan - - TOperationPlan::TOperationPlan() : - m_eOperation(eOperation_None) - { - } - - TOperationPlan::TOperationPlan(const TOperationPlan& rSrc) : - m_eOperation(eOperation_None) - { - SetOperationType(rSrc.GetOperationType()); - } - - TOperationPlan::~TOperationPlan() - { - } - - TOperationPlan& TOperationPlan::operator=(const TOperationPlan& rSrc) - { - if (this != &rSrc) - SetOperationType(rSrc.GetOperationType()); - - return *this; - } - - void TOperationPlan::SetOperationType(EOperationType eOperation) - { - boost::unique_lock lock(m_lock); - m_eOperation = eOperation; - } - - EOperationType TOperationPlan::GetOperationType() const - { - boost::shared_lock lock(m_lock); - return m_eOperation; - } -} +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskOperationPlan.cpp +/// @date 2010/09/18 +/// @brief File contains implementation of class handling planning of the entire operation +// ============================================================================ +#include "stdafx.h" +#include "TTaskOperationPlan.h" +#include "TCoreException.h" +#include "ErrorCodes.h" +#include + +namespace chcore +{ + //////////////////////////////////////////////////////////////////////////// + // class TOperationPlan + + TOperationPlan::TOperationPlan() : + m_eOperation(eOperation_None) + { + } + + TOperationPlan::TOperationPlan(const TOperationPlan& rSrc) : + m_eOperation(eOperation_None) + { + SetOperationType(rSrc.GetOperationType()); + } + + TOperationPlan::~TOperationPlan() + { + } + + TOperationPlan& TOperationPlan::operator=(const TOperationPlan& rSrc) + { + if (this != &rSrc) + SetOperationType(rSrc.GetOperationType()); + + return *this; + } + + void TOperationPlan::SetOperationType(EOperationType eOperation) + { + boost::unique_lock lock(m_lock); + m_eOperation = eOperation; + } + + EOperationType TOperationPlan::GetOperationType() const + { + boost::shared_lock lock(m_lock); + return m_eOperation; + } +} Index: src/libchcore/TTaskOperationPlan.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskOperationPlan.h (.../TTaskOperationPlan.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TTaskOperationPlan.h (.../TTaskOperationPlan.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,56 +1,56 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskOperationPlan.cpp -/// @date 2010/09/18 -/// @brief File contains class handling planning of the entire operation. -// ============================================================================ -#ifndef __TTASKOPERATIONPLAN_H__ -#define __TTASKOPERATIONPLAN_H__ - -#include "libchcore.h" -#include "EOperationTypes.h" - -namespace chcore -{ - /////////////////////////////////////////////////////////////////////////// - // TOperationPlan - - // class describes the sub-operations to be performed - class LIBCHCORE_API TOperationPlan - { - public: - TOperationPlan(); - TOperationPlan(const TOperationPlan& rSrc); - ~TOperationPlan(); - - TOperationPlan& operator=(const TOperationPlan& rSrc); - - void SetOperationType(EOperationType eOperation); - EOperationType GetOperationType() const; - - private: - EOperationType m_eOperation; -#pragma warning(push) -#pragma warning(disable: 4251) - mutable boost::shared_mutex m_lock; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskOperationPlan.cpp +/// @date 2010/09/18 +/// @brief File contains class handling planning of the entire operation. +// ============================================================================ +#ifndef __TTASKOPERATIONPLAN_H__ +#define __TTASKOPERATIONPLAN_H__ + +#include "libchcore.h" +#include "EOperationTypes.h" + +namespace chcore +{ + /////////////////////////////////////////////////////////////////////////// + // TOperationPlan + + // class describes the sub-operations to be performed + class LIBCHCORE_API TOperationPlan + { + public: + TOperationPlan(); + TOperationPlan(const TOperationPlan& rSrc); + ~TOperationPlan(); + + TOperationPlan& operator=(const TOperationPlan& rSrc); + + void SetOperationType(EOperationType eOperation); + EOperationType GetOperationType() const; + + private: + EOperationType m_eOperation; +#pragma warning(push) +#pragma warning(disable: 4251) + mutable boost::shared_mutex m_lock; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TTaskStatsSnapshot.cpp =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskStatsSnapshot.cpp (.../TTaskStatsSnapshot.cpp) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TTaskStatsSnapshot.cpp (.../TTaskStatsSnapshot.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,223 +1,223 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskStatsSnapshot.cpp -/// @date 2012/02/26 -/// @brief Contains class responsible for holding task stats. -// ============================================================================ -#include "stdafx.h" -#include "TTaskStatsSnapshot.h" -#include "MathFunctions.h" -#include "EngineConstants.h" - -namespace chcore -{ - //////////////////////////////////////////////////////////////////////////////// - // TTaskStatsSnapshot members - - TTaskStatsSnapshot::TTaskStatsSnapshot() : - m_tSubTasksStats(), - m_bTaskIsRunning(false), - m_ullTimeElapsed(0), - m_iThreadPriority(0), - m_strDestinationPath(), - m_filters(), - m_eTaskState(eTaskState_None), - m_strTaskID(), - m_eOperationType(eOperation_None), - m_bIgnoreDirectories(false), - m_bCreateEmptyFiles(false), - m_ullCurrentBufferSize(0), - m_bCacheFilled(false), - m_ullProcessedCount(0), - m_ullTotalCount(0), - m_ullProcessedSize(0), - m_ullTotalSize(0), - m_dTaskCountSpeed(0.0), - m_dTaskSizeSpeed(0.0), - m_dCombinedProgress(0.0), - m_uiBufferCount(0), - m_tTaskID(0) - { - } - - void TTaskStatsSnapshot::Clear() - { - m_tSubTasksStats.Clear(); - m_bTaskIsRunning = false; - m_ullTimeElapsed = 0; - m_iThreadPriority = 0; - m_strDestinationPath.Clear(); - m_filters.Clear(); - m_eTaskState = eTaskState_None; - m_strTaskID.Clear(); - m_eOperationType = eOperation_None; - m_bIgnoreDirectories = false; - m_bCreateEmptyFiles = false; - m_ullCurrentBufferSize = 0; - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dTaskCountSpeed = 0.0; - m_dTaskSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - m_uiBufferCount = 0; - } - - void TTaskStatsSnapshot::CalculateProgressAndSpeeds() const - { - m_bCacheFilled = false; - m_ullProcessedCount = 0; - m_ullTotalCount = 0; - m_ullProcessedSize = 0; - m_ullTotalSize = 0; - m_dTaskCountSpeed = 0.0; - m_dTaskSizeSpeed = 0.0; - m_dCombinedProgress = 0.0; - - size_t stCount = m_tSubTasksStats.GetSubTaskSnapshotCount(); - for (size_t stIndex = 0; stIndex < stCount; ++stIndex) - { - TSubTaskStatsSnapshotPtr spSubtaskStats = m_tSubTasksStats.GetSubTaskSnapshotAt(stIndex); - - m_ullProcessedCount += spSubtaskStats->GetProcessedCount(); - m_ullTotalCount += spSubtaskStats->GetTotalCount(); - - m_ullProcessedSize += spSubtaskStats->GetProcessedSize(); - m_ullTotalSize += spSubtaskStats->GetTotalSize(); - - if(IsTaskRunning()) - { - m_dTaskCountSpeed += spSubtaskStats->GetCountSpeed(); - m_dTaskSizeSpeed += spSubtaskStats->GetSizeSpeed(); - } - } - - // we're treating each of the items as 4096 bytes object to process - // to have some balance between items' count and items' size in - // progress information - unsigned long long ullProcessed = AssumedFileMinDataSize * m_ullProcessedCount + m_ullProcessedSize; - unsigned long long ullTotal = AssumedFileMinDataSize * m_ullTotalCount + m_ullTotalSize; - - if (ullTotal != 0) - m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); - - m_bCacheFilled = true; - } - - unsigned long long TTaskStatsSnapshot::GetProcessedCount() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullProcessedCount; - } - - unsigned long long TTaskStatsSnapshot::GetTotalCount() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullTotalCount; - } - - unsigned long long TTaskStatsSnapshot::GetProcessedSize() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullProcessedSize; - } - - unsigned long long TTaskStatsSnapshot::GetTotalSize() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_ullTotalSize; - } - - double TTaskStatsSnapshot::GetCountSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dTaskCountSpeed; - } - - double TTaskStatsSnapshot::GetSizeSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dTaskSizeSpeed; - } - - double TTaskStatsSnapshot::GetCombinedProgress() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - return m_dCombinedProgress; - } - - TString TTaskStatsSnapshot::GetSourcePath() const - { - return m_strSrcPath; - } - - void TTaskStatsSnapshot::SetSourcePath(const TString& pathSrc) - { - m_strSrcPath = pathSrc; - } - - double TTaskStatsSnapshot::GetAvgCountSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - if (m_ullTimeElapsed) - return Math::Div64(m_ullProcessedCount, m_ullTimeElapsed / 1000.0); - else - return 0.0; - } - - double TTaskStatsSnapshot::GetAvgSizeSpeed() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - if (m_ullTimeElapsed) - return Math::Div64(m_ullProcessedSize, m_ullTimeElapsed / 1000.0); - else - return 0.0; - } - - unsigned long long TTaskStatsSnapshot::GetEstimatedTotalTime() const - { - if (!m_bCacheFilled) - CalculateProgressAndSpeeds(); - - if (m_dCombinedProgress == 0.0) - return std::numeric_limits::max(); - else - return (unsigned long long)(m_ullTimeElapsed / m_dCombinedProgress); - } -} +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskStatsSnapshot.cpp +/// @date 2012/02/26 +/// @brief Contains class responsible for holding task stats. +// ============================================================================ +#include "stdafx.h" +#include "TTaskStatsSnapshot.h" +#include "MathFunctions.h" +#include "EngineConstants.h" + +namespace chcore +{ + //////////////////////////////////////////////////////////////////////////////// + // TTaskStatsSnapshot members + + TTaskStatsSnapshot::TTaskStatsSnapshot() : + m_tSubTasksStats(), + m_bTaskIsRunning(false), + m_ullTimeElapsed(0), + m_iThreadPriority(0), + m_strDestinationPath(), + m_filters(), + m_eTaskState(eTaskState_None), + m_strTaskID(), + m_eOperationType(eOperation_None), + m_bIgnoreDirectories(false), + m_bCreateEmptyFiles(false), + m_ullCurrentBufferSize(0), + m_bCacheFilled(false), + m_ullProcessedCount(0), + m_ullTotalCount(0), + m_ullProcessedSize(0), + m_ullTotalSize(0), + m_dTaskCountSpeed(0.0), + m_dTaskSizeSpeed(0.0), + m_dCombinedProgress(0.0), + m_uiBufferCount(0), + m_tTaskID(0) + { + } + + void TTaskStatsSnapshot::Clear() + { + m_tSubTasksStats.Clear(); + m_bTaskIsRunning = false; + m_ullTimeElapsed = 0; + m_iThreadPriority = 0; + m_strDestinationPath.Clear(); + m_filters.Clear(); + m_eTaskState = eTaskState_None; + m_strTaskID.Clear(); + m_eOperationType = eOperation_None; + m_bIgnoreDirectories = false; + m_bCreateEmptyFiles = false; + m_ullCurrentBufferSize = 0; + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dTaskCountSpeed = 0.0; + m_dTaskSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + m_uiBufferCount = 0; + } + + void TTaskStatsSnapshot::CalculateProgressAndSpeeds() const + { + m_bCacheFilled = false; + m_ullProcessedCount = 0; + m_ullTotalCount = 0; + m_ullProcessedSize = 0; + m_ullTotalSize = 0; + m_dTaskCountSpeed = 0.0; + m_dTaskSizeSpeed = 0.0; + m_dCombinedProgress = 0.0; + + size_t stCount = m_tSubTasksStats.GetSubTaskSnapshotCount(); + for (size_t stIndex = 0; stIndex < stCount; ++stIndex) + { + TSubTaskStatsSnapshotPtr spSubtaskStats = m_tSubTasksStats.GetSubTaskSnapshotAt(stIndex); + + m_ullProcessedCount += spSubtaskStats->GetProcessedCount(); + m_ullTotalCount += spSubtaskStats->GetTotalCount(); + + m_ullProcessedSize += spSubtaskStats->GetProcessedSize(); + m_ullTotalSize += spSubtaskStats->GetTotalSize(); + + if(IsTaskRunning()) + { + m_dTaskCountSpeed += spSubtaskStats->GetCountSpeed(); + m_dTaskSizeSpeed += spSubtaskStats->GetSizeSpeed(); + } + } + + // we're treating each of the items as 4096 bytes object to process + // to have some balance between items' count and items' size in + // progress information + unsigned long long ullProcessed = AssumedFileMinDataSize * m_ullProcessedCount + m_ullProcessedSize; + unsigned long long ullTotal = AssumedFileMinDataSize * m_ullTotalCount + m_ullTotalSize; + + if (ullTotal != 0) + m_dCombinedProgress = Math::Div64(ullProcessed, ullTotal); + + m_bCacheFilled = true; + } + + unsigned long long TTaskStatsSnapshot::GetProcessedCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullProcessedCount; + } + + unsigned long long TTaskStatsSnapshot::GetTotalCount() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullTotalCount; + } + + unsigned long long TTaskStatsSnapshot::GetProcessedSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullProcessedSize; + } + + unsigned long long TTaskStatsSnapshot::GetTotalSize() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_ullTotalSize; + } + + double TTaskStatsSnapshot::GetCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dTaskCountSpeed; + } + + double TTaskStatsSnapshot::GetSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dTaskSizeSpeed; + } + + double TTaskStatsSnapshot::GetCombinedProgress() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + return m_dCombinedProgress; + } + + TString TTaskStatsSnapshot::GetSourcePath() const + { + return m_strSrcPath; + } + + void TTaskStatsSnapshot::SetSourcePath(const TString& pathSrc) + { + m_strSrcPath = pathSrc; + } + + double TTaskStatsSnapshot::GetAvgCountSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + if (m_ullTimeElapsed) + return Math::Div64(m_ullProcessedCount, m_ullTimeElapsed / 1000.0); + else + return 0.0; + } + + double TTaskStatsSnapshot::GetAvgSizeSpeed() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + if (m_ullTimeElapsed) + return Math::Div64(m_ullProcessedSize, m_ullTimeElapsed / 1000.0); + else + return 0.0; + } + + unsigned long long TTaskStatsSnapshot::GetEstimatedTotalTime() const + { + if (!m_bCacheFilled) + CalculateProgressAndSpeeds(); + + if (m_dCombinedProgress == 0.0) + return std::numeric_limits::max(); + else + return (unsigned long long)(m_ullTimeElapsed / m_dCombinedProgress); + } +} Index: src/libchcore/TTaskStatsSnapshot.h =================================================================== diff -u -r2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTaskStatsSnapshot.h (.../TTaskStatsSnapshot.h) (revision 2a34de9ddfcfb4a1ed4c61ece641d37b91c23b6b) +++ src/libchcore/TTaskStatsSnapshot.h (.../TTaskStatsSnapshot.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,148 +1,148 @@ -// ============================================================================ -// Copyright (C) 2001-2012 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TTaskStatsSnapshot.h -/// @date 2012/02/26 -/// @brief Contains class responsible for holding task stats. -// ============================================================================ -#ifndef __TTASKSTATSSNAPSHOT_H__ -#define __TTASKSTATSSNAPSHOT_H__ - -#include "libchcore.h" -#include "TSubTaskStatsInfo.h" -#include "TSubTaskArrayStatsSnapshot.h" -#include "TFileFiltersArray.h" -#include "EOperationTypes.h" -#include "ETaskCurrentState.h" -#include "TaskID.h" - -namespace chcore -{ - class LIBCHCORE_API TTaskStatsSnapshot - { - public: - TTaskStatsSnapshot(); - - void Clear(); - - // task ID - taskid_t GetTaskID() const { return m_tTaskID; } - void SetTaskID(taskid_t val) { m_tTaskID = val; } - - // subtasks' stats - const TSubTaskArrayStatsSnapshot& GetSubTasksStats() const { return m_tSubTasksStats; } - TSubTaskArrayStatsSnapshot& GetSubTasksStats() { return m_tSubTasksStats; } - - // task running - bool IsTaskRunning() const { return m_bTaskIsRunning; } - void SetTaskRunning(bool bRunning) { m_bTaskIsRunning = bRunning; } - - // time elapsed - unsigned long long GetTimeElapsed() const { return m_ullTimeElapsed; } - void SetTimeElapsed(unsigned long long ullTimeElapsed) { m_ullTimeElapsed = ullTimeElapsed; } - unsigned long long GetEstimatedTotalTime() const; - - // speed and progress - unsigned long long GetProcessedCount() const; - unsigned long long GetTotalCount() const; - unsigned long long GetProcessedSize() const; - unsigned long long GetTotalSize() const; - - double GetCountSpeed() const; - double GetSizeSpeed() const; - double GetAvgCountSpeed() const; - double GetAvgSizeSpeed() const; - - double GetCombinedProgress() const; - - // other properties - int GetThreadPriority() const { return m_iThreadPriority; } - void SetThreadPriority(int val) { m_iThreadPriority = val; } - - TString GetDestinationPath() const { return m_strDestinationPath; } - void SetDestinationPath(const TString& val) { m_strDestinationPath = val; } - - const TFileFiltersArray& GetFilters() const { return m_filters; } - void SetFilters(const TFileFiltersArray& val) { m_filters = val; } - - ETaskCurrentState GetTaskState() const { return m_eTaskState; } - void SetTaskState(ETaskCurrentState val) { m_eTaskState = val; } - - TString GetTaskName() const { return m_strTaskID; } - void SetTaskName(const TString& val) { m_strTaskID = val; } - - EOperationType GetOperationType() const { return m_eOperationType; } - void SetOperationType(EOperationType val) { m_eOperationType = val; } - - bool GetIgnoreDirectories() const { return m_bIgnoreDirectories; } - void SetIgnoreDirectories(bool val) { m_bIgnoreDirectories = val; } - - bool GetCreateEmptyFiles() const { return m_bCreateEmptyFiles; } - void SetCreateEmptyFiles(bool val) { m_bCreateEmptyFiles = val; } - - void SetCurrentBufferSize(unsigned long long ullSize) { m_ullCurrentBufferSize = ullSize; } - unsigned long long GetCurrentBufferSize() const { return m_ullCurrentBufferSize; } - - unsigned int GetBufferCount() const { return m_uiBufferCount; } - void SetBufferCount(unsigned int uiBufferCount) { m_uiBufferCount = uiBufferCount; } - - TString GetSourcePath() const; - void SetSourcePath(const TString& pathSrc); - - private: - void CalculateProgressAndSpeeds() const; - - private: - TSubTaskArrayStatsSnapshot m_tSubTasksStats; - - taskid_t m_tTaskID; - - bool m_bTaskIsRunning; - - TString m_strSrcPath; - unsigned long long m_ullTimeElapsed; - - int m_iThreadPriority; - TString m_strDestinationPath; - TFileFiltersArray m_filters; - ETaskCurrentState m_eTaskState; - TString m_strTaskID; - EOperationType m_eOperationType; - bool m_bIgnoreDirectories; - bool m_bCreateEmptyFiles; - - unsigned long long m_ullCurrentBufferSize; - unsigned int m_uiBufferCount; - - // cache for items calculated on-demand - mutable bool m_bCacheFilled; - mutable unsigned long long m_ullProcessedCount; - mutable unsigned long long m_ullTotalCount; - mutable unsigned long long m_ullProcessedSize; - mutable unsigned long long m_ullTotalSize; - - mutable double m_dTaskCountSpeed; - mutable double m_dTaskSizeSpeed; - - mutable double m_dCombinedProgress; - }; - - typedef std::shared_ptr TTaskStatsSnapshotPtr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2012 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TTaskStatsSnapshot.h +/// @date 2012/02/26 +/// @brief Contains class responsible for holding task stats. +// ============================================================================ +#ifndef __TTASKSTATSSNAPSHOT_H__ +#define __TTASKSTATSSNAPSHOT_H__ + +#include "libchcore.h" +#include "TSubTaskStatsInfo.h" +#include "TSubTaskArrayStatsSnapshot.h" +#include "TFileFiltersArray.h" +#include "EOperationTypes.h" +#include "ETaskCurrentState.h" +#include "TaskID.h" + +namespace chcore +{ + class LIBCHCORE_API TTaskStatsSnapshot + { + public: + TTaskStatsSnapshot(); + + void Clear(); + + // task ID + taskid_t GetTaskID() const { return m_tTaskID; } + void SetTaskID(taskid_t val) { m_tTaskID = val; } + + // subtasks' stats + const TSubTaskArrayStatsSnapshot& GetSubTasksStats() const { return m_tSubTasksStats; } + TSubTaskArrayStatsSnapshot& GetSubTasksStats() { return m_tSubTasksStats; } + + // task running + bool IsTaskRunning() const { return m_bTaskIsRunning; } + void SetTaskRunning(bool bRunning) { m_bTaskIsRunning = bRunning; } + + // time elapsed + unsigned long long GetTimeElapsed() const { return m_ullTimeElapsed; } + void SetTimeElapsed(unsigned long long ullTimeElapsed) { m_ullTimeElapsed = ullTimeElapsed; } + unsigned long long GetEstimatedTotalTime() const; + + // speed and progress + unsigned long long GetProcessedCount() const; + unsigned long long GetTotalCount() const; + unsigned long long GetProcessedSize() const; + unsigned long long GetTotalSize() const; + + double GetCountSpeed() const; + double GetSizeSpeed() const; + double GetAvgCountSpeed() const; + double GetAvgSizeSpeed() const; + + double GetCombinedProgress() const; + + // other properties + int GetThreadPriority() const { return m_iThreadPriority; } + void SetThreadPriority(int val) { m_iThreadPriority = val; } + + TString GetDestinationPath() const { return m_strDestinationPath; } + void SetDestinationPath(const TString& val) { m_strDestinationPath = val; } + + const TFileFiltersArray& GetFilters() const { return m_filters; } + void SetFilters(const TFileFiltersArray& val) { m_filters = val; } + + ETaskCurrentState GetTaskState() const { return m_eTaskState; } + void SetTaskState(ETaskCurrentState val) { m_eTaskState = val; } + + TString GetTaskName() const { return m_strTaskID; } + void SetTaskName(const TString& val) { m_strTaskID = val; } + + EOperationType GetOperationType() const { return m_eOperationType; } + void SetOperationType(EOperationType val) { m_eOperationType = val; } + + bool GetIgnoreDirectories() const { return m_bIgnoreDirectories; } + void SetIgnoreDirectories(bool val) { m_bIgnoreDirectories = val; } + + bool GetCreateEmptyFiles() const { return m_bCreateEmptyFiles; } + void SetCreateEmptyFiles(bool val) { m_bCreateEmptyFiles = val; } + + void SetCurrentBufferSize(unsigned long long ullSize) { m_ullCurrentBufferSize = ullSize; } + unsigned long long GetCurrentBufferSize() const { return m_ullCurrentBufferSize; } + + unsigned int GetBufferCount() const { return m_uiBufferCount; } + void SetBufferCount(unsigned int uiBufferCount) { m_uiBufferCount = uiBufferCount; } + + TString GetSourcePath() const; + void SetSourcePath(const TString& pathSrc); + + private: + void CalculateProgressAndSpeeds() const; + + private: + TSubTaskArrayStatsSnapshot m_tSubTasksStats; + + taskid_t m_tTaskID; + + bool m_bTaskIsRunning; + + TString m_strSrcPath; + unsigned long long m_ullTimeElapsed; + + int m_iThreadPriority; + TString m_strDestinationPath; + TFileFiltersArray m_filters; + ETaskCurrentState m_eTaskState; + TString m_strTaskID; + EOperationType m_eOperationType; + bool m_bIgnoreDirectories; + bool m_bCreateEmptyFiles; + + unsigned long long m_ullCurrentBufferSize; + unsigned int m_uiBufferCount; + + // cache for items calculated on-demand + mutable bool m_bCacheFilled; + mutable unsigned long long m_ullProcessedCount; + mutable unsigned long long m_ullTotalCount; + mutable unsigned long long m_ullProcessedSize; + mutable unsigned long long m_ullTotalSize; + + mutable double m_dTaskCountSpeed; + mutable double m_dTaskSizeSpeed; + + mutable double m_dCombinedProgress; + }; + + typedef std::shared_ptr TTaskStatsSnapshotPtr; +} + +#endif Index: src/libchcore/TTimestampProviderTickCount.cpp =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTimestampProviderTickCount.cpp (.../TTimestampProviderTickCount.cpp) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TTimestampProviderTickCount.cpp (.../TTimestampProviderTickCount.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,41 +1,41 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TTimestampProviderTickCount.h" - -namespace chcore -{ - TTimestampProviderTickCount::TTimestampProviderTickCount() : - m_dwLastTimestamp(0), - m_ullTimestampAdjustment(0) - { - } - - unsigned long long TTimestampProviderTickCount::GetCurrentTimestamp() const - { - DWORD dwTimestamp = GetTickCount(); - if (dwTimestamp < m_dwLastTimestamp) - { - m_ullTimestampAdjustment += (1ULL << 32); - } - m_dwLastTimestamp = dwTimestamp; - - return m_ullTimestampAdjustment + dwTimestamp; - } -} +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TTimestampProviderTickCount.h" + +namespace chcore +{ + TTimestampProviderTickCount::TTimestampProviderTickCount() : + m_dwLastTimestamp(0), + m_ullTimestampAdjustment(0) + { + } + + unsigned long long TTimestampProviderTickCount::GetCurrentTimestamp() const + { + DWORD dwTimestamp = GetTickCount(); + if (dwTimestamp < m_dwLastTimestamp) + { + m_ullTimestampAdjustment += (1ULL << 32); + } + m_dwLastTimestamp = dwTimestamp; + + return m_ullTimestampAdjustment + dwTimestamp; + } +} Index: src/libchcore/TTimestampProviderTickCount.h =================================================================== diff -u -r62d767936f1675e1db51174f53c91484fe691937 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TTimestampProviderTickCount.h (.../TTimestampProviderTickCount.h) (revision 62d767936f1675e1db51174f53c91484fe691937) +++ src/libchcore/TTimestampProviderTickCount.h (.../TTimestampProviderTickCount.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,40 +1,40 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TTIMESTAMPPROVIDERTICKCOUNT_H__ -#define __TTIMESTAMPPROVIDERTICKCOUNT_H__ - -#include "ITimestampProvider.h" -#include "libchcore.h" - -namespace chcore -{ - class LIBCHCORE_API TTimestampProviderTickCount : public ITimestampProvider - { - public: - TTimestampProviderTickCount(); - - virtual unsigned long long GetCurrentTimestamp() const; - - private: - mutable unsigned long long m_ullTimestampAdjustment; - mutable DWORD m_dwLastTimestamp; - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TTIMESTAMPPROVIDERTICKCOUNT_H__ +#define __TTIMESTAMPPROVIDERTICKCOUNT_H__ + +#include "ITimestampProvider.h" +#include "libchcore.h" + +namespace chcore +{ + class LIBCHCORE_API TTimestampProviderTickCount : public ITimestampProvider + { + public: + TTimestampProviderTickCount(); + + virtual unsigned long long GetCurrentTimestamp() const; + + private: + mutable unsigned long long m_ullTimestampAdjustment; + mutable DWORD m_dwLastTimestamp; + }; +} + +#endif Index: src/libchcore/TWin32ErrorFormatter.cpp =================================================================== diff -u -r0db67d6b8b989871a621b6f34ddee09559184d01 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TWin32ErrorFormatter.cpp (.../TWin32ErrorFormatter.cpp) (revision 0db67d6b8b989871a621b6f34ddee09559184d01) +++ src/libchcore/TWin32ErrorFormatter.cpp (.../TWin32ErrorFormatter.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,67 +1,67 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TWin32ErrorFormatter.h" -#include -#include - -namespace chcore -{ - TString TWin32ErrorFormatter::FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback) - { - return FormatWin32ErrorCodeWithModule(dwErrorCode, nullptr, bUseNumberFallback); - } - - TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback) - { - TString strError = FormatWin32ErrorCode(dwErrorCode, false); - if (strError.IsEmpty()) - return FormatWin32ErrorCodeWithModule(dwErrorCode, GetModuleHandle(pszModuleName), bUseNumberFallback); - - return strError; - } - - TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback) - { - const DWORD dwMaxError = 1024; - - TString strData; - wchar_t* pszBuffer = strData.GetBuffer(dwMaxError); - - DWORD dwPos = 0; - if(hModule) - dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, hModule, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, nullptr); - else - dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, nullptr); - - if (dwPos == 0xffffffff || dwPos == 0) - { - int iPos = 0; - if (bUseNumberFallback) - iPos = _sntprintf_s(pszBuffer, dwMaxError, _TRUNCATE, _T("ErrorCode: 0x%lx"), dwErrorCode); - strData.ReleaseBufferSetLength(iPos < 0 ? 0 : iPos); - } - else - strData.ReleaseBufferSetLength(std::min(dwPos, dwMaxError - 1)); - - strData.TrimRightSelf(_T("\r\n")); - - return strData; - } -} +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TWin32ErrorFormatter.h" +#include +#include + +namespace chcore +{ + TString TWin32ErrorFormatter::FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback) + { + return FormatWin32ErrorCodeWithModule(dwErrorCode, nullptr, bUseNumberFallback); + } + + TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback) + { + TString strError = FormatWin32ErrorCode(dwErrorCode, false); + if (strError.IsEmpty()) + return FormatWin32ErrorCodeWithModule(dwErrorCode, GetModuleHandle(pszModuleName), bUseNumberFallback); + + return strError; + } + + TString TWin32ErrorFormatter::FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback) + { + const DWORD dwMaxError = 1024; + + TString strData; + wchar_t* pszBuffer = strData.GetBuffer(dwMaxError); + + DWORD dwPos = 0; + if(hModule) + dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, hModule, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, nullptr); + else + dwPos = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pszBuffer, dwMaxError - 1, nullptr); + + if (dwPos == 0xffffffff || dwPos == 0) + { + int iPos = 0; + if (bUseNumberFallback) + iPos = _sntprintf_s(pszBuffer, dwMaxError, _TRUNCATE, _T("ErrorCode: 0x%lx"), dwErrorCode); + strData.ReleaseBufferSetLength(iPos < 0 ? 0 : iPos); + } + else + strData.ReleaseBufferSetLength(std::min(dwPos, dwMaxError - 1)); + + strData.TrimRightSelf(_T("\r\n")); + + return strData; + } +} Index: src/libchcore/TWin32ErrorFormatter.h =================================================================== diff -u -re96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TWin32ErrorFormatter.h (.../TWin32ErrorFormatter.h) (revision e96806b7f8ff7ca7e9f4afbea603e6351a3dc3e3) +++ src/libchcore/TWin32ErrorFormatter.h (.../TWin32ErrorFormatter.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,38 +1,38 @@ -// ============================================================================ -// Copyright (C) 2001-2015 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TWIN32ERRORFORMATTER_H__ -#define __TWIN32ERRORFORMATTER_H__ - -#include "libchcore.h" -#include "TString.h" - -namespace chcore -{ - class LIBCHCORE_API TWin32ErrorFormatter - { - public: - static TString FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback); - static TString FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback); - - private: - static TString FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback); - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2015 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TWIN32ERRORFORMATTER_H__ +#define __TWIN32ERRORFORMATTER_H__ + +#include "libchcore.h" +#include "TString.h" + +namespace chcore +{ + class LIBCHCORE_API TWin32ErrorFormatter + { + public: + static TString FormatWin32ErrorCode(DWORD dwErrorCode, bool bUseNumberFallback); + static TString FormatWin32ErrorCodeWithFallback(DWORD dwErrorCode, const wchar_t* pszModuleName, bool bUseNumberFallback); + + private: + static TString FormatWin32ErrorCodeWithModule(DWORD dwErrorCode, HMODULE hModule, bool bUseNumberFallback); + }; +} + +#endif Index: src/libchcore/TWorkerThreadController.cpp =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TWorkerThreadController.cpp (.../TWorkerThreadController.cpp) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TWorkerThreadController.cpp (.../TWorkerThreadController.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,221 +1,221 @@ -// ============================================================================ -// Copyright (C) 2001-2010 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TWorkerThreadController.cpp -/// @date 2010/09/04 -/// @brief Contains implementation of class TWorkerThreadController. -// ============================================================================ -#include "stdafx.h" -#include "TWorkerThreadController.h" -#include "TCoreWin32Exception.h" -#include "ErrorCodes.h" -#include - -namespace chcore -{ - TWorkerThreadController::TWorkerThreadController() : - m_hThread(nullptr), - m_hKillThread(nullptr) - { - m_hKillThread = CreateEvent(nullptr, TRUE, FALSE, nullptr); - if (!m_hKillThread) - throw TCoreWin32Exception(eErr_CannotCreateEvent, GetLastError(), L"Failed to create event", LOCATION); - } - - TWorkerThreadController::~TWorkerThreadController() - { - try - { - StopThread(); - CloseHandle(m_hKillThread); - } - catch (...) - { - } - } - - void TWorkerThreadController::StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority) - { - boost::upgrade_lock lock(m_lock); - - RemoveZombieData(lock); - - if (m_hThread) - throw TCoreException(eErr_ThreadAlreadyStarted, L"Thread was already started", LOCATION); - - // just in case reset the kill event to avoid early death of the thread to be created - if (!::ResetEvent(m_hKillThread)) - throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); - - boost::upgrade_to_unique_lock lock_upgraded(lock); - - m_hThread = ::CreateThread(nullptr, 0, pThreadFunction, pThreadParam, CREATE_SUSPENDED, nullptr); - if (!m_hThread) - throw TCoreWin32Exception(eErr_CannotCreateThread, GetLastError(), L"Failed to create thread", LOCATION); - - if (!::SetThreadPriority(m_hThread, iPriority)) - { - DWORD dwLastError = GetLastError(); - - CloseHandle(m_hThread); - m_hThread = nullptr; - - throw TCoreWin32Exception(eErr_CannotChangeThreadPriority, dwLastError, L"Failed to set thread priority", LOCATION); - } - - if (::ResumeThread(m_hThread) == (DWORD)-1) - { - DWORD dwLastError = GetLastError(); - - CloseHandle(m_hThread); - m_hThread = nullptr; - - throw TCoreWin32Exception(eErr_CannotResumeThread, dwLastError, L"Failed to resume thread", LOCATION); - } - } - - void TWorkerThreadController::SignalThreadToStop() - { - boost::upgrade_lock lock(m_lock); - - SignalThreadToStop(lock); - } - - void TWorkerThreadController::WaitForThreadToExit(DWORD dwMiliseconds) - { - boost::upgrade_lock lock(m_lock); - - DWORD dwRes = WaitForSingleObject(m_hThread, dwMiliseconds); - if (dwRes == WAIT_OBJECT_0) - { - if (!::ResetEvent(m_hKillThread)) - throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); - - boost::upgrade_to_unique_lock lock_upgraded(lock); - - CloseHandle(m_hThread); - m_hThread = nullptr; - } - else - throw TCoreWin32Exception(eErr_WaitingFailed, GetLastError(), L"Waiting failed", LOCATION); - } - - void TWorkerThreadController::StopThread() - { - boost::upgrade_lock lock(m_lock); - - SignalThreadToStop(lock); - - WaitForThreadToExit(lock); - } - - void TWorkerThreadController::ChangePriority(int iPriority) - { - boost::upgrade_lock lock(m_lock); - - RemoveZombieData(lock); - - if (!m_hThread) - return; - - if (m_hThread != nullptr) - { - if (::SuspendThread(m_hThread) == (DWORD)-1) - throw TCoreWin32Exception(eErr_CannotSuspendThread, GetLastError(), L"Failed to suspend thread", LOCATION); - - if (!::SetThreadPriority(m_hThread, iPriority)) - { - DWORD dwLastError = GetLastError(); - - // try to resume thread priority cannot be changed - DWORD dwResult = ::ResumeThread(m_hThread); - dwResult; // to avoid warnings in release builds - BOOST_ASSERT(dwResult != (DWORD)-1); - - throw TCoreWin32Exception(eErr_CannotChangeThreadPriority, dwLastError, L"Failed to set thread priority", LOCATION); - } - - if (::ResumeThread(m_hThread) == (DWORD)-1) - throw TCoreWin32Exception(eErr_CannotResumeThread, GetLastError(), L"Failed to resume thread", LOCATION); - } - } - - bool TWorkerThreadController::KillRequested(DWORD dwWaitForSignal) - { - // this method does not have any mutexes, because it should be only called from within the thread - // being controlled by this object. This implies that the thread is alive and running, - // this class must exist because it should not be possible for the thread to exist and be active - // when this object is out of scope, and so the m_hKillThread should be non-nullptr, since it is being destroyed - // in destructor. - return (m_hKillThread && WaitForSingleObject(m_hKillThread, dwWaitForSignal) == WAIT_OBJECT_0); - } - - HANDLE TWorkerThreadController::GetKillThreadHandle() const - { - return m_hKillThread; - } - - void TWorkerThreadController::RemoveZombieData(boost::upgrade_lock& rUpgradeLock) - { - // if thread is already stopped, then there is nothing to do - if (!m_hThread) - return; - - // thread already stopped? - if (WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0) - { - if (!::ResetEvent(m_hKillThread)) - throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); - - boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); - - CloseHandle(m_hThread); - m_hThread = nullptr; - } - } - - void TWorkerThreadController::SignalThreadToStop(boost::upgrade_lock& rUpgradeLock) - { - RemoveZombieData(rUpgradeLock); - if (!m_hThread) - return; - - if (!::SetEvent(m_hKillThread)) - throw TCoreWin32Exception(eErr_CannotSetEvent, GetLastError(), L"Failed to set event", LOCATION); - } - - void TWorkerThreadController::WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock, DWORD dwMiliseconds) - { - if (!m_hThread) - return; - - DWORD dwRes = WaitForSingleObject(m_hThread, dwMiliseconds); - if (dwRes == WAIT_OBJECT_0) - { - if (!::ResetEvent(m_hKillThread)) - throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); - - boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); - - CloseHandle(m_hThread); - m_hThread = nullptr; - } - else - throw TCoreWin32Exception(eErr_WaitingFailed, GetLastError(), L"Failed to wait for object", LOCATION); - } -} +// ============================================================================ +// Copyright (C) 2001-2010 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TWorkerThreadController.cpp +/// @date 2010/09/04 +/// @brief Contains implementation of class TWorkerThreadController. +// ============================================================================ +#include "stdafx.h" +#include "TWorkerThreadController.h" +#include "TCoreWin32Exception.h" +#include "ErrorCodes.h" +#include + +namespace chcore +{ + TWorkerThreadController::TWorkerThreadController() : + m_hThread(nullptr), + m_hKillThread(nullptr) + { + m_hKillThread = CreateEvent(nullptr, TRUE, FALSE, nullptr); + if (!m_hKillThread) + throw TCoreWin32Exception(eErr_CannotCreateEvent, GetLastError(), L"Failed to create event", LOCATION); + } + + TWorkerThreadController::~TWorkerThreadController() + { + try + { + StopThread(); + CloseHandle(m_hKillThread); + } + catch (...) + { + } + } + + void TWorkerThreadController::StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority) + { + boost::upgrade_lock lock(m_lock); + + RemoveZombieData(lock); + + if (m_hThread) + throw TCoreException(eErr_ThreadAlreadyStarted, L"Thread was already started", LOCATION); + + // just in case reset the kill event to avoid early death of the thread to be created + if (!::ResetEvent(m_hKillThread)) + throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); + + boost::upgrade_to_unique_lock lock_upgraded(lock); + + m_hThread = ::CreateThread(nullptr, 0, pThreadFunction, pThreadParam, CREATE_SUSPENDED, nullptr); + if (!m_hThread) + throw TCoreWin32Exception(eErr_CannotCreateThread, GetLastError(), L"Failed to create thread", LOCATION); + + if (!::SetThreadPriority(m_hThread, iPriority)) + { + DWORD dwLastError = GetLastError(); + + CloseHandle(m_hThread); + m_hThread = nullptr; + + throw TCoreWin32Exception(eErr_CannotChangeThreadPriority, dwLastError, L"Failed to set thread priority", LOCATION); + } + + if (::ResumeThread(m_hThread) == (DWORD)-1) + { + DWORD dwLastError = GetLastError(); + + CloseHandle(m_hThread); + m_hThread = nullptr; + + throw TCoreWin32Exception(eErr_CannotResumeThread, dwLastError, L"Failed to resume thread", LOCATION); + } + } + + void TWorkerThreadController::SignalThreadToStop() + { + boost::upgrade_lock lock(m_lock); + + SignalThreadToStop(lock); + } + + void TWorkerThreadController::WaitForThreadToExit(DWORD dwMiliseconds) + { + boost::upgrade_lock lock(m_lock); + + DWORD dwRes = WaitForSingleObject(m_hThread, dwMiliseconds); + if (dwRes == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); + + boost::upgrade_to_unique_lock lock_upgraded(lock); + + CloseHandle(m_hThread); + m_hThread = nullptr; + } + else + throw TCoreWin32Exception(eErr_WaitingFailed, GetLastError(), L"Waiting failed", LOCATION); + } + + void TWorkerThreadController::StopThread() + { + boost::upgrade_lock lock(m_lock); + + SignalThreadToStop(lock); + + WaitForThreadToExit(lock); + } + + void TWorkerThreadController::ChangePriority(int iPriority) + { + boost::upgrade_lock lock(m_lock); + + RemoveZombieData(lock); + + if (!m_hThread) + return; + + if (m_hThread != nullptr) + { + if (::SuspendThread(m_hThread) == (DWORD)-1) + throw TCoreWin32Exception(eErr_CannotSuspendThread, GetLastError(), L"Failed to suspend thread", LOCATION); + + if (!::SetThreadPriority(m_hThread, iPriority)) + { + DWORD dwLastError = GetLastError(); + + // try to resume thread priority cannot be changed + DWORD dwResult = ::ResumeThread(m_hThread); + dwResult; // to avoid warnings in release builds + BOOST_ASSERT(dwResult != (DWORD)-1); + + throw TCoreWin32Exception(eErr_CannotChangeThreadPriority, dwLastError, L"Failed to set thread priority", LOCATION); + } + + if (::ResumeThread(m_hThread) == (DWORD)-1) + throw TCoreWin32Exception(eErr_CannotResumeThread, GetLastError(), L"Failed to resume thread", LOCATION); + } + } + + bool TWorkerThreadController::KillRequested(DWORD dwWaitForSignal) + { + // this method does not have any mutexes, because it should be only called from within the thread + // being controlled by this object. This implies that the thread is alive and running, + // this class must exist because it should not be possible for the thread to exist and be active + // when this object is out of scope, and so the m_hKillThread should be non-nullptr, since it is being destroyed + // in destructor. + return (m_hKillThread && WaitForSingleObject(m_hKillThread, dwWaitForSignal) == WAIT_OBJECT_0); + } + + HANDLE TWorkerThreadController::GetKillThreadHandle() const + { + return m_hKillThread; + } + + void TWorkerThreadController::RemoveZombieData(boost::upgrade_lock& rUpgradeLock) + { + // if thread is already stopped, then there is nothing to do + if (!m_hThread) + return; + + // thread already stopped? + if (WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); + + boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + + CloseHandle(m_hThread); + m_hThread = nullptr; + } + } + + void TWorkerThreadController::SignalThreadToStop(boost::upgrade_lock& rUpgradeLock) + { + RemoveZombieData(rUpgradeLock); + if (!m_hThread) + return; + + if (!::SetEvent(m_hKillThread)) + throw TCoreWin32Exception(eErr_CannotSetEvent, GetLastError(), L"Failed to set event", LOCATION); + } + + void TWorkerThreadController::WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock, DWORD dwMiliseconds) + { + if (!m_hThread) + return; + + DWORD dwRes = WaitForSingleObject(m_hThread, dwMiliseconds); + if (dwRes == WAIT_OBJECT_0) + { + if (!::ResetEvent(m_hKillThread)) + throw TCoreWin32Exception(eErr_CannotResetEvent, GetLastError(), L"Failed to reset event", LOCATION); + + boost::upgrade_to_unique_lock lock_upgraded(rUpgradeLock); + + CloseHandle(m_hThread); + m_hThread = nullptr; + } + else + throw TCoreWin32Exception(eErr_WaitingFailed, GetLastError(), L"Failed to wait for object", LOCATION); + } +} Index: src/libchcore/TWorkerThreadController.h =================================================================== diff -u -r8a2ff3b2b71b45fb525e030167e62f316cb32869 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TWorkerThreadController.h (.../TWorkerThreadController.h) (revision 8a2ff3b2b71b45fb525e030167e62f316cb32869) +++ src/libchcore/TWorkerThreadController.h (.../TWorkerThreadController.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,74 +1,74 @@ -// ============================================================================ -// Copyright (C) 2001-2009 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -/// @file TWorkerThreadController.h -/// @date 2010/09/04 -/// @brief Contains class TWorkerThreadController. -// ============================================================================ -#ifndef __TWORKERTHREADCONTROLLER_H__ -#define __TWORKERTHREADCONTROLLER_H__ - -#include "libchcore.h" - -/////////////////////////////////////////////////////////////////////////// -// TWorkerThreadController -namespace boost -{ - template class upgrade_lock; -} -namespace chcore -{ - class LIBCHCORE_API TWorkerThreadController - { - public: - TWorkerThreadController(); - ~TWorkerThreadController(); - - // methods to be used outside of the thread being controlled - void StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority = THREAD_PRIORITY_NORMAL); - void SignalThreadToStop(); - void WaitForThreadToExit(DWORD dwMiliseconds = INFINITE); - - void StopThread(); - void ChangePriority(int iPriority); - - // methods to be used only inside the thread being controlled - bool KillRequested(DWORD dwWaitForSignal = 0); - HANDLE GetKillThreadHandle() const; - - protected: - void RemoveZombieData(boost::upgrade_lock& rUpgradeLock); - - void SignalThreadToStop(boost::upgrade_lock& rUpgradeLock); - void WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock, DWORD dwMiliseconds = INFINITE); - - private: - TWorkerThreadController(const TWorkerThreadController&); - TWorkerThreadController& operator=(const TWorkerThreadController&); - - private: - HANDLE m_hThread; - HANDLE m_hKillThread; -#pragma warning(push) -#pragma warning(disable: 4251) - boost::shared_mutex m_lock; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2009 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +/// @file TWorkerThreadController.h +/// @date 2010/09/04 +/// @brief Contains class TWorkerThreadController. +// ============================================================================ +#ifndef __TWORKERTHREADCONTROLLER_H__ +#define __TWORKERTHREADCONTROLLER_H__ + +#include "libchcore.h" + +/////////////////////////////////////////////////////////////////////////// +// TWorkerThreadController +namespace boost +{ + template class upgrade_lock; +} +namespace chcore +{ + class LIBCHCORE_API TWorkerThreadController + { + public: + TWorkerThreadController(); + ~TWorkerThreadController(); + + // methods to be used outside of the thread being controlled + void StartThread(PTHREAD_START_ROUTINE pThreadFunction, PVOID pThreadParam, int iPriority = THREAD_PRIORITY_NORMAL); + void SignalThreadToStop(); + void WaitForThreadToExit(DWORD dwMiliseconds = INFINITE); + + void StopThread(); + void ChangePriority(int iPriority); + + // methods to be used only inside the thread being controlled + bool KillRequested(DWORD dwWaitForSignal = 0); + HANDLE GetKillThreadHandle() const; + + protected: + void RemoveZombieData(boost::upgrade_lock& rUpgradeLock); + + void SignalThreadToStop(boost::upgrade_lock& rUpgradeLock); + void WaitForThreadToExit(boost::upgrade_lock& rUpgradeLock, DWORD dwMiliseconds = INFINITE); + + private: + TWorkerThreadController(const TWorkerThreadController&); + TWorkerThreadController& operator=(const TWorkerThreadController&); + + private: + HANDLE m_hThread; + HANDLE m_hKillThread; +#pragma warning(push) +#pragma warning(disable: 4251) + boost::shared_mutex m_lock; +#pragma warning(pop) + }; +} + +#endif Index: src/libchcore/TaskID.h =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/TaskID.h (.../TaskID.h) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/TaskID.h (.../TaskID.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,30 +1,30 @@ -// ============================================================================ -// Copyright (C) 2001-2013 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TASKID_H__ -#define __TASKID_H__ - -#include "SerializerDataTypes.h" - -namespace chcore -{ - typedef object_id_t taskid_t; - enum ENoTaskID { NoTaskID = 0 }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2013 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TASKID_H__ +#define __TASKID_H__ + +#include "SerializerDataTypes.h" + +namespace chcore +{ + typedef object_id_t taskid_t; + enum ENoTaskID { NoTaskID = 0 }; +} + +#endif Index: src/libchcore/Tests/OverlappedCallbacksTests.cpp =================================================================== diff -u -r3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/OverlappedCallbacksTests.cpp (.../OverlappedCallbacksTests.cpp) (revision 3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4) +++ src/libchcore/Tests/OverlappedCallbacksTests.cpp (.../OverlappedCallbacksTests.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,78 +1,78 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../OverlappedCallbacks.h" -#include "../TOverlappedMemoryPool.h" -#include "../../liblogger/TLogFileData.h" -#include "../TOverlappedReader.h" -#include "../TOverlappedWriter.h" - -using namespace chcore; -/* - -TEST(OverlappedCallbackTests, OverlappedReadCompleted_Success) -{ - logger::TLogFileDataPtr spLogData(std::make_shared()); - - TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); - TOverlappedProcessorRangePtr spRange(std::make_shared(0)); - TOverlappedReader queue(spLogData, spBuffers->GetBufferList(), spRange, 4096); - TOverlappedDataBuffer buffer(16384, &queue); - - buffer.InitForRead(0, 1024); - buffer.SetStatusCode(0); - buffer.SetBytesTransferred(234); - buffer.SetParam(&queue); - - OverlappedReadCompleted(ERROR_SUCCESS, 234, &buffer); - - EXPECT_TRUE(buffer.IsLastPart()); - EXPECT_EQ(ERROR_SUCCESS, buffer.GetErrorCode()); - EXPECT_EQ(234, buffer.GetRealDataSize()); -} - -TEST(OverlappedCallbackTests, OverlappedReadCompleted_Failure) -{ - logger::TLogFileDataPtr spLogData(std::make_shared()); - - TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); - TOverlappedProcessorRangePtr spRange(std::make_shared(0)); - TOverlappedReader queue(spLogData, spBuffers->GetBufferList(), spRange, 4096); - TOverlappedDataBuffer buffer(16384, &queue); - - buffer.InitForRead(0, 1024); - buffer.SetStatusCode(0); - buffer.SetBytesTransferred(0); - - OverlappedReadCompleted(ERROR_ACCESS_DENIED, 0, &buffer); - - EXPECT_FALSE(buffer.IsLastPart()); - EXPECT_EQ(ERROR_ACCESS_DENIED, buffer.GetErrorCode()); - EXPECT_EQ(0, buffer.GetRealDataSize()); - - EXPECT_EQ(queue.GetFailedReadBuffer(), &buffer); -}*/ -/* - -TEST(OverlappedCallbackTests, OverlappedWriteCompleted_Success) -{ - logger::TLogFileDataPtr spLogData(std::make_shared()); - - TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); - TOrderedBufferQueuePtr spBuffersToWrite(std::make_shared(0)); - TOverlappedProcessorRangePtr spRange(std::make_shared(0)); - TOverlappedWriter queue(spLogData, spBuffersToWrite, spRange, spBuffers->GetBufferList()); - TOverlappedDataBuffer buffer(16384, &queue); - - buffer.InitForRead(0, 1024); - buffer.SetStatusCode(0); - buffer.SetBytesTransferred(234); - buffer.SetLastPart(true); - buffer.SetRealDataSize(234); - - OverlappedWriteCompleted(ERROR_SUCCESS, 234, &buffer); - - EXPECT_EQ(ERROR_SUCCESS, buffer.GetErrorCode()); - EXPECT_EQ(queue.GetFinishedBuffer(), &buffer); -} -*/ +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../OverlappedCallbacks.h" +#include "../TOverlappedMemoryPool.h" +#include "../../liblogger/TLogFileData.h" +#include "../TOverlappedReader.h" +#include "../TOverlappedWriter.h" + +using namespace chcore; +/* + +TEST(OverlappedCallbackTests, OverlappedReadCompleted_Success) +{ + logger::TLogFileDataPtr spLogData(std::make_shared()); + + TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); + TOverlappedProcessorRangePtr spRange(std::make_shared(0)); + TOverlappedReader queue(spLogData, spBuffers->GetBufferList(), spRange, 4096); + TOverlappedDataBuffer buffer(16384, &queue); + + buffer.InitForRead(0, 1024); + buffer.SetStatusCode(0); + buffer.SetBytesTransferred(234); + buffer.SetParam(&queue); + + OverlappedReadCompleted(ERROR_SUCCESS, 234, &buffer); + + EXPECT_TRUE(buffer.IsLastPart()); + EXPECT_EQ(ERROR_SUCCESS, buffer.GetErrorCode()); + EXPECT_EQ(234, buffer.GetRealDataSize()); +} + +TEST(OverlappedCallbackTests, OverlappedReadCompleted_Failure) +{ + logger::TLogFileDataPtr spLogData(std::make_shared()); + + TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); + TOverlappedProcessorRangePtr spRange(std::make_shared(0)); + TOverlappedReader queue(spLogData, spBuffers->GetBufferList(), spRange, 4096); + TOverlappedDataBuffer buffer(16384, &queue); + + buffer.InitForRead(0, 1024); + buffer.SetStatusCode(0); + buffer.SetBytesTransferred(0); + + OverlappedReadCompleted(ERROR_ACCESS_DENIED, 0, &buffer); + + EXPECT_FALSE(buffer.IsLastPart()); + EXPECT_EQ(ERROR_ACCESS_DENIED, buffer.GetErrorCode()); + EXPECT_EQ(0, buffer.GetRealDataSize()); + + EXPECT_EQ(queue.GetFailedReadBuffer(), &buffer); +}*/ +/* + +TEST(OverlappedCallbackTests, OverlappedWriteCompleted_Success) +{ + logger::TLogFileDataPtr spLogData(std::make_shared()); + + TOverlappedMemoryPoolPtr spBuffers(std::make_shared()); + TOrderedBufferQueuePtr spBuffersToWrite(std::make_shared(0)); + TOverlappedProcessorRangePtr spRange(std::make_shared(0)); + TOverlappedWriter queue(spLogData, spBuffersToWrite, spRange, spBuffers->GetBufferList()); + TOverlappedDataBuffer buffer(16384, &queue); + + buffer.InitForRead(0, 1024); + buffer.SetStatusCode(0); + buffer.SetBytesTransferred(234); + buffer.SetLastPart(true); + buffer.SetRealDataSize(234); + + OverlappedWriteCompleted(ERROR_SUCCESS, 234, &buffer); + + EXPECT_EQ(ERROR_SUCCESS, buffer.GetErrorCode()); + EXPECT_EQ(queue.GetFinishedBuffer(), &buffer); +} +*/ Index: src/libchcore/Tests/TOverlappedDataBufferTests.cpp =================================================================== diff -u -rdcbfdc95eedacd24d8b1d78fa507029ce12a5a63 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TOverlappedDataBufferTests.cpp (.../TOverlappedDataBufferTests.cpp) (revision dcbfdc95eedacd24d8b1d78fa507029ce12a5a63) +++ src/libchcore/Tests/TOverlappedDataBufferTests.cpp (.../TOverlappedDataBufferTests.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,246 +1,246 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TOverlappedDataBuffer.h" -#include "../../liblogger/TLogFileData.h" -#include "../TCoreException.h" - -using namespace chcore; - -/////////////////////////////////////////////////////////////////////////////// -// construction - -TEST(TOverlappedDataBufferTests, Constructor_ZeroSizedBuffer) -{ - EXPECT_THROW(TOverlappedDataBuffer(0, nullptr), TCoreException); -} - -TEST(TOverlappedDataBufferTests, Constructor_NullParam) -{ - TOverlappedDataBuffer buffer(4096, nullptr); - - EXPECT_EQ(nullptr, buffer.GetParam()); -} - -TEST(TOverlappedDataBufferTests, Constructor_NonNullParam) -{ - TOverlappedDataBuffer buffer(4096, (void*)5); - - EXPECT_EQ((void*)5, buffer.GetParam()); -} - -TEST(TOverlappedDataBufferTests, Constructor_SanityTest) -{ - int iParam = 5; - TOverlappedDataBuffer buffer(32768, &iParam); - - EXPECT_NE(nullptr, buffer.GetBufferPtr()); - EXPECT_EQ(32768, buffer.GetBufferSize()); - EXPECT_EQ(0, buffer.GetBytesTransferred()); - EXPECT_EQ(0, buffer.GetErrorCode()); - EXPECT_EQ(0, buffer.GetFilePosition()); - EXPECT_EQ(0, buffer.GetRealDataSize()); - EXPECT_EQ(0, buffer.GetRequestedDataSize()); - EXPECT_EQ(0, buffer.GetStatusCode()); - EXPECT_FALSE(buffer.IsLastPart()); -} - -/////////////////////////////////////////////////////////////////////////////// -// parameter handling - -TEST(TOverlappedDataBufferTests, GetParam) -{ - int iTest = 5; - - TOverlappedDataBuffer buffer(4096, &iTest); - - EXPECT_EQ(&iTest, buffer.GetParam()); -} - -TEST(TOverlappedDataBufferTests, SetParam_GetParam) -{ - int iTest = 5; - - TOverlappedDataBuffer buffer(4096, &iTest); - buffer.SetParam(nullptr); - - EXPECT_EQ(nullptr, buffer.GetParam()); -} - -/////////////////////////////////////////////////////////////////////////////// -// buffer re-initialization - -TEST(TOverlappedDataBufferTests, ReinitializeBuffer_ZeroSize) -{ - TOverlappedDataBuffer buffer(32768, nullptr); - - EXPECT_THROW(buffer.ReinitializeBuffer(0), TCoreException); -} - -TEST(TOverlappedDataBufferTests, ReinitializeBuffer_ReduceSize) -{ - TOverlappedDataBuffer buffer(32768, nullptr); - - buffer.ReinitializeBuffer(16384); - - EXPECT_NE(nullptr, buffer.GetBufferPtr()); - EXPECT_EQ(16384, buffer.GetBufferSize()); -} - -TEST(TOverlappedDataBufferTests, ReinitializeBuffer_IncreaseSize) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.ReinitializeBuffer(32768); - - EXPECT_NE(nullptr, buffer.GetBufferPtr()); - EXPECT_EQ(32768, buffer.GetBufferSize()); -} - -TEST(TOverlappedDataBufferTests, ReinitializeBuffer_SameSize) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - void* pBuffer = buffer.GetBufferPtr(); - - buffer.ReinitializeBuffer(16384); - - EXPECT_EQ(pBuffer, buffer.GetBufferPtr()); -} - -/////////////////////////////////////////////////////////////////////////////// -// other attributes - -TEST(TOverlappedDataBufferTests, SetRequestedDataSize_GetRequestedDataSize) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetRequestedDataSize(123); - - EXPECT_EQ(123, buffer.GetRequestedDataSize()); -} - -TEST(TOverlappedDataBufferTests, SetRealDataSize_GetRealDataSize) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetRealDataSize(123); - - EXPECT_EQ(123, buffer.GetRealDataSize()); -} - -TEST(TOverlappedDataBufferTests, SetLastPart_IsLastPart) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetLastPart(true); - - EXPECT_TRUE(buffer.IsLastPart()); -} - -TEST(TOverlappedDataBufferTests, SetErrorCode_GetErrorCode) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetErrorCode(123); - - EXPECT_EQ(123, buffer.GetErrorCode()); -} - -TEST(TOverlappedDataBufferTests, SetStatusCode_GetStatusCode) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetStatusCode(123); - - EXPECT_EQ(123, buffer.GetStatusCode()); -} - -TEST(TOverlappedDataBufferTests, SetBytesTransferred_GetBytesTransferred) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetBytesTransferred(123); - - EXPECT_EQ(123, buffer.GetBytesTransferred()); -} - -TEST(TOverlappedDataBufferTests, GetFilePosition_SetFilePosition) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetFilePosition(123); - - EXPECT_EQ(123, buffer.GetFilePosition()); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -TEST(TOverlappedDataBufferTests, InitForRead) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetRequestedDataSize(123); - buffer.SetFilePosition(1); - buffer.SetRealDataSize(120); - buffer.SetLastPart(true); - buffer.SetErrorCode(54); - buffer.SetStatusCode(3); - buffer.SetBytesTransferred(12); - - buffer.InitForRead(320, 600); - - EXPECT_EQ(600, buffer.GetRequestedDataSize()); - EXPECT_EQ(320, buffer.GetFilePosition()); - EXPECT_EQ(0, buffer.GetRealDataSize()); - EXPECT_EQ(false, buffer.IsLastPart()); - EXPECT_EQ(0, buffer.GetErrorCode()); - EXPECT_EQ(0, buffer.GetStatusCode()); - EXPECT_EQ(0, buffer.GetBytesTransferred()); -} - -TEST(TOverlappedDataBufferTests, InitForWrite) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetRequestedDataSize(123); - buffer.SetFilePosition(1); - buffer.SetRealDataSize(120); - buffer.SetLastPart(true); - buffer.SetErrorCode(54); - buffer.SetStatusCode(3); - buffer.SetBytesTransferred(12); - - buffer.InitForWrite(); - - EXPECT_EQ(0, buffer.GetErrorCode()); - EXPECT_EQ(0, buffer.GetStatusCode()); - EXPECT_EQ(0, buffer.GetBytesTransferred()); -} - -TEST(TOverlappedDataBufferTests, Reset) -{ - TOverlappedDataBuffer buffer(16384, nullptr); - - buffer.SetRequestedDataSize(123); - buffer.SetFilePosition(1); - buffer.SetRealDataSize(120); - buffer.SetLastPart(true); - buffer.SetErrorCode(54); - buffer.SetStatusCode(3); - buffer.SetBytesTransferred(12); - buffer.SetParam((void*)1); - - buffer.Reset(); - - EXPECT_EQ(0, buffer.GetRequestedDataSize()); - EXPECT_EQ(0, buffer.GetFilePosition()); - EXPECT_EQ(0, buffer.GetRealDataSize()); - EXPECT_EQ(false, buffer.IsLastPart()); - EXPECT_EQ(0, buffer.GetErrorCode()); - EXPECT_EQ(0, buffer.GetStatusCode()); - EXPECT_EQ(0, buffer.GetBytesTransferred()); - EXPECT_EQ(nullptr, buffer.GetParam()); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TOverlappedDataBuffer.h" +#include "../../liblogger/TLogFileData.h" +#include "../TCoreException.h" + +using namespace chcore; + +/////////////////////////////////////////////////////////////////////////////// +// construction + +TEST(TOverlappedDataBufferTests, Constructor_ZeroSizedBuffer) +{ + EXPECT_THROW(TOverlappedDataBuffer(0, nullptr), TCoreException); +} + +TEST(TOverlappedDataBufferTests, Constructor_NullParam) +{ + TOverlappedDataBuffer buffer(4096, nullptr); + + EXPECT_EQ(nullptr, buffer.GetParam()); +} + +TEST(TOverlappedDataBufferTests, Constructor_NonNullParam) +{ + TOverlappedDataBuffer buffer(4096, (void*)5); + + EXPECT_EQ((void*)5, buffer.GetParam()); +} + +TEST(TOverlappedDataBufferTests, Constructor_SanityTest) +{ + int iParam = 5; + TOverlappedDataBuffer buffer(32768, &iParam); + + EXPECT_NE(nullptr, buffer.GetBufferPtr()); + EXPECT_EQ(32768, buffer.GetBufferSize()); + EXPECT_EQ(0, buffer.GetBytesTransferred()); + EXPECT_EQ(0, buffer.GetErrorCode()); + EXPECT_EQ(0, buffer.GetFilePosition()); + EXPECT_EQ(0, buffer.GetRealDataSize()); + EXPECT_EQ(0, buffer.GetRequestedDataSize()); + EXPECT_EQ(0, buffer.GetStatusCode()); + EXPECT_FALSE(buffer.IsLastPart()); +} + +/////////////////////////////////////////////////////////////////////////////// +// parameter handling + +TEST(TOverlappedDataBufferTests, GetParam) +{ + int iTest = 5; + + TOverlappedDataBuffer buffer(4096, &iTest); + + EXPECT_EQ(&iTest, buffer.GetParam()); +} + +TEST(TOverlappedDataBufferTests, SetParam_GetParam) +{ + int iTest = 5; + + TOverlappedDataBuffer buffer(4096, &iTest); + buffer.SetParam(nullptr); + + EXPECT_EQ(nullptr, buffer.GetParam()); +} + +/////////////////////////////////////////////////////////////////////////////// +// buffer re-initialization + +TEST(TOverlappedDataBufferTests, ReinitializeBuffer_ZeroSize) +{ + TOverlappedDataBuffer buffer(32768, nullptr); + + EXPECT_THROW(buffer.ReinitializeBuffer(0), TCoreException); +} + +TEST(TOverlappedDataBufferTests, ReinitializeBuffer_ReduceSize) +{ + TOverlappedDataBuffer buffer(32768, nullptr); + + buffer.ReinitializeBuffer(16384); + + EXPECT_NE(nullptr, buffer.GetBufferPtr()); + EXPECT_EQ(16384, buffer.GetBufferSize()); +} + +TEST(TOverlappedDataBufferTests, ReinitializeBuffer_IncreaseSize) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.ReinitializeBuffer(32768); + + EXPECT_NE(nullptr, buffer.GetBufferPtr()); + EXPECT_EQ(32768, buffer.GetBufferSize()); +} + +TEST(TOverlappedDataBufferTests, ReinitializeBuffer_SameSize) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + void* pBuffer = buffer.GetBufferPtr(); + + buffer.ReinitializeBuffer(16384); + + EXPECT_EQ(pBuffer, buffer.GetBufferPtr()); +} + +/////////////////////////////////////////////////////////////////////////////// +// other attributes + +TEST(TOverlappedDataBufferTests, SetRequestedDataSize_GetRequestedDataSize) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetRequestedDataSize(123); + + EXPECT_EQ(123, buffer.GetRequestedDataSize()); +} + +TEST(TOverlappedDataBufferTests, SetRealDataSize_GetRealDataSize) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetRealDataSize(123); + + EXPECT_EQ(123, buffer.GetRealDataSize()); +} + +TEST(TOverlappedDataBufferTests, SetLastPart_IsLastPart) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetLastPart(true); + + EXPECT_TRUE(buffer.IsLastPart()); +} + +TEST(TOverlappedDataBufferTests, SetErrorCode_GetErrorCode) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetErrorCode(123); + + EXPECT_EQ(123, buffer.GetErrorCode()); +} + +TEST(TOverlappedDataBufferTests, SetStatusCode_GetStatusCode) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetStatusCode(123); + + EXPECT_EQ(123, buffer.GetStatusCode()); +} + +TEST(TOverlappedDataBufferTests, SetBytesTransferred_GetBytesTransferred) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetBytesTransferred(123); + + EXPECT_EQ(123, buffer.GetBytesTransferred()); +} + +TEST(TOverlappedDataBufferTests, GetFilePosition_SetFilePosition) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetFilePosition(123); + + EXPECT_EQ(123, buffer.GetFilePosition()); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// +TEST(TOverlappedDataBufferTests, InitForRead) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetRequestedDataSize(123); + buffer.SetFilePosition(1); + buffer.SetRealDataSize(120); + buffer.SetLastPart(true); + buffer.SetErrorCode(54); + buffer.SetStatusCode(3); + buffer.SetBytesTransferred(12); + + buffer.InitForRead(320, 600); + + EXPECT_EQ(600, buffer.GetRequestedDataSize()); + EXPECT_EQ(320, buffer.GetFilePosition()); + EXPECT_EQ(0, buffer.GetRealDataSize()); + EXPECT_EQ(false, buffer.IsLastPart()); + EXPECT_EQ(0, buffer.GetErrorCode()); + EXPECT_EQ(0, buffer.GetStatusCode()); + EXPECT_EQ(0, buffer.GetBytesTransferred()); +} + +TEST(TOverlappedDataBufferTests, InitForWrite) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetRequestedDataSize(123); + buffer.SetFilePosition(1); + buffer.SetRealDataSize(120); + buffer.SetLastPart(true); + buffer.SetErrorCode(54); + buffer.SetStatusCode(3); + buffer.SetBytesTransferred(12); + + buffer.InitForWrite(); + + EXPECT_EQ(0, buffer.GetErrorCode()); + EXPECT_EQ(0, buffer.GetStatusCode()); + EXPECT_EQ(0, buffer.GetBytesTransferred()); +} + +TEST(TOverlappedDataBufferTests, Reset) +{ + TOverlappedDataBuffer buffer(16384, nullptr); + + buffer.SetRequestedDataSize(123); + buffer.SetFilePosition(1); + buffer.SetRealDataSize(120); + buffer.SetLastPart(true); + buffer.SetErrorCode(54); + buffer.SetStatusCode(3); + buffer.SetBytesTransferred(12); + buffer.SetParam((void*)1); + + buffer.Reset(); + + EXPECT_EQ(0, buffer.GetRequestedDataSize()); + EXPECT_EQ(0, buffer.GetFilePosition()); + EXPECT_EQ(0, buffer.GetRealDataSize()); + EXPECT_EQ(false, buffer.IsLastPart()); + EXPECT_EQ(0, buffer.GetErrorCode()); + EXPECT_EQ(0, buffer.GetStatusCode()); + EXPECT_EQ(0, buffer.GetBytesTransferred()); + EXPECT_EQ(nullptr, buffer.GetParam()); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// Index: src/libchcore/Tests/TestsTBufferSizes.cpp =================================================================== diff -u -rcdc76e1a95383dff63a5254aeb8d37035028512c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTBufferSizes.cpp (.../TestsTBufferSizes.cpp) (revision cdc76e1a95383dff63a5254aeb8d37035028512c) +++ src/libchcore/Tests/TestsTBufferSizes.cpp (.../TestsTBufferSizes.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,344 +1,344 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TBufferSizes.h" -#include "../TCoreException.h" - -using namespace chcore; - -TEST(TestsTBufferSizes, DefaultConstructor) -{ - TBufferSizes tSizes; - - EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); - EXPECT_EQ(false, tSizes.IsOnlyDefault()); -} - -TEST(TestsTBufferSizes, ParametrizedConstructor_RoundedValues) -{ - TBufferSizes tSizes(true, 2, 4096, 8192, 16384, 32768, 65536); - - EXPECT_EQ(2, tSizes.GetBufferCount()); - EXPECT_EQ(4096, tSizes.GetDefaultSize()); - EXPECT_EQ(8192, tSizes.GetOneDiskSize()); - EXPECT_EQ(16384, tSizes.GetTwoDisksSize()); - EXPECT_EQ(32768, tSizes.GetCDSize()); - EXPECT_EQ(65536, tSizes.GetLANSize()); - EXPECT_EQ(true, tSizes.IsOnlyDefault()); -} - -TEST(TestsTBufferSizes, ParametrizedConstructor_MinimumCheck) -{ - TBufferSizes tSizes(true, 0, 0, 0, 0, 0, 0); - - EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); - EXPECT_EQ(true, tSizes.IsOnlyDefault()); -} - -TEST(TestsTBufferSizes, ParametrizedConstructor_RoundingCheck) -{ - TBufferSizes tSizes(true, 2, 6543, 9891, 17123, 37012, 72089); - - EXPECT_EQ(2, tSizes.GetBufferCount()); - EXPECT_EQ(8192, tSizes.GetDefaultSize()); - EXPECT_EQ(12288, tSizes.GetOneDiskSize()); - EXPECT_EQ(20480, tSizes.GetTwoDisksSize()); - EXPECT_EQ(40960, tSizes.GetCDSize()); - EXPECT_EQ(73728, tSizes.GetLANSize()); - EXPECT_EQ(true, tSizes.IsOnlyDefault()); -} - -TEST(TestsTBufferSizes, Clear) -{ - TBufferSizes tSizes(true, 2, 6543, 9891, 17123, 37012, 72089); - - tSizes.Clear(); - - EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); - EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); - EXPECT_EQ(false, tSizes.IsOnlyDefault()); -} - -TEST(TestsTBufferSizes, SetOnlyDefault_IsOnlyDefault) -{ - TBufferSizes tSizes; - - tSizes.SetOnlyDefault(true); - - EXPECT_EQ(true, tSizes.IsOnlyDefault()); -} - -//////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_Rounded) -{ - TBufferSizes tSizes; - - tSizes.SetDefaultSize(8192); - - EXPECT_EQ(8192, tSizes.GetDefaultSize()); -} - -TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_MinCheck) -{ - TBufferSizes tSizes; - - tSizes.SetDefaultSize(1); - - EXPECT_EQ(4096, tSizes.GetDefaultSize()); -} - -TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetDefaultSize(8193); - - EXPECT_EQ(12288, tSizes.GetDefaultSize()); -} - -///////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_Rounded) -{ - TBufferSizes tSizes; - - tSizes.SetOneDiskSize(8192); - - EXPECT_EQ(8192, tSizes.GetOneDiskSize()); -} - -TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_MinCheck) -{ - TBufferSizes tSizes; - - tSizes.SetOneDiskSize(1); - - EXPECT_EQ(4096, tSizes.GetOneDiskSize()); -} - -TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetOneDiskSize(8193); - - EXPECT_EQ(12288, tSizes.GetOneDiskSize()); -} - -//////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_Rounded) -{ - TBufferSizes tSizes; - - tSizes.SetTwoDisksSize(8192); - - EXPECT_EQ(8192, tSizes.GetTwoDisksSize()); -} - -TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_MinCheck) -{ - TBufferSizes tSizes; - - tSizes.SetTwoDisksSize(1); - - EXPECT_EQ(4096, tSizes.GetTwoDisksSize()); -} - -TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetTwoDisksSize(8193); - - EXPECT_EQ(12288, tSizes.GetTwoDisksSize()); -} -//////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetCDSize_GetCDSize_Rounded) -{ - TBufferSizes tSizes; - - tSizes.SetCDSize(8192); - - EXPECT_EQ(8192, tSizes.GetCDSize()); -} - -TEST(TestsTBufferSizes, SetCDSize_GetCDSize_MinCheck) -{ - TBufferSizes tSizes; - - tSizes.SetCDSize(1); - - EXPECT_EQ(4096, tSizes.GetCDSize()); -} - -TEST(TestsTBufferSizes, SetCDSize_GetCDSize_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetCDSize(8193); - - EXPECT_EQ(12288, tSizes.GetCDSize()); -} - -//////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetLANSize_GetLANSize_Rounded) -{ - TBufferSizes tSizes; - - tSizes.SetLANSize(8192); - - EXPECT_EQ(8192, tSizes.GetLANSize()); -} - -TEST(TestsTBufferSizes, SetLANSize_GetLANSize_MinCheck) -{ - TBufferSizes tSizes; - - tSizes.SetLANSize(1); - - EXPECT_EQ(4096, tSizes.GetLANSize()); -} - -TEST(TestsTBufferSizes, SetLANSize_GetLANSize_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetLANSize(8193); - - EXPECT_EQ(12288, tSizes.GetLANSize()); -} - -////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetBufferCount_GetBufferCount) -{ - TBufferSizes tSizes; - - tSizes.SetBufferCount(5); - - EXPECT_EQ(5, tSizes.GetBufferCount()); -} - -TEST(TestsTBufferSizes, SetBufferCount_GetBufferCount_MinSize) -{ - TBufferSizes tSizes; - - tSizes.SetBufferCount(0); - - EXPECT_EQ(1, tSizes.GetBufferCount()); -} - -//////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_RoundedSize) -{ - TBufferSizes tSizes; - - tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 8192); - tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 16384); - tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 32768); - tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 65536); - tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 131072); - - EXPECT_EQ(8192, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); - EXPECT_EQ(16384, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); - EXPECT_EQ(32768, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); - EXPECT_EQ(65536, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); - EXPECT_EQ(131072, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); -} - -TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_RoundCheck) -{ - TBufferSizes tSizes; - - tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 8190); - tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 16380); - tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 32760); - tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 65530); - tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 131070); - - EXPECT_EQ(8192, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); - EXPECT_EQ(16384, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); - EXPECT_EQ(32768, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); - EXPECT_EQ(65536, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); - EXPECT_EQ(131072, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); -} - -TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_MinSize) -{ - TBufferSizes tSizes; - - tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 0); - tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 0); - tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 0); - tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 0); - tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 0); - - EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); - EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); - EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); - EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); - EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); -} - -TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_OutOfRange) -{ - TBufferSizes tSizes; - - EXPECT_THROW(tSizes.SetSizeByType(TBufferSizes::eBuffer_Last, 0), TCoreException); - EXPECT_THROW(tSizes.GetSizeByType(TBufferSizes::eBuffer_Last), TCoreException); -} - -//////////////////////////////////////////////////////////////////////////////////////////////// -TEST(TestsTBufferSizes, GetMaxSize_Default) -{ - TBufferSizes tSizes(false, 1, 16384, 0, 0, 0, 0); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} - -TEST(TestsTBufferSizes, GetMaxSize_OneDisk) -{ - TBufferSizes tSizes(false, 1, 0, 16384, 0, 0, 0); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} - -TEST(TestsTBufferSizes, GetMaxSize_TwoDisks) -{ - TBufferSizes tSizes(false, 1, 0, 0, 16384, 0, 0); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} - -TEST(TestsTBufferSizes, GetMaxSize_CD) -{ - TBufferSizes tSizes(false, 1, 0, 0, 0, 16384, 0); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} - -TEST(TestsTBufferSizes, GetMaxSize_LAN) -{ - TBufferSizes tSizes(false, 1, 0, 0, 0, 0, 16384); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} - -TEST(TestsTBufferSizes, GetMaxSize_OnlyDefault) -{ - TBufferSizes tSizes(true, 1, 16384, 0, 0, 0, 32768); - - EXPECT_EQ(16384, tSizes.GetMaxSize()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TBufferSizes.h" +#include "../TCoreException.h" + +using namespace chcore; + +TEST(TestsTBufferSizes, DefaultConstructor) +{ + TBufferSizes tSizes; + + EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); + EXPECT_EQ(false, tSizes.IsOnlyDefault()); +} + +TEST(TestsTBufferSizes, ParametrizedConstructor_RoundedValues) +{ + TBufferSizes tSizes(true, 2, 4096, 8192, 16384, 32768, 65536); + + EXPECT_EQ(2, tSizes.GetBufferCount()); + EXPECT_EQ(4096, tSizes.GetDefaultSize()); + EXPECT_EQ(8192, tSizes.GetOneDiskSize()); + EXPECT_EQ(16384, tSizes.GetTwoDisksSize()); + EXPECT_EQ(32768, tSizes.GetCDSize()); + EXPECT_EQ(65536, tSizes.GetLANSize()); + EXPECT_EQ(true, tSizes.IsOnlyDefault()); +} + +TEST(TestsTBufferSizes, ParametrizedConstructor_MinimumCheck) +{ + TBufferSizes tSizes(true, 0, 0, 0, 0, 0, 0); + + EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); + EXPECT_EQ(true, tSizes.IsOnlyDefault()); +} + +TEST(TestsTBufferSizes, ParametrizedConstructor_RoundingCheck) +{ + TBufferSizes tSizes(true, 2, 6543, 9891, 17123, 37012, 72089); + + EXPECT_EQ(2, tSizes.GetBufferCount()); + EXPECT_EQ(8192, tSizes.GetDefaultSize()); + EXPECT_EQ(12288, tSizes.GetOneDiskSize()); + EXPECT_EQ(20480, tSizes.GetTwoDisksSize()); + EXPECT_EQ(40960, tSizes.GetCDSize()); + EXPECT_EQ(73728, tSizes.GetLANSize()); + EXPECT_EQ(true, tSizes.IsOnlyDefault()); +} + +TEST(TestsTBufferSizes, Clear) +{ + TBufferSizes tSizes(true, 2, 6543, 9891, 17123, 37012, 72089); + + tSizes.Clear(); + + EXPECT_EQ(TBufferSizes::MinBufferCount, tSizes.GetBufferCount()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetDefaultSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetOneDiskSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetTwoDisksSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetCDSize()); + EXPECT_EQ(TBufferSizes::BufferGranularity, tSizes.GetLANSize()); + EXPECT_EQ(false, tSizes.IsOnlyDefault()); +} + +TEST(TestsTBufferSizes, SetOnlyDefault_IsOnlyDefault) +{ + TBufferSizes tSizes; + + tSizes.SetOnlyDefault(true); + + EXPECT_EQ(true, tSizes.IsOnlyDefault()); +} + +//////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_Rounded) +{ + TBufferSizes tSizes; + + tSizes.SetDefaultSize(8192); + + EXPECT_EQ(8192, tSizes.GetDefaultSize()); +} + +TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_MinCheck) +{ + TBufferSizes tSizes; + + tSizes.SetDefaultSize(1); + + EXPECT_EQ(4096, tSizes.GetDefaultSize()); +} + +TEST(TestsTBufferSizes, SetDefaultSize_GetDefaultSize_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetDefaultSize(8193); + + EXPECT_EQ(12288, tSizes.GetDefaultSize()); +} + +///////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_Rounded) +{ + TBufferSizes tSizes; + + tSizes.SetOneDiskSize(8192); + + EXPECT_EQ(8192, tSizes.GetOneDiskSize()); +} + +TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_MinCheck) +{ + TBufferSizes tSizes; + + tSizes.SetOneDiskSize(1); + + EXPECT_EQ(4096, tSizes.GetOneDiskSize()); +} + +TEST(TestsTBufferSizes, SetOneDiskSize_GetOneDiskSize_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetOneDiskSize(8193); + + EXPECT_EQ(12288, tSizes.GetOneDiskSize()); +} + +//////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_Rounded) +{ + TBufferSizes tSizes; + + tSizes.SetTwoDisksSize(8192); + + EXPECT_EQ(8192, tSizes.GetTwoDisksSize()); +} + +TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_MinCheck) +{ + TBufferSizes tSizes; + + tSizes.SetTwoDisksSize(1); + + EXPECT_EQ(4096, tSizes.GetTwoDisksSize()); +} + +TEST(TestsTBufferSizes, SetTwoDisksSize_GetTwoDisksSize_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetTwoDisksSize(8193); + + EXPECT_EQ(12288, tSizes.GetTwoDisksSize()); +} +//////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetCDSize_GetCDSize_Rounded) +{ + TBufferSizes tSizes; + + tSizes.SetCDSize(8192); + + EXPECT_EQ(8192, tSizes.GetCDSize()); +} + +TEST(TestsTBufferSizes, SetCDSize_GetCDSize_MinCheck) +{ + TBufferSizes tSizes; + + tSizes.SetCDSize(1); + + EXPECT_EQ(4096, tSizes.GetCDSize()); +} + +TEST(TestsTBufferSizes, SetCDSize_GetCDSize_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetCDSize(8193); + + EXPECT_EQ(12288, tSizes.GetCDSize()); +} + +//////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetLANSize_GetLANSize_Rounded) +{ + TBufferSizes tSizes; + + tSizes.SetLANSize(8192); + + EXPECT_EQ(8192, tSizes.GetLANSize()); +} + +TEST(TestsTBufferSizes, SetLANSize_GetLANSize_MinCheck) +{ + TBufferSizes tSizes; + + tSizes.SetLANSize(1); + + EXPECT_EQ(4096, tSizes.GetLANSize()); +} + +TEST(TestsTBufferSizes, SetLANSize_GetLANSize_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetLANSize(8193); + + EXPECT_EQ(12288, tSizes.GetLANSize()); +} + +////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetBufferCount_GetBufferCount) +{ + TBufferSizes tSizes; + + tSizes.SetBufferCount(5); + + EXPECT_EQ(5, tSizes.GetBufferCount()); +} + +TEST(TestsTBufferSizes, SetBufferCount_GetBufferCount_MinSize) +{ + TBufferSizes tSizes; + + tSizes.SetBufferCount(0); + + EXPECT_EQ(1, tSizes.GetBufferCount()); +} + +//////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_RoundedSize) +{ + TBufferSizes tSizes; + + tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 8192); + tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 16384); + tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 32768); + tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 65536); + tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 131072); + + EXPECT_EQ(8192, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); + EXPECT_EQ(16384, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); + EXPECT_EQ(32768, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); + EXPECT_EQ(65536, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); + EXPECT_EQ(131072, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); +} + +TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_RoundCheck) +{ + TBufferSizes tSizes; + + tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 8190); + tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 16380); + tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 32760); + tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 65530); + tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 131070); + + EXPECT_EQ(8192, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); + EXPECT_EQ(16384, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); + EXPECT_EQ(32768, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); + EXPECT_EQ(65536, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); + EXPECT_EQ(131072, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); +} + +TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_MinSize) +{ + TBufferSizes tSizes; + + tSizes.SetSizeByType(TBufferSizes::eBuffer_Default, 0); + tSizes.SetSizeByType(TBufferSizes::eBuffer_OneDisk, 0); + tSizes.SetSizeByType(TBufferSizes::eBuffer_TwoDisks, 0); + tSizes.SetSizeByType(TBufferSizes::eBuffer_CD, 0); + tSizes.SetSizeByType(TBufferSizes::eBuffer_LAN, 0); + + EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_Default)); + EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_OneDisk)); + EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_TwoDisks)); + EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_CD)); + EXPECT_EQ(4096, tSizes.GetSizeByType(TBufferSizes::eBuffer_LAN)); +} + +TEST(TestsTBufferSizes, SetSizeByType_GetSizeByType_OutOfRange) +{ + TBufferSizes tSizes; + + EXPECT_THROW(tSizes.SetSizeByType(TBufferSizes::eBuffer_Last, 0), TCoreException); + EXPECT_THROW(tSizes.GetSizeByType(TBufferSizes::eBuffer_Last), TCoreException); +} + +//////////////////////////////////////////////////////////////////////////////////////////////// +TEST(TestsTBufferSizes, GetMaxSize_Default) +{ + TBufferSizes tSizes(false, 1, 16384, 0, 0, 0, 0); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} + +TEST(TestsTBufferSizes, GetMaxSize_OneDisk) +{ + TBufferSizes tSizes(false, 1, 0, 16384, 0, 0, 0); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} + +TEST(TestsTBufferSizes, GetMaxSize_TwoDisks) +{ + TBufferSizes tSizes(false, 1, 0, 0, 16384, 0, 0); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} + +TEST(TestsTBufferSizes, GetMaxSize_CD) +{ + TBufferSizes tSizes(false, 1, 0, 0, 0, 16384, 0); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} + +TEST(TestsTBufferSizes, GetMaxSize_LAN) +{ + TBufferSizes tSizes(false, 1, 0, 0, 0, 0, 16384); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} + +TEST(TestsTBufferSizes, GetMaxSize_OnlyDefault) +{ + TBufferSizes tSizes(true, 1, 16384, 0, 0, 0, 32768); + + EXPECT_EQ(16384, tSizes.GetMaxSize()); +} Index: src/libchcore/Tests/TestsTConfig.cpp =================================================================== diff -u -r09f1dd01c80a2c14e7b3c8531356a60ce5a6a801 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTConfig.cpp (.../TestsTConfig.cpp) (revision 09f1dd01c80a2c14e7b3c8531356a60ce5a6a801) +++ src/libchcore/Tests/TestsTConfig.cpp (.../TestsTConfig.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,659 +1,659 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include -#include -#include -#include -#include "../TConfig.h" -#include "../TStringArray.h" -#include "../TConfigArray.h" - -using namespace chcore; - -namespace -{ - std::wstring GetTmpPath() - { - TCHAR szPath[_MAX_PATH]; - GetTempPath(_MAX_PATH, szPath); - - TCHAR szFilename[_MAX_PATH]; - GetTempFileName(szPath, _T("TempCfg"), 0, szFilename); - - return szFilename; - } -} - -// fixtures -class FileWithConfigurationFixture : public ::testing::Test -{ -protected: - virtual void SetUp() - { - m_strTempFilePath = GetTmpPath(); - - std::wofstream outFile(m_strTempFilePath.c_str(), std::wofstream::out | std::wofstream::binary); - - std::locale utf8locale(std::locale(), new std::codecvt_utf8); - outFile.imbue(utf8locale); - - std::wstring wstrData = - L"\ -\ - \ - 30000\ - \ - \ - true\ - <WINDOWS>\\media\\chord.wav\ - <WINDOWS>\\\x597D\x8FD0\\ding.wav\ - \ - \ - c:\\Windows\\System32\ - d:\\Movies\ - x:\\Music\ - s:\\projects\\ch-rw\ - \ - \ - \ - \ - <WINDOWS>\\FirstPath\ - FirstName\ - \ - \ - <WINDOWS>\\SecondPath\ - SecondName\ - \ - \ - \ -"; - - outFile << wstrData; - outFile.flush(); - } - - virtual void TearDown() - { - DeleteFile(m_strTempFilePath.c_str()); - } - - std::wstring m_strTempFilePath; -}; - -class InitializedConfigFixture : public ::testing::Test -{ -protected: - virtual void SetUp() - { - m_strInputXmlString = - L"\ -\ - \ - 30000\ - \ - \ - true\ - <WINDOWS>\\media\\chord.wav\ - <WINDOWS>\\\x597D\x8FD0\\ding.wav\ - \ - \ - c:\\Windows\\System32\ - d:\\Movies\ - x:\\Music\ - s:\\projects\\ch-rw\ - \ - \ - \ - \ - <WINDOWS>\\FirstPath\ - FirstName\ - \ - \ - <WINDOWS>\\SecondPath\ - SecondName\ - \ - \ - \ -"; - - m_cfg.ReadFromString(m_strInputXmlString); - } - - TString m_strInputXmlString; - TConfig m_cfg; -}; - -/////////////////////////////////////////////////////////////////////////// -// read from/write to file - -TEST_F(FileWithConfigurationFixture, ReadFromFile) -{ - TConfig cfg; - cfg.Read(m_strTempFilePath.c_str()); - - EXPECT_EQ(true, cfg.GetBool(_T("CHConfig.Core.Notifications.Sounds.Enable"), false)); - EXPECT_EQ(30000, cfg.GetInt(_T("CHConfig.Core.AutosaveInterval"), 0)); - EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), cfg.GetString(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T(""))); -} - -TEST(TConfigTests, WriteToFile) -{ - TConfig cfg; - cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.Enable"), true); - cfg.SetValue(_T("CHConfig.Core.AutosaveInterval"), 10000); - cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T("c:\\Users\\\x597D\x8FD0")); - - std::wstring strPath(GetTmpPath()); - cfg.SetFilePath(strPath.c_str()); - - cfg.Write(); - - std::wstring wstrData; - std::wifstream inFile(strPath.c_str(), std::wofstream::in | std::wofstream::binary); - - std::locale utf8locale(std::locale(), new std::codecvt_utf8); - inFile.imbue(utf8locale); - - std::wstringstream wstrStream; - wstrStream << inFile.rdbuf(); - - wstrData = wstrStream.str(); - - DeleteFile(strPath.c_str()); - - boost::replace_all(wstrData, _T("\r\n"), _T("\n")); - - EXPECT_EQ(_T("\n\ -10000truec:\\Users\\\x597D\x8FD0"), -wstrData); -} - -/////////////////////////////////////////////////////////////////////////// -// store in/load from string -TEST_F(InitializedConfigFixture, ReadFromString) -{ - EXPECT_EQ(true, m_cfg.GetBool(_T("CHConfig.Core.Notifications.Sounds.Enable"), false)); - EXPECT_EQ(30000, m_cfg.GetInt(_T("CHConfig.Core.AutosaveInterval"), 0)); - EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), m_cfg.GetString(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T(""))); -} - -TEST(TConfigTests, WriteToString) -{ - TConfig cfg; - cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.Enable"), true); - cfg.SetValue(_T("CHConfig.Core.AutosaveInterval"), 10000); - cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T("c:\\Users\\NewUser")); - - TString strData; - cfg.WriteToString(strData); - - EXPECT_EQ(TString(_T("\n\ -10000truec:\\Users\\NewUser")), strData); -} - -/////////////////////////////////////////////////////////////////////////// -// value get/set - -// bool - -TEST(TConfigTests, GetSetBool) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), true); - cfg.SetValue(_T("Root.Node.Value2"), false); - - // check if stored successfully (typed get) - EXPECT_EQ(true, cfg.GetBool(_T("Root.Node.Value1"))); - EXPECT_EQ(false, cfg.GetBool(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - bool bValue = false; - cfg.GetValue(_T("Root.Node.Value1"), bValue); - EXPECT_EQ(true, bValue); - cfg.GetValue(_T("Root.Node.Value2"), bValue); - EXPECT_EQ(false, bValue); -} - -TEST(TConfigTests, GetSetBoolExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -truefalse")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ(true, cfg.GetBool(_T("Root.Node.Value1"))); - EXPECT_EQ(false, cfg.GetBool(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetInt) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), 2147483647); - cfg.SetValue(_T("Root.Node.Value2"), (-2147483647 - 1)); - - // check if stored successfully (typed get) - EXPECT_EQ(2147483647, cfg.GetInt(_T("Root.Node.Value1"))); - EXPECT_EQ((-2147483647 - 1), cfg.GetInt(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - int iValue = 0; - cfg.GetValue(_T("Root.Node.Value1"), iValue); - EXPECT_EQ(2147483647, iValue); - cfg.GetValue(_T("Root.Node.Value2"), iValue); - EXPECT_EQ((-2147483647 - 1), iValue); -} - -TEST(TConfigTests, GetSetIntExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -2147483647-2147483648")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ(2147483647, cfg.GetInt(_T("Root.Node.Value1"))); - EXPECT_EQ((-2147483647 - 1), cfg.GetInt(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetUInt) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), (unsigned int)1489); - cfg.SetValue(_T("Root.Node.Value2"), (unsigned int)4294967295); - - // check if stored successfully (typed get) - EXPECT_EQ(1489, cfg.GetUInt(_T("Root.Node.Value1"))); - EXPECT_EQ(4294967295, cfg.GetUInt(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - unsigned int value = 0; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_EQ(1489, value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_EQ(4294967295, value); -} - -TEST(TConfigTests, GetSetUIntExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -14894294967295")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ(1489, cfg.GetUInt(_T("Root.Node.Value1"))); - EXPECT_EQ(4294967295, cfg.GetUInt(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetLongLong) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), (long long)9223372036854775807); - cfg.SetValue(_T("Root.Node.Value2"), (long long)(-9223372036854775807 - 1)); - - // check if stored successfully (typed get) - EXPECT_EQ((long long)9223372036854775807, cfg.GetLongLong(_T("Root.Node.Value1"))); - EXPECT_EQ((long long)(-9223372036854775807 - 1), cfg.GetLongLong(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - long long value = 0; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_EQ((long long)9223372036854775807, value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_EQ((long long)(-9223372036854775807 - 1), value); -} - -TEST(TConfigTests, GetSetLongLongExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -9223372036854775807-9223372036854775808")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ((long long)9223372036854775807, cfg.GetLongLong(_T("Root.Node.Value1"))); - EXPECT_EQ((long long)(-9223372036854775807 - 1), cfg.GetLongLong(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetULongLong) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), (unsigned long long)1489); - cfg.SetValue(_T("Root.Node.Value2"), (unsigned long long)18446744073709551615); - - // check if stored successfully (typed get) - EXPECT_EQ((unsigned long long)1489, cfg.GetULongLong(_T("Root.Node.Value1"))); - EXPECT_EQ((unsigned long long)18446744073709551615, cfg.GetULongLong(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - unsigned long long value = 0; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_EQ((unsigned long long)1489, value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_EQ((unsigned long long)18446744073709551615, value); -} - -TEST(TConfigTests, GetSetULongLongExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -148918446744073709551615")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ((unsigned long long)1489, cfg.GetULongLong(_T("Root.Node.Value1"))); - EXPECT_EQ((unsigned long long)18446744073709551615, cfg.GetULongLong(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetDouble) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), (double)0.0); - cfg.SetValue(_T("Root.Node.Value2"), 1.7976931348623158e+308); - - // check if stored successfully (typed get) - EXPECT_DOUBLE_EQ(0.0, cfg.GetDouble(_T("Root.Node.Value1"))); - EXPECT_DOUBLE_EQ(1.7976931348623158e+308, cfg.GetDouble(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - double value = 0; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_DOUBLE_EQ(0.0, value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_DOUBLE_EQ(1.7976931348623158e+308, value); -} - -TEST(TConfigTests, GetSetDoubleExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -01.7976931348623158e+308")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_DOUBLE_EQ(0.0, cfg.GetDouble(_T("Root.Node.Value1"))); - EXPECT_DOUBLE_EQ(1.7976931348623158e+308, cfg.GetDouble(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetString) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), _T("Some basic string")); - cfg.SetValue(_T("Root.Node.Value2"), L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"); - - // check if stored successfully (typed get) - EXPECT_EQ(TString(_T("Some basic string")), cfg.GetString(_T("Root.Node.Value1"))); - EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), cfg.GetString(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - TString value; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_EQ(TString(_T("Some basic string")), value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), value); -} - -TEST(TConfigTests, GetSetStringExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -Some basic string!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ(TString(_T("Some basic string")), cfg.GetString(_T("Root.Node.Value1"))); - EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), cfg.GetString(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetPath) -{ - TConfig cfg; - - // store data in config - cfg.SetValue(_T("Root.Node.Value1"), _T("c:\\Windows\\System32")); - cfg.SetValue(_T("Root.Node.Value2"), _T("\\\\machine\\share\\SomeFile.dat")); - - // check if stored successfully (typed get) - EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), cfg.GetPath(_T("Root.Node.Value1"))); - EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), cfg.GetPath(_T("Root.Node.Value2"))); - - // check if stored successfully (GetValue) - TSmartPath value; - cfg.GetValue(_T("Root.Node.Value1"), value); - EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), value); - cfg.GetValue(_T("Root.Node.Value2"), value); - EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), value); -} - -TEST(TConfigTests, GetSetPathExport) -{ - TConfig cfg; - - TString strXmlData(_T("\n\ -c:\\Windows\\System32\\\\machine\\share\\SomeFile.dat")); - - // store in string - cfg.ReadFromString(strXmlData); - - EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), cfg.GetPath(_T("Root.Node.Value1"))); - EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), cfg.GetPath(_T("Root.Node.Value2"))); - - TString strWriteXmlData; - cfg.WriteToString(strWriteXmlData); - - EXPECT_EQ(strXmlData, strWriteXmlData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TConfigTests, GetSetStringArray) -{ - TConfig cfg; - - TStringArray arrString; - arrString.Add(_T("String1")); - arrString.Add(_T("SampleStringPath")); - arrString.Add(_T("!@#$%^&*()")); - arrString.Add(_T("")); - - // store data in config - cfg.SetValue(_T("Root.Node.Values.Node"), arrString); - - // check if stored successfully (typed get) - TStringArray arrRead; - cfg.GetValue(_T("Root.Node.Values.Node"), arrRead); - - EXPECT_EQ(arrString.GetCount(), arrRead.GetCount()); - EXPECT_EQ(arrString.GetAt(0), arrRead.GetAt(0)); - EXPECT_EQ(arrString.GetAt(1), arrRead.GetAt(1)); - EXPECT_EQ(arrString.GetAt(2), arrRead.GetAt(2)); - EXPECT_EQ(arrString.GetAt(3), arrRead.GetAt(3)); -} - -TEST_F(InitializedConfigFixture, GetSetStringArrayImport) -{ - TStringArray arrRead; - m_cfg.GetValue(_T("CHConfig.Core.Notifications.PathList.Path"), arrRead); - - EXPECT_EQ(arrRead.GetCount(), 4); - EXPECT_EQ(TString(_T("c:\\Windows\\System32")), arrRead.GetAt(0)); - EXPECT_EQ(TString(_T("d:\\Movies")), arrRead.GetAt(1)); - EXPECT_EQ(TString(_T("x:\\Music")), arrRead.GetAt(2)); - EXPECT_EQ(TString(_T("s:\\projects\\ch-rw")), arrRead.GetAt(3)); -} - -TEST(TConfigTests, GetSetStringArrayExport) -{ - TConfig cfg; - - TStringArray arrString; - arrString.Add(_T("String1")); - arrString.Add(_T("SampleStringPath")); - arrString.Add(_T("!@#$%^&*()")); - arrString.Add(_T("")); - - // store data in config - cfg.SetValue(_T("Root.Node.Values.Node"), arrString); - - // store in string - TString wstrData; - cfg.WriteToString(wstrData); - - EXPECT_EQ(TString(_T("\n\ -String1SampleStringPath!@#$%^&*()")), wstrData); -} - -/////////////////////////////////////////////////////////////////////////// -TEST_F(InitializedConfigFixture, CompositeObjectsReadWriteString) -{ - TString wstrWithDeletion; - m_cfg.WriteToString(wstrWithDeletion); - - EXPECT_EQ(TString(_T("\n\ -30000\ -FirstName<WINDOWS>\\FirstPathSecondName<WINDOWS>\\SecondPath\ -c:\\Windows\\System32d:\\Moviesx:\\Musics:\\projects\\ch-rw\ -true<WINDOWS>\\media\\chord.wav\ -<WINDOWS>\\\x597D\x8FD0\\ding.wav")), wstrWithDeletion); -} - -/////////////////////////////////////////////////////////////////////////// -TEST_F(InitializedConfigFixture, DeleteNodeTest) -{ - m_cfg.DeleteNode(_T("CHConfig.Core.Notifications")); - - TString wstrWithDeletion; - m_cfg.WriteToString(wstrWithDeletion); - - EXPECT_EQ(TString(_T("\n\ -30000FirstName<WINDOWS>\\FirstPath\ -SecondName<WINDOWS>\\SecondPath")), wstrWithDeletion); -} - -/////////////////////////////////////////////////////////////////////////// -TEST_F(InitializedConfigFixture, ExtractConfig) -{ - TConfig cfgSub; - - m_cfg.ExtractSubConfig(_T("CHConfig.Core.Notifications.Sounds"), cfgSub); - EXPECT_EQ(true, cfgSub.GetBool(_T("Enable"))); - EXPECT_EQ(TString(_T("\\media\\chord.wav")), cfgSub.GetString(_T("ErrorSoundPath"))); - EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), cfgSub.GetString(_T("FinishedSoundPath"))); -} - -TEST_F(InitializedConfigFixture, ExtractMultipleConfigs) -{ - TConfigArray cfgSubArray; - - m_cfg.ExtractMultiSubConfigs(_T("CHConfig.Core.CompositeObjects.Object"), cfgSubArray); - - EXPECT_EQ(2, cfgSubArray.GetCount()); - - EXPECT_EQ(TString(_T("FirstName")), cfgSubArray.GetAt(0).GetString(_T("Name"))); - EXPECT_EQ(TString(_T("\\FirstPath")), cfgSubArray.GetAt(0).GetString(_T("Path"))); - EXPECT_EQ(TString(_T("SecondName")), cfgSubArray.GetAt(1).GetString(_T("Name"))); - EXPECT_EQ(TString(_T("\\SecondPath")), cfgSubArray.GetAt(1).GetString(_T("Path"))); -} - -TEST(TConfigTests, PutSubConfig) -{ - TConfig mainCfg; - - TConfig cfgSub; - cfgSub.SetValue(_T("Node1"), true); - cfgSub.SetValue(_T("NameNode"), _T("TestNode")); - - mainCfg.PutSubConfig(_T("Root.NodeSet"), cfgSub); - - EXPECT_EQ(true, mainCfg.GetBool(_T("Root.NodeSet.Node1"))); - EXPECT_EQ(TString(_T("TestNode")), mainCfg.GetString(_T("Root.NodeSet.NameNode"))); -} - -TEST(TConfigTests, AddSubConfig) -{ - TConfig mainCfg; - - TConfig cfgSub; - cfgSub.SetValue(_T("Node1"), true); - cfgSub.SetValue(_T("NameNode"), _T("TestNode")); - - mainCfg.AddSubConfig(_T("Root.NodeSet.Node"), cfgSub); - mainCfg.AddSubConfig(_T("Root.NodeSet.Node"), cfgSub); - - TString strXml; - mainCfg.WriteToString(strXml); - - EXPECT_EQ(TString(_T("\n\ -TestNodetrueTestNodetrue")), strXml); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include +#include +#include +#include +#include "../TConfig.h" +#include "../TStringArray.h" +#include "../TConfigArray.h" + +using namespace chcore; + +namespace +{ + std::wstring GetTmpPath() + { + TCHAR szPath[_MAX_PATH]; + GetTempPath(_MAX_PATH, szPath); + + TCHAR szFilename[_MAX_PATH]; + GetTempFileName(szPath, _T("TempCfg"), 0, szFilename); + + return szFilename; + } +} + +// fixtures +class FileWithConfigurationFixture : public ::testing::Test +{ +protected: + virtual void SetUp() + { + m_strTempFilePath = GetTmpPath(); + + std::wofstream outFile(m_strTempFilePath.c_str(), std::wofstream::out | std::wofstream::binary); + + std::locale utf8locale(std::locale(), new std::codecvt_utf8); + outFile.imbue(utf8locale); + + std::wstring wstrData = + L"\ +\ + \ + 30000\ + \ + \ + true\ + <WINDOWS>\\media\\chord.wav\ + <WINDOWS>\\\x597D\x8FD0\\ding.wav\ + \ + \ + c:\\Windows\\System32\ + d:\\Movies\ + x:\\Music\ + s:\\projects\\ch-rw\ + \ + \ + \ + \ + <WINDOWS>\\FirstPath\ + FirstName\ + \ + \ + <WINDOWS>\\SecondPath\ + SecondName\ + \ + \ + \ +"; + + outFile << wstrData; + outFile.flush(); + } + + virtual void TearDown() + { + DeleteFile(m_strTempFilePath.c_str()); + } + + std::wstring m_strTempFilePath; +}; + +class InitializedConfigFixture : public ::testing::Test +{ +protected: + virtual void SetUp() + { + m_strInputXmlString = + L"\ +\ + \ + 30000\ + \ + \ + true\ + <WINDOWS>\\media\\chord.wav\ + <WINDOWS>\\\x597D\x8FD0\\ding.wav\ + \ + \ + c:\\Windows\\System32\ + d:\\Movies\ + x:\\Music\ + s:\\projects\\ch-rw\ + \ + \ + \ + \ + <WINDOWS>\\FirstPath\ + FirstName\ + \ + \ + <WINDOWS>\\SecondPath\ + SecondName\ + \ + \ + \ +"; + + m_cfg.ReadFromString(m_strInputXmlString); + } + + TString m_strInputXmlString; + TConfig m_cfg; +}; + +/////////////////////////////////////////////////////////////////////////// +// read from/write to file + +TEST_F(FileWithConfigurationFixture, ReadFromFile) +{ + TConfig cfg; + cfg.Read(m_strTempFilePath.c_str()); + + EXPECT_EQ(true, cfg.GetBool(_T("CHConfig.Core.Notifications.Sounds.Enable"), false)); + EXPECT_EQ(30000, cfg.GetInt(_T("CHConfig.Core.AutosaveInterval"), 0)); + EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), cfg.GetString(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T(""))); +} + +TEST(TConfigTests, WriteToFile) +{ + TConfig cfg; + cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.Enable"), true); + cfg.SetValue(_T("CHConfig.Core.AutosaveInterval"), 10000); + cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T("c:\\Users\\\x597D\x8FD0")); + + std::wstring strPath(GetTmpPath()); + cfg.SetFilePath(strPath.c_str()); + + cfg.Write(); + + std::wstring wstrData; + std::wifstream inFile(strPath.c_str(), std::wofstream::in | std::wofstream::binary); + + std::locale utf8locale(std::locale(), new std::codecvt_utf8); + inFile.imbue(utf8locale); + + std::wstringstream wstrStream; + wstrStream << inFile.rdbuf(); + + wstrData = wstrStream.str(); + + DeleteFile(strPath.c_str()); + + boost::replace_all(wstrData, _T("\r\n"), _T("\n")); + + EXPECT_EQ(_T("\n\ +10000truec:\\Users\\\x597D\x8FD0"), +wstrData); +} + +/////////////////////////////////////////////////////////////////////////// +// store in/load from string +TEST_F(InitializedConfigFixture, ReadFromString) +{ + EXPECT_EQ(true, m_cfg.GetBool(_T("CHConfig.Core.Notifications.Sounds.Enable"), false)); + EXPECT_EQ(30000, m_cfg.GetInt(_T("CHConfig.Core.AutosaveInterval"), 0)); + EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), m_cfg.GetString(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T(""))); +} + +TEST(TConfigTests, WriteToString) +{ + TConfig cfg; + cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.Enable"), true); + cfg.SetValue(_T("CHConfig.Core.AutosaveInterval"), 10000); + cfg.SetValue(_T("CHConfig.Core.Notifications.Sounds.FinishedSoundPath"), _T("c:\\Users\\NewUser")); + + TString strData; + cfg.WriteToString(strData); + + EXPECT_EQ(TString(_T("\n\ +10000truec:\\Users\\NewUser")), strData); +} + +/////////////////////////////////////////////////////////////////////////// +// value get/set + +// bool + +TEST(TConfigTests, GetSetBool) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), true); + cfg.SetValue(_T("Root.Node.Value2"), false); + + // check if stored successfully (typed get) + EXPECT_EQ(true, cfg.GetBool(_T("Root.Node.Value1"))); + EXPECT_EQ(false, cfg.GetBool(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + bool bValue = false; + cfg.GetValue(_T("Root.Node.Value1"), bValue); + EXPECT_EQ(true, bValue); + cfg.GetValue(_T("Root.Node.Value2"), bValue); + EXPECT_EQ(false, bValue); +} + +TEST(TConfigTests, GetSetBoolExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +truefalse")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ(true, cfg.GetBool(_T("Root.Node.Value1"))); + EXPECT_EQ(false, cfg.GetBool(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetInt) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), 2147483647); + cfg.SetValue(_T("Root.Node.Value2"), (-2147483647 - 1)); + + // check if stored successfully (typed get) + EXPECT_EQ(2147483647, cfg.GetInt(_T("Root.Node.Value1"))); + EXPECT_EQ((-2147483647 - 1), cfg.GetInt(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + int iValue = 0; + cfg.GetValue(_T("Root.Node.Value1"), iValue); + EXPECT_EQ(2147483647, iValue); + cfg.GetValue(_T("Root.Node.Value2"), iValue); + EXPECT_EQ((-2147483647 - 1), iValue); +} + +TEST(TConfigTests, GetSetIntExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +2147483647-2147483648")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ(2147483647, cfg.GetInt(_T("Root.Node.Value1"))); + EXPECT_EQ((-2147483647 - 1), cfg.GetInt(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetUInt) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), (unsigned int)1489); + cfg.SetValue(_T("Root.Node.Value2"), (unsigned int)4294967295); + + // check if stored successfully (typed get) + EXPECT_EQ(1489, cfg.GetUInt(_T("Root.Node.Value1"))); + EXPECT_EQ(4294967295, cfg.GetUInt(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + unsigned int value = 0; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_EQ(1489, value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_EQ(4294967295, value); +} + +TEST(TConfigTests, GetSetUIntExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +14894294967295")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ(1489, cfg.GetUInt(_T("Root.Node.Value1"))); + EXPECT_EQ(4294967295, cfg.GetUInt(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetLongLong) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), (long long)9223372036854775807); + cfg.SetValue(_T("Root.Node.Value2"), (long long)(-9223372036854775807 - 1)); + + // check if stored successfully (typed get) + EXPECT_EQ((long long)9223372036854775807, cfg.GetLongLong(_T("Root.Node.Value1"))); + EXPECT_EQ((long long)(-9223372036854775807 - 1), cfg.GetLongLong(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + long long value = 0; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_EQ((long long)9223372036854775807, value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_EQ((long long)(-9223372036854775807 - 1), value); +} + +TEST(TConfigTests, GetSetLongLongExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +9223372036854775807-9223372036854775808")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ((long long)9223372036854775807, cfg.GetLongLong(_T("Root.Node.Value1"))); + EXPECT_EQ((long long)(-9223372036854775807 - 1), cfg.GetLongLong(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetULongLong) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), (unsigned long long)1489); + cfg.SetValue(_T("Root.Node.Value2"), (unsigned long long)18446744073709551615); + + // check if stored successfully (typed get) + EXPECT_EQ((unsigned long long)1489, cfg.GetULongLong(_T("Root.Node.Value1"))); + EXPECT_EQ((unsigned long long)18446744073709551615, cfg.GetULongLong(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + unsigned long long value = 0; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_EQ((unsigned long long)1489, value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_EQ((unsigned long long)18446744073709551615, value); +} + +TEST(TConfigTests, GetSetULongLongExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +148918446744073709551615")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ((unsigned long long)1489, cfg.GetULongLong(_T("Root.Node.Value1"))); + EXPECT_EQ((unsigned long long)18446744073709551615, cfg.GetULongLong(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetDouble) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), (double)0.0); + cfg.SetValue(_T("Root.Node.Value2"), 1.7976931348623158e+308); + + // check if stored successfully (typed get) + EXPECT_DOUBLE_EQ(0.0, cfg.GetDouble(_T("Root.Node.Value1"))); + EXPECT_DOUBLE_EQ(1.7976931348623158e+308, cfg.GetDouble(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + double value = 0; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_DOUBLE_EQ(0.0, value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_DOUBLE_EQ(1.7976931348623158e+308, value); +} + +TEST(TConfigTests, GetSetDoubleExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +01.7976931348623158e+308")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_DOUBLE_EQ(0.0, cfg.GetDouble(_T("Root.Node.Value1"))); + EXPECT_DOUBLE_EQ(1.7976931348623158e+308, cfg.GetDouble(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetString) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), _T("Some basic string")); + cfg.SetValue(_T("Root.Node.Value2"), L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"); + + // check if stored successfully (typed get) + EXPECT_EQ(TString(_T("Some basic string")), cfg.GetString(_T("Root.Node.Value1"))); + EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), cfg.GetString(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + TString value; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_EQ(TString(_T("Some basic string")), value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), value); +} + +TEST(TConfigTests, GetSetStringExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +Some basic string!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ(TString(_T("Some basic string")), cfg.GetString(_T("Root.Node.Value1"))); + EXPECT_EQ(TString(L"!@#$%^&*()[]\\/<>,.QWERTYqwerty\x2021"), cfg.GetString(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetPath) +{ + TConfig cfg; + + // store data in config + cfg.SetValue(_T("Root.Node.Value1"), _T("c:\\Windows\\System32")); + cfg.SetValue(_T("Root.Node.Value2"), _T("\\\\machine\\share\\SomeFile.dat")); + + // check if stored successfully (typed get) + EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), cfg.GetPath(_T("Root.Node.Value1"))); + EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), cfg.GetPath(_T("Root.Node.Value2"))); + + // check if stored successfully (GetValue) + TSmartPath value; + cfg.GetValue(_T("Root.Node.Value1"), value); + EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), value); + cfg.GetValue(_T("Root.Node.Value2"), value); + EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), value); +} + +TEST(TConfigTests, GetSetPathExport) +{ + TConfig cfg; + + TString strXmlData(_T("\n\ +c:\\Windows\\System32\\\\machine\\share\\SomeFile.dat")); + + // store in string + cfg.ReadFromString(strXmlData); + + EXPECT_EQ(PathFromString(_T("c:\\Windows\\System32")), cfg.GetPath(_T("Root.Node.Value1"))); + EXPECT_EQ(PathFromString(_T("\\\\machine\\share\\SomeFile.dat")), cfg.GetPath(_T("Root.Node.Value2"))); + + TString strWriteXmlData; + cfg.WriteToString(strWriteXmlData); + + EXPECT_EQ(strXmlData, strWriteXmlData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TConfigTests, GetSetStringArray) +{ + TConfig cfg; + + TStringArray arrString; + arrString.Add(_T("String1")); + arrString.Add(_T("SampleStringPath")); + arrString.Add(_T("!@#$%^&*()")); + arrString.Add(_T("")); + + // store data in config + cfg.SetValue(_T("Root.Node.Values.Node"), arrString); + + // check if stored successfully (typed get) + TStringArray arrRead; + cfg.GetValue(_T("Root.Node.Values.Node"), arrRead); + + EXPECT_EQ(arrString.GetCount(), arrRead.GetCount()); + EXPECT_EQ(arrString.GetAt(0), arrRead.GetAt(0)); + EXPECT_EQ(arrString.GetAt(1), arrRead.GetAt(1)); + EXPECT_EQ(arrString.GetAt(2), arrRead.GetAt(2)); + EXPECT_EQ(arrString.GetAt(3), arrRead.GetAt(3)); +} + +TEST_F(InitializedConfigFixture, GetSetStringArrayImport) +{ + TStringArray arrRead; + m_cfg.GetValue(_T("CHConfig.Core.Notifications.PathList.Path"), arrRead); + + EXPECT_EQ(arrRead.GetCount(), 4); + EXPECT_EQ(TString(_T("c:\\Windows\\System32")), arrRead.GetAt(0)); + EXPECT_EQ(TString(_T("d:\\Movies")), arrRead.GetAt(1)); + EXPECT_EQ(TString(_T("x:\\Music")), arrRead.GetAt(2)); + EXPECT_EQ(TString(_T("s:\\projects\\ch-rw")), arrRead.GetAt(3)); +} + +TEST(TConfigTests, GetSetStringArrayExport) +{ + TConfig cfg; + + TStringArray arrString; + arrString.Add(_T("String1")); + arrString.Add(_T("SampleStringPath")); + arrString.Add(_T("!@#$%^&*()")); + arrString.Add(_T("")); + + // store data in config + cfg.SetValue(_T("Root.Node.Values.Node"), arrString); + + // store in string + TString wstrData; + cfg.WriteToString(wstrData); + + EXPECT_EQ(TString(_T("\n\ +String1SampleStringPath!@#$%^&*()")), wstrData); +} + +/////////////////////////////////////////////////////////////////////////// +TEST_F(InitializedConfigFixture, CompositeObjectsReadWriteString) +{ + TString wstrWithDeletion; + m_cfg.WriteToString(wstrWithDeletion); + + EXPECT_EQ(TString(_T("\n\ +30000\ +FirstName<WINDOWS>\\FirstPathSecondName<WINDOWS>\\SecondPath\ +c:\\Windows\\System32d:\\Moviesx:\\Musics:\\projects\\ch-rw\ +true<WINDOWS>\\media\\chord.wav\ +<WINDOWS>\\\x597D\x8FD0\\ding.wav")), wstrWithDeletion); +} + +/////////////////////////////////////////////////////////////////////////// +TEST_F(InitializedConfigFixture, DeleteNodeTest) +{ + m_cfg.DeleteNode(_T("CHConfig.Core.Notifications")); + + TString wstrWithDeletion; + m_cfg.WriteToString(wstrWithDeletion); + + EXPECT_EQ(TString(_T("\n\ +30000FirstName<WINDOWS>\\FirstPath\ +SecondName<WINDOWS>\\SecondPath")), wstrWithDeletion); +} + +/////////////////////////////////////////////////////////////////////////// +TEST_F(InitializedConfigFixture, ExtractConfig) +{ + TConfig cfgSub; + + m_cfg.ExtractSubConfig(_T("CHConfig.Core.Notifications.Sounds"), cfgSub); + EXPECT_EQ(true, cfgSub.GetBool(_T("Enable"))); + EXPECT_EQ(TString(_T("\\media\\chord.wav")), cfgSub.GetString(_T("ErrorSoundPath"))); + EXPECT_EQ(TString(_T("\\\x597D\x8FD0\\ding.wav")), cfgSub.GetString(_T("FinishedSoundPath"))); +} + +TEST_F(InitializedConfigFixture, ExtractMultipleConfigs) +{ + TConfigArray cfgSubArray; + + m_cfg.ExtractMultiSubConfigs(_T("CHConfig.Core.CompositeObjects.Object"), cfgSubArray); + + EXPECT_EQ(2, cfgSubArray.GetCount()); + + EXPECT_EQ(TString(_T("FirstName")), cfgSubArray.GetAt(0).GetString(_T("Name"))); + EXPECT_EQ(TString(_T("\\FirstPath")), cfgSubArray.GetAt(0).GetString(_T("Path"))); + EXPECT_EQ(TString(_T("SecondName")), cfgSubArray.GetAt(1).GetString(_T("Name"))); + EXPECT_EQ(TString(_T("\\SecondPath")), cfgSubArray.GetAt(1).GetString(_T("Path"))); +} + +TEST(TConfigTests, PutSubConfig) +{ + TConfig mainCfg; + + TConfig cfgSub; + cfgSub.SetValue(_T("Node1"), true); + cfgSub.SetValue(_T("NameNode"), _T("TestNode")); + + mainCfg.PutSubConfig(_T("Root.NodeSet"), cfgSub); + + EXPECT_EQ(true, mainCfg.GetBool(_T("Root.NodeSet.Node1"))); + EXPECT_EQ(TString(_T("TestNode")), mainCfg.GetString(_T("Root.NodeSet.NameNode"))); +} + +TEST(TConfigTests, AddSubConfig) +{ + TConfig mainCfg; + + TConfig cfgSub; + cfgSub.SetValue(_T("Node1"), true); + cfgSub.SetValue(_T("NameNode"), _T("TestNode")); + + mainCfg.AddSubConfig(_T("Root.NodeSet.Node"), cfgSub); + mainCfg.AddSubConfig(_T("Root.NodeSet.Node"), cfgSub); + + TString strXml; + mainCfg.WriteToString(strXml); + + EXPECT_EQ(TString(_T("\n\ +TestNodetrueTestNodetrue")), strXml); +} Index: src/libchcore/Tests/TestsTFileFilter.cpp =================================================================== diff -u -r2755e12daeccb1935f569e7235e685e566b0b098 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTFileFilter.cpp (.../TestsTFileFilter.cpp) (revision 2755e12daeccb1935f569e7235e685e566b0b098) +++ src/libchcore/Tests/TestsTFileFilter.cpp (.../TestsTFileFilter.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,54 +1,54 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TFileFilter.h" - -using namespace chcore; - -TEST(TestsTFileFilter, DefaultConstruction) -{ - TFileFilter filter; - - // other - EXPECT_EQ(0, filter.GetObjectID()); - - EXPECT_EQ(false, filter.GetUseMask()); - EXPECT_STREQ(L"", filter.GetCombinedMask().c_str()); - - EXPECT_EQ(false, filter.GetUseExcludeMask()); - EXPECT_STREQ(L"", filter.GetCombinedExcludeMask().c_str()); - - EXPECT_EQ(false, filter.GetUseSize1()); - EXPECT_EQ(TFileFilter::eSizeCmp_Greater, filter.GetSizeType1()); - EXPECT_EQ(0, filter.GetSize1()); - - EXPECT_EQ(false, filter.GetUseSize2()); - EXPECT_EQ(TFileFilter::eSizeCmp_Less, filter.GetSizeType2()); - EXPECT_EQ(0, filter.GetSize2()); - - // dates - EXPECT_EQ(TFileFilter::eDateType_Created, filter.GetDateType()); - - // date 1 - EXPECT_EQ(false, filter.GetUseDateTime1()); - EXPECT_EQ(TFileFilter::eDateCmp_Greater, filter.GetDateCmpType1()); - EXPECT_EQ(false, filter.GetUseDate1()); - EXPECT_EQ(false, filter.GetUseTime1()); -// EXPECT_EQ(TDateTime(), filter.GetDateTime1()); - - // date 2 - EXPECT_EQ(false, filter.GetUseDateTime2()); - EXPECT_EQ(TFileFilter::eDateCmp_Less, filter.GetDateCmpType2()); - EXPECT_EQ(false, filter.GetUseDate2()); - EXPECT_EQ(false, filter.GetUseTime2()); -// EXPECT_EQ(TDateTime(), filter.GetDateTime2()); - - // attributes - EXPECT_EQ(false, filter.GetUseAttributes()); - EXPECT_EQ(2, filter.GetArchive()); - EXPECT_EQ(2, filter.GetReadOnly()); - EXPECT_EQ(2, filter.GetHidden()); - EXPECT_EQ(2, filter.GetSystem()); - EXPECT_EQ(2, filter.GetDirectory()); - -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TFileFilter.h" + +using namespace chcore; + +TEST(TestsTFileFilter, DefaultConstruction) +{ + TFileFilter filter; + + // other + EXPECT_EQ(0, filter.GetObjectID()); + + EXPECT_EQ(false, filter.GetUseMask()); + EXPECT_STREQ(L"", filter.GetCombinedMask().c_str()); + + EXPECT_EQ(false, filter.GetUseExcludeMask()); + EXPECT_STREQ(L"", filter.GetCombinedExcludeMask().c_str()); + + EXPECT_EQ(false, filter.GetUseSize1()); + EXPECT_EQ(TFileFilter::eSizeCmp_Greater, filter.GetSizeType1()); + EXPECT_EQ(0, filter.GetSize1()); + + EXPECT_EQ(false, filter.GetUseSize2()); + EXPECT_EQ(TFileFilter::eSizeCmp_Less, filter.GetSizeType2()); + EXPECT_EQ(0, filter.GetSize2()); + + // dates + EXPECT_EQ(TFileFilter::eDateType_Created, filter.GetDateType()); + + // date 1 + EXPECT_EQ(false, filter.GetUseDateTime1()); + EXPECT_EQ(TFileFilter::eDateCmp_Greater, filter.GetDateCmpType1()); + EXPECT_EQ(false, filter.GetUseDate1()); + EXPECT_EQ(false, filter.GetUseTime1()); +// EXPECT_EQ(TDateTime(), filter.GetDateTime1()); + + // date 2 + EXPECT_EQ(false, filter.GetUseDateTime2()); + EXPECT_EQ(TFileFilter::eDateCmp_Less, filter.GetDateCmpType2()); + EXPECT_EQ(false, filter.GetUseDate2()); + EXPECT_EQ(false, filter.GetUseTime2()); +// EXPECT_EQ(TDateTime(), filter.GetDateTime2()); + + // attributes + EXPECT_EQ(false, filter.GetUseAttributes()); + EXPECT_EQ(2, filter.GetArchive()); + EXPECT_EQ(2, filter.GetReadOnly()); + EXPECT_EQ(2, filter.GetHidden()); + EXPECT_EQ(2, filter.GetSystem()); + EXPECT_EQ(2, filter.GetDirectory()); + +} Index: src/libchcore/Tests/TestsTModificationTracker.cpp =================================================================== diff -u -r87f7271b86103cc66243554a91af0c0654f55f45 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTModificationTracker.cpp (.../TestsTModificationTracker.cpp) (revision 87f7271b86103cc66243554a91af0c0654f55f45) +++ src/libchcore/Tests/TestsTModificationTracker.cpp (.../TestsTModificationTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,128 +1,128 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TModificationTracker.h" -#include "../TString.h" - -using namespace chcore; - -TEST(TModificationTrackerTests, DefaultConstructor) -{ - TModificationTracker tracker; - - EXPECT_TRUE(tracker.IsModified()); - EXPECT_EQ(TString(), tracker); - EXPECT_FALSE(tracker.IsAdded()); -} - -TEST(TModificationTrackerTests, ValueConstructor_NotAdded) -{ - TModificationTracker tracker(L"SomeString", false); - - EXPECT_EQ(TString(L"SomeString"), tracker); - EXPECT_TRUE(tracker.IsModified()); - EXPECT_FALSE(tracker.IsAdded()); -} - -TEST(TModificationTrackerTests, ValueConstructor_Added) -{ - TModificationTracker tracker(L"SomeString", true); - - EXPECT_EQ(TString(L"SomeString"), tracker); - EXPECT_TRUE(tracker.IsModified()); - EXPECT_TRUE(tracker.IsAdded()); -} - -TEST(TModificationTrackerTests, CopyConstructor_NotAdded) -{ - TModificationTracker tracker(L"SomeString", false); - TModificationTracker tracker2(tracker); - - EXPECT_EQ(TString(L"SomeString"), tracker2); - EXPECT_TRUE(tracker2.IsModified()); - EXPECT_FALSE(tracker2.IsAdded()); -} - -TEST(TModificationTrackerTests, CopyConstructor_Added) -{ - TModificationTracker tracker(L"SomeString", true); - TModificationTracker tracker2(tracker); - - EXPECT_EQ(TString(L"SomeString"), tracker2); - EXPECT_TRUE(tracker2.IsModified()); - EXPECT_TRUE(tracker2.IsAdded()); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TModificationTrackerTests, AssignmentOperator_ModificationTracker_NotAdded) -{ - TModificationTracker tracker(L"SomeString", false); - TModificationTracker tracker2; - - tracker2 = tracker; - - EXPECT_EQ(TString(L"SomeString"), tracker2); - EXPECT_TRUE(tracker2.IsModified()); - EXPECT_FALSE(tracker2.IsAdded()); -} - -TEST(TModificationTrackerTests, AssignmentOperator_ModificationTracker_Added) -{ - TModificationTracker tracker(L"SomeString", true); - TModificationTracker tracker2; - - tracker2 = tracker; - - EXPECT_EQ(TString(L"SomeString"), tracker2); - EXPECT_TRUE(tracker2.IsModified()); - EXPECT_TRUE(tracker2.IsAdded()); -} - -TEST(TModificationTrackerTests, AssignmentOperator_ValueModified) -{ - TModificationTracker tracker(L"SomeString", false); - tracker.ClearModifications(); - - tracker = L"OtherString"; - - EXPECT_EQ(TString(L"OtherString"), tracker); - EXPECT_TRUE(tracker.IsModified()); - EXPECT_FALSE(tracker.IsAdded()); -} - -TEST(TModificationTrackerTests, AssignmentOperator_ValueNotModified) -{ - TModificationTracker tracker(L"SomeString", false); - tracker.ClearModifications(); - - tracker = L"SomeString"; - - EXPECT_EQ(TString(L"SomeString"), tracker); - EXPECT_FALSE(tracker.IsModified()); - EXPECT_FALSE(tracker.IsAdded()); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TModificationTrackerTests, Modify) -{ - TModificationTracker tracker(L"SomeString", false); - tracker.ClearModifications(); - - tracker.Modify() = L"SomeString"; - - EXPECT_EQ(TString(L"SomeString"), tracker); - EXPECT_TRUE(tracker.IsModified()); - EXPECT_FALSE(tracker.IsAdded()); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TModificationTrackerTests, IsModified_IsAdded_ClearModifications) -{ - TModificationTracker tracker(L"SomeString", true); - EXPECT_TRUE(tracker.IsModified()); - EXPECT_TRUE(tracker.IsAdded()); - - tracker.ClearModifications(); - EXPECT_FALSE(tracker.IsModified()); - EXPECT_FALSE(tracker.IsAdded()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TModificationTracker.h" +#include "../TString.h" + +using namespace chcore; + +TEST(TModificationTrackerTests, DefaultConstructor) +{ + TModificationTracker tracker; + + EXPECT_TRUE(tracker.IsModified()); + EXPECT_EQ(TString(), tracker); + EXPECT_FALSE(tracker.IsAdded()); +} + +TEST(TModificationTrackerTests, ValueConstructor_NotAdded) +{ + TModificationTracker tracker(L"SomeString", false); + + EXPECT_EQ(TString(L"SomeString"), tracker); + EXPECT_TRUE(tracker.IsModified()); + EXPECT_FALSE(tracker.IsAdded()); +} + +TEST(TModificationTrackerTests, ValueConstructor_Added) +{ + TModificationTracker tracker(L"SomeString", true); + + EXPECT_EQ(TString(L"SomeString"), tracker); + EXPECT_TRUE(tracker.IsModified()); + EXPECT_TRUE(tracker.IsAdded()); +} + +TEST(TModificationTrackerTests, CopyConstructor_NotAdded) +{ + TModificationTracker tracker(L"SomeString", false); + TModificationTracker tracker2(tracker); + + EXPECT_EQ(TString(L"SomeString"), tracker2); + EXPECT_TRUE(tracker2.IsModified()); + EXPECT_FALSE(tracker2.IsAdded()); +} + +TEST(TModificationTrackerTests, CopyConstructor_Added) +{ + TModificationTracker tracker(L"SomeString", true); + TModificationTracker tracker2(tracker); + + EXPECT_EQ(TString(L"SomeString"), tracker2); + EXPECT_TRUE(tracker2.IsModified()); + EXPECT_TRUE(tracker2.IsAdded()); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TModificationTrackerTests, AssignmentOperator_ModificationTracker_NotAdded) +{ + TModificationTracker tracker(L"SomeString", false); + TModificationTracker tracker2; + + tracker2 = tracker; + + EXPECT_EQ(TString(L"SomeString"), tracker2); + EXPECT_TRUE(tracker2.IsModified()); + EXPECT_FALSE(tracker2.IsAdded()); +} + +TEST(TModificationTrackerTests, AssignmentOperator_ModificationTracker_Added) +{ + TModificationTracker tracker(L"SomeString", true); + TModificationTracker tracker2; + + tracker2 = tracker; + + EXPECT_EQ(TString(L"SomeString"), tracker2); + EXPECT_TRUE(tracker2.IsModified()); + EXPECT_TRUE(tracker2.IsAdded()); +} + +TEST(TModificationTrackerTests, AssignmentOperator_ValueModified) +{ + TModificationTracker tracker(L"SomeString", false); + tracker.ClearModifications(); + + tracker = L"OtherString"; + + EXPECT_EQ(TString(L"OtherString"), tracker); + EXPECT_TRUE(tracker.IsModified()); + EXPECT_FALSE(tracker.IsAdded()); +} + +TEST(TModificationTrackerTests, AssignmentOperator_ValueNotModified) +{ + TModificationTracker tracker(L"SomeString", false); + tracker.ClearModifications(); + + tracker = L"SomeString"; + + EXPECT_EQ(TString(L"SomeString"), tracker); + EXPECT_FALSE(tracker.IsModified()); + EXPECT_FALSE(tracker.IsAdded()); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TModificationTrackerTests, Modify) +{ + TModificationTracker tracker(L"SomeString", false); + tracker.ClearModifications(); + + tracker.Modify() = L"SomeString"; + + EXPECT_EQ(TString(L"SomeString"), tracker); + EXPECT_TRUE(tracker.IsModified()); + EXPECT_FALSE(tracker.IsAdded()); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TModificationTrackerTests, IsModified_IsAdded_ClearModifications) +{ + TModificationTracker tracker(L"SomeString", true); + EXPECT_TRUE(tracker.IsModified()); + EXPECT_TRUE(tracker.IsAdded()); + + tracker.ClearModifications(); + EXPECT_FALSE(tracker.IsModified()); + EXPECT_FALSE(tracker.IsAdded()); +} Index: src/libchcore/Tests/TestsTSQLiteDatabase.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSQLiteDatabase.cpp (.../TestsTSQLiteDatabase.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/Tests/TestsTSQLiteDatabase.cpp (.../TestsTSQLiteDatabase.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,14 +1,14 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSQLiteDatabase.h" - -using namespace chcore; -using namespace sqlite; - -TEST(SQLiteDatabase, CreationWithVerification) -{ - TSQLiteDatabase db(PathFromString(_T(":memory:"))); - EXPECT_TRUE(db.GetHandle() != nullptr); - EXPECT_FALSE(db.GetInTransaction()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSQLiteDatabase.h" + +using namespace chcore; +using namespace sqlite; + +TEST(SQLiteDatabase, CreationWithVerification) +{ + TSQLiteDatabase db(PathFromString(_T(":memory:"))); + EXPECT_TRUE(db.GetHandle() != nullptr); + EXPECT_FALSE(db.GetInTransaction()); +} Index: src/libchcore/Tests/TestsTSQLiteStatement.cpp =================================================================== diff -u -rd18db617f4727a237c94b59af9b4328f829eda16 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSQLiteStatement.cpp (.../TestsTSQLiteStatement.cpp) (revision d18db617f4727a237c94b59af9b4328f829eda16) +++ src/libchcore/Tests/TestsTSQLiteStatement.cpp (.../TestsTSQLiteStatement.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,109 +1,109 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSQLiteDatabase.h" -#include "../TSQLiteStatement.h" -#include "../TSQLiteException.h" - -using namespace chcore; -using namespace sqlite; - -TEST(SQLiteStatement, CorrectPrepare) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); -} - -TEST(SQLiteStatement, IncorrectPrepare) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - EXPECT_THROW(tStatement.Prepare(_T("CREATE incorrect TABLE test(col1 INTEGER, col2 VARCHAR(40))")), TSQLiteException); -} - -TEST(SQLiteStatement, PreparedStep) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - EXPECT_EQ(tStatement.Step(), TSQLiteStatement::eStep_Finished); -} - -TEST(SQLiteStatement, UnpreparedStep) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - EXPECT_THROW(tStatement.Step(), TSQLiteException); -} - -TEST(SQLiteStatement, UnpreparedBind) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - // insert data - EXPECT_THROW(tStatement.BindValue(1, 54), TSQLiteException); -} - -TEST(SQLiteStatement, InsertAndRetrieveData) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - // create schema - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); - - // insert data - tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); - tStatement.BindValue(1, 54); - tStatement.BindValue(2, _T("Some Value")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); - - // retrieve data - tStatement.Prepare(_T("SELECT col2, col1 FROM test")); - EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); - EXPECT_EQ(54, tStatement.GetInt(1)); - EXPECT_EQ(TString(_T("Some Value")), tStatement.GetText(0)); -} - -TEST(SQLiteStatement, ClearBindings) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - // create schema - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); - - // insert data - tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); - - tStatement.BindValue(1, 54); - tStatement.BindValue(2, _T("Some Value")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); - - tStatement.BindValue(1, 32); - tStatement.BindValue(2, _T("???")); - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); - - // retrieve data - tStatement.Prepare(_T("SELECT col2, col1 FROM test ORDER BY col1")); - EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); - - EXPECT_EQ(32, tStatement.GetInt(1)); - EXPECT_EQ(TString(_T("???")), tStatement.GetText(0)); - - EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); - - EXPECT_EQ(54, tStatement.GetInt(1)); - EXPECT_EQ(TString(_T("Some Value")), tStatement.GetText(0)); - - EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSQLiteDatabase.h" +#include "../TSQLiteStatement.h" +#include "../TSQLiteException.h" + +using namespace chcore; +using namespace sqlite; + +TEST(SQLiteStatement, CorrectPrepare) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); +} + +TEST(SQLiteStatement, IncorrectPrepare) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + EXPECT_THROW(tStatement.Prepare(_T("CREATE incorrect TABLE test(col1 INTEGER, col2 VARCHAR(40))")), TSQLiteException); +} + +TEST(SQLiteStatement, PreparedStep) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + EXPECT_EQ(tStatement.Step(), TSQLiteStatement::eStep_Finished); +} + +TEST(SQLiteStatement, UnpreparedStep) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + EXPECT_THROW(tStatement.Step(), TSQLiteException); +} + +TEST(SQLiteStatement, UnpreparedBind) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + // insert data + EXPECT_THROW(tStatement.BindValue(1, 54), TSQLiteException); +} + +TEST(SQLiteStatement, InsertAndRetrieveData) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + // create schema + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); + + // insert data + tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); + tStatement.BindValue(1, 54); + tStatement.BindValue(2, _T("Some Value")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); + + // retrieve data + tStatement.Prepare(_T("SELECT col2, col1 FROM test")); + EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); + EXPECT_EQ(54, tStatement.GetInt(1)); + EXPECT_EQ(TString(_T("Some Value")), tStatement.GetText(0)); +} + +TEST(SQLiteStatement, ClearBindings) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + // create schema + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); + + // insert data + tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); + + tStatement.BindValue(1, 54); + tStatement.BindValue(2, _T("Some Value")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); + + tStatement.BindValue(1, 32); + tStatement.BindValue(2, _T("???")); + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); + + // retrieve data + tStatement.Prepare(_T("SELECT col2, col1 FROM test ORDER BY col1")); + EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); + + EXPECT_EQ(32, tStatement.GetInt(1)); + EXPECT_EQ(TString(_T("???")), tStatement.GetText(0)); + + EXPECT_EQ(TSQLiteStatement::eStep_HasRow, tStatement.Step()); + + EXPECT_EQ(54, tStatement.GetInt(1)); + EXPECT_EQ(TString(_T("Some Value")), tStatement.GetText(0)); + + EXPECT_EQ(TSQLiteStatement::eStep_Finished, tStatement.Step()); +} Index: src/libchcore/Tests/TestsTSQLiteTransaction.cpp =================================================================== diff -u -rd18db617f4727a237c94b59af9b4328f829eda16 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSQLiteTransaction.cpp (.../TestsTSQLiteTransaction.cpp) (revision d18db617f4727a237c94b59af9b4328f829eda16) +++ src/libchcore/Tests/TestsTSQLiteTransaction.cpp (.../TestsTSQLiteTransaction.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,82 +1,82 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSQLiteTransaction.h" -#include "../TSQLiteDatabase.h" -#include "../TSQLiteStatement.h" -#include "../TSQLiteException.h" - -using namespace chcore; -using namespace sqlite; - -TEST(SQLiteTransaction, BeginTransactionWithDefaultRollback_Empty) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - - // separate scope for the transaction - { - TSQLiteTransaction tran(spDB); - EXPECT_TRUE(spDB->GetInTransaction()); - } - EXPECT_FALSE(spDB->GetInTransaction()); -} - -TEST(SQLiteTransaction, BeginTransactionWithDefaultRollback_WithData) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - // separate scope for the transaction - { - TSQLiteTransaction tran(spDB); - - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - tStatement.Step(); - - tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); - tStatement.BindValue(1, 54); - tStatement.BindValue(2, _T("Some Value")); - tStatement.Step(); - } - - // rollback seem to revert the schema changes, so this statement can't be processed due to missing table - EXPECT_THROW(tStatement.Prepare(_T("SELECT count(*) FROM test")), TSQLiteException); -} - -TEST(SQLiteTransaction, BeginTransactionWithCommit) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - - // separate scope for the transaction - TSQLiteTransaction tran(spDB); - - tran.Commit(); - EXPECT_FALSE(spDB->GetInTransaction()); -} - -TEST(SQLiteTransaction, BeginTransactionWithCommit_WithData) -{ - TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); - TSQLiteStatement tStatement(spDB); - - // separate scope for the transaction - { - TSQLiteTransaction tran(spDB); - - tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); - tStatement.Step(); - - tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); - tStatement.BindValue(1, 54); - tStatement.BindValue(2, _T("Some Value")); - tStatement.Step(); - - tran.Commit(); - } - - // rollback seem to revert the schema changes, so this statement can't be processed due to missing table - tStatement.Prepare(_T("SELECT count(*) FROM test")); - tStatement.Step(); - - EXPECT_EQ(1, tStatement.GetInt(0)); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSQLiteTransaction.h" +#include "../TSQLiteDatabase.h" +#include "../TSQLiteStatement.h" +#include "../TSQLiteException.h" + +using namespace chcore; +using namespace sqlite; + +TEST(SQLiteTransaction, BeginTransactionWithDefaultRollback_Empty) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + + // separate scope for the transaction + { + TSQLiteTransaction tran(spDB); + EXPECT_TRUE(spDB->GetInTransaction()); + } + EXPECT_FALSE(spDB->GetInTransaction()); +} + +TEST(SQLiteTransaction, BeginTransactionWithDefaultRollback_WithData) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + // separate scope for the transaction + { + TSQLiteTransaction tran(spDB); + + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + tStatement.Step(); + + tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); + tStatement.BindValue(1, 54); + tStatement.BindValue(2, _T("Some Value")); + tStatement.Step(); + } + + // rollback seem to revert the schema changes, so this statement can't be processed due to missing table + EXPECT_THROW(tStatement.Prepare(_T("SELECT count(*) FROM test")), TSQLiteException); +} + +TEST(SQLiteTransaction, BeginTransactionWithCommit) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + + // separate scope for the transaction + TSQLiteTransaction tran(spDB); + + tran.Commit(); + EXPECT_FALSE(spDB->GetInTransaction()); +} + +TEST(SQLiteTransaction, BeginTransactionWithCommit_WithData) +{ + TSQLiteDatabasePtr spDB(new TSQLiteDatabase(PathFromString(_T(":memory:")))); + TSQLiteStatement tStatement(spDB); + + // separate scope for the transaction + { + TSQLiteTransaction tran(spDB); + + tStatement.Prepare(_T("CREATE TABLE test(col1 INTEGER, col2 VARCHAR(40))")); + tStatement.Step(); + + tStatement.Prepare(_T("INSERT INTO test(col1, col2) VALUES(?1, ?2)")); + tStatement.BindValue(1, 54); + tStatement.BindValue(2, _T("Some Value")); + tStatement.Step(); + + tran.Commit(); + } + + // rollback seem to revert the schema changes, so this statement can't be processed due to missing table + tStatement.Prepare(_T("SELECT count(*) FROM test")); + tStatement.Step(); + + EXPECT_EQ(1, tStatement.GetInt(0)); +} Index: src/libchcore/Tests/TestsTSharedModificationTracker.cpp =================================================================== diff -u -r87f7271b86103cc66243554a91af0c0654f55f45 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSharedModificationTracker.cpp (.../TestsTSharedModificationTracker.cpp) (revision 87f7271b86103cc66243554a91af0c0654f55f45) +++ src/libchcore/Tests/TestsTSharedModificationTracker.cpp (.../TestsTSharedModificationTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,193 +1,193 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSharedModificationTracker.h" -#include -#include "../TString.h" - -using namespace chcore; - -TEST(TSharedModificationTrackerTests, DefaultConstructor) -{ - enum { eMyElement, eLast }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - - EXPECT_EQ(true, tracker.IsModified()); - EXPECT_EQ(true, setBits[eMyElement]); - EXPECT_EQ(TString(), tracker); -} - -TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Modified) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - - std::bitset setBits2; - TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); - - EXPECT_EQ(true, tracker2.IsModified()); - EXPECT_EQ(true, setBits2[eMyElement]); - EXPECT_EQ(TString(), tracker2); -} - -TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Modified_WithValue) -{ - enum - { - eMyElement, eLast - }; - - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - tracker = L"SomeString"; - - std::bitset setBits2; - TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); - - EXPECT_EQ(true, tracker2.IsModified()); - EXPECT_EQ(true, setBits2[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker2); -} - -TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Unmodified) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - tracker.MarkAsUnmodified(); - - std::bitset setBits2; - TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); - - EXPECT_EQ(false, tracker2.IsModified()); - EXPECT_EQ(false, setBits2[eMyElement]); -} - -TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Unmodified_WithValue) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - tracker = L"SomeString"; - tracker.MarkAsUnmodified(); - - std::bitset setBits2; - TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); - - EXPECT_EQ(false, tracker2.IsModified()); - EXPECT_EQ(false, setBits2[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker2); -} - -TEST(TSharedModificationTrackerTests, ConstructorWithValue) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); - - EXPECT_EQ(true, tracker.IsModified()); - EXPECT_EQ(true, setBits[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TSharedModificationTrackerTests, AssignmentOperator_SharedTracker) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); - - std::bitset setBits2; - TSharedModificationTracker, eMyElement> tracker2(setBits2); - tracker2 = tracker; - - EXPECT_EQ(true, tracker2.IsModified()); - EXPECT_EQ(true, setBits2[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker2); -} - -TEST(TSharedModificationTrackerTests, AssignmentOperator_OtherValue_ModifiesValue) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - - tracker = L"SomeString"; - - EXPECT_EQ(true, tracker.IsModified()); - EXPECT_EQ(true, setBits[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker); -} - -TEST(TSharedModificationTrackerTests, AssignmentOperator_OtherValue_DoesNotModifyValue) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits); - - tracker = L"SomeString"; - - EXPECT_EQ(true, tracker.IsModified()); - EXPECT_EQ(true, setBits[eMyElement]); - EXPECT_EQ(TString(L"SomeString"), tracker); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TSharedModificationTrackerTests, Modify) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); - tracker.MarkAsUnmodified(); - - tracker.Modify() = L"OtherString"; - - EXPECT_EQ(true, tracker.IsModified()); - EXPECT_EQ(true, setBits[eMyElement]); - EXPECT_EQ(TString(L"OtherString"), tracker); -} - -/////////////////////////////////////////////////////////////////////////// -TEST(TSharedModificationTrackerTests, MarkAsModified_MarkAsUnmodified) -{ - enum - { - eMyElement, eLast - }; - std::bitset setBits; - TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); - - EXPECT_EQ(true, tracker.IsModified()); - - tracker.MarkAsUnmodified(); - EXPECT_EQ(false, tracker.IsModified()); - - tracker.MarkAsModified(); - EXPECT_EQ(true, tracker.IsModified()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSharedModificationTracker.h" +#include +#include "../TString.h" + +using namespace chcore; + +TEST(TSharedModificationTrackerTests, DefaultConstructor) +{ + enum { eMyElement, eLast }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + + EXPECT_EQ(true, tracker.IsModified()); + EXPECT_EQ(true, setBits[eMyElement]); + EXPECT_EQ(TString(), tracker); +} + +TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Modified) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + + std::bitset setBits2; + TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); + + EXPECT_EQ(true, tracker2.IsModified()); + EXPECT_EQ(true, setBits2[eMyElement]); + EXPECT_EQ(TString(), tracker2); +} + +TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Modified_WithValue) +{ + enum + { + eMyElement, eLast + }; + + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + tracker = L"SomeString"; + + std::bitset setBits2; + TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); + + EXPECT_EQ(true, tracker2.IsModified()); + EXPECT_EQ(true, setBits2[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker2); +} + +TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Unmodified) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + tracker.MarkAsUnmodified(); + + std::bitset setBits2; + TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); + + EXPECT_EQ(false, tracker2.IsModified()); + EXPECT_EQ(false, setBits2[eMyElement]); +} + +TEST(TSharedModificationTrackerTests, AlmostCopyConstructor_Unmodified_WithValue) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + tracker = L"SomeString"; + tracker.MarkAsUnmodified(); + + std::bitset setBits2; + TSharedModificationTracker, eMyElement> tracker2(tracker, setBits2); + + EXPECT_EQ(false, tracker2.IsModified()); + EXPECT_EQ(false, setBits2[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker2); +} + +TEST(TSharedModificationTrackerTests, ConstructorWithValue) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); + + EXPECT_EQ(true, tracker.IsModified()); + EXPECT_EQ(true, setBits[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TSharedModificationTrackerTests, AssignmentOperator_SharedTracker) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); + + std::bitset setBits2; + TSharedModificationTracker, eMyElement> tracker2(setBits2); + tracker2 = tracker; + + EXPECT_EQ(true, tracker2.IsModified()); + EXPECT_EQ(true, setBits2[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker2); +} + +TEST(TSharedModificationTrackerTests, AssignmentOperator_OtherValue_ModifiesValue) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + + tracker = L"SomeString"; + + EXPECT_EQ(true, tracker.IsModified()); + EXPECT_EQ(true, setBits[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker); +} + +TEST(TSharedModificationTrackerTests, AssignmentOperator_OtherValue_DoesNotModifyValue) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits); + + tracker = L"SomeString"; + + EXPECT_EQ(true, tracker.IsModified()); + EXPECT_EQ(true, setBits[eMyElement]); + EXPECT_EQ(TString(L"SomeString"), tracker); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TSharedModificationTrackerTests, Modify) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); + tracker.MarkAsUnmodified(); + + tracker.Modify() = L"OtherString"; + + EXPECT_EQ(true, tracker.IsModified()); + EXPECT_EQ(true, setBits[eMyElement]); + EXPECT_EQ(TString(L"OtherString"), tracker); +} + +/////////////////////////////////////////////////////////////////////////// +TEST(TSharedModificationTrackerTests, MarkAsModified_MarkAsUnmodified) +{ + enum + { + eMyElement, eLast + }; + std::bitset setBits; + TSharedModificationTracker, eMyElement> tracker(setBits, L"SomeString"); + + EXPECT_EQ(true, tracker.IsModified()); + + tracker.MarkAsUnmodified(); + EXPECT_EQ(false, tracker.IsModified()); + + tracker.MarkAsModified(); + EXPECT_EQ(true, tracker.IsModified()); +} Index: src/libchcore/Tests/TestsTSimpleTimer.cpp =================================================================== diff -u -r4fe995b304ea342b50293f92d3c1992b43b820f7 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSimpleTimer.cpp (.../TestsTSimpleTimer.cpp) (revision 4fe995b304ea342b50293f92d3c1992b43b820f7) +++ src/libchcore/Tests/TestsTSimpleTimer.cpp (.../TestsTSimpleTimer.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,90 +1,90 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSimpleTimer.h" -#include "../ITimestampProvider.h" - -class ITimestampProviderMock : public chcore::ITimestampProvider -{ -public: - MOCK_CONST_METHOD0(GetCurrentTimestamp, unsigned long long()); -}; - -using namespace testing; -using namespace chcore; - -TEST(TSimpleTimerTests, SimpleStartStop_CalculatesTimeProperly) -{ - std::shared_ptr > spTimestampProviderMock(new StrictMock); - - EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) - .WillOnce(Return(30)) - .WillOnce(Return(100)); - - TSimpleTimer tTimer(false, spTimestampProviderMock); - tTimer.Start(); - EXPECT_EQ(70, tTimer.Stop()); - EXPECT_EQ(70, tTimer.GetTotalTime()); - EXPECT_EQ(100, tTimer.GetLastTimestamp()); -} - -TEST(TSimpleTimerTests, TickWithoutStarting_UpdatesLastTimestamp) -{ - std::shared_ptr > spTimestampProviderMock(new StrictMock); - - EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) - .WillOnce(Return(30)); - - TSimpleTimer tTimer(false, spTimestampProviderMock); - tTimer.Tick(); - EXPECT_EQ(30, tTimer.GetLastTimestamp()); -} - -TEST(TSimpleTimerTests, StartAndTicking_CorrectlyCountsTime) -{ - std::shared_ptr > spTimestampProviderMock(new StrictMock); - - EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) - .WillOnce(Return(30)) - .WillOnce(Return(40)) - .WillOnce(Return(990)); - - TSimpleTimer tTimer(false, spTimestampProviderMock); - tTimer.Start(); - tTimer.Tick(); - EXPECT_EQ(10, tTimer.GetTotalTime()); - tTimer.Tick(); - EXPECT_EQ((990 - 30), tTimer.GetTotalTime()); -} - -TEST(TSimpleTimerTests, StartAndTicking_TickReturnsLastTimestamp) -{ - std::shared_ptr > spTimestampProviderMock(new StrictMock); - - EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) - .WillOnce(Return(30)) - .WillOnce(Return(40)) - .WillOnce(Return(990)); - - TSimpleTimer tTimer(false, spTimestampProviderMock); - tTimer.Start(); - EXPECT_EQ(40, tTimer.Tick()); - EXPECT_EQ(990, tTimer.Tick()); -} - -TEST(TSimpleTimerTests, Reset_StopsTimeCountingAndResetsTime) -{ - std::shared_ptr > spTimestampProviderMock(new StrictMock); - - EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) - .WillOnce(Return(30)) - .WillOnce(Return(40)); - - TSimpleTimer tTimer(false, spTimestampProviderMock); - tTimer.Start(); - tTimer.Tick(); - - tTimer.Reset(); - EXPECT_EQ(tTimer.GetTotalTime(), 0); - EXPECT_EQ(tTimer.GetLastTimestamp(), 0); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSimpleTimer.h" +#include "../ITimestampProvider.h" + +class ITimestampProviderMock : public chcore::ITimestampProvider +{ +public: + MOCK_CONST_METHOD0(GetCurrentTimestamp, unsigned long long()); +}; + +using namespace testing; +using namespace chcore; + +TEST(TSimpleTimerTests, SimpleStartStop_CalculatesTimeProperly) +{ + std::shared_ptr > spTimestampProviderMock(new StrictMock); + + EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) + .WillOnce(Return(30)) + .WillOnce(Return(100)); + + TSimpleTimer tTimer(false, spTimestampProviderMock); + tTimer.Start(); + EXPECT_EQ(70, tTimer.Stop()); + EXPECT_EQ(70, tTimer.GetTotalTime()); + EXPECT_EQ(100, tTimer.GetLastTimestamp()); +} + +TEST(TSimpleTimerTests, TickWithoutStarting_UpdatesLastTimestamp) +{ + std::shared_ptr > spTimestampProviderMock(new StrictMock); + + EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) + .WillOnce(Return(30)); + + TSimpleTimer tTimer(false, spTimestampProviderMock); + tTimer.Tick(); + EXPECT_EQ(30, tTimer.GetLastTimestamp()); +} + +TEST(TSimpleTimerTests, StartAndTicking_CorrectlyCountsTime) +{ + std::shared_ptr > spTimestampProviderMock(new StrictMock); + + EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) + .WillOnce(Return(30)) + .WillOnce(Return(40)) + .WillOnce(Return(990)); + + TSimpleTimer tTimer(false, spTimestampProviderMock); + tTimer.Start(); + tTimer.Tick(); + EXPECT_EQ(10, tTimer.GetTotalTime()); + tTimer.Tick(); + EXPECT_EQ((990 - 30), tTimer.GetTotalTime()); +} + +TEST(TSimpleTimerTests, StartAndTicking_TickReturnsLastTimestamp) +{ + std::shared_ptr > spTimestampProviderMock(new StrictMock); + + EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) + .WillOnce(Return(30)) + .WillOnce(Return(40)) + .WillOnce(Return(990)); + + TSimpleTimer tTimer(false, spTimestampProviderMock); + tTimer.Start(); + EXPECT_EQ(40, tTimer.Tick()); + EXPECT_EQ(990, tTimer.Tick()); +} + +TEST(TSimpleTimerTests, Reset_StopsTimeCountingAndResetsTime) +{ + std::shared_ptr > spTimestampProviderMock(new StrictMock); + + EXPECT_CALL(*spTimestampProviderMock, GetCurrentTimestamp()) + .WillOnce(Return(30)) + .WillOnce(Return(40)); + + TSimpleTimer tTimer(false, spTimestampProviderMock); + tTimer.Start(); + tTimer.Tick(); + + tTimer.Reset(); + EXPECT_EQ(tTimer.GetTotalTime(), 0); + EXPECT_EQ(tTimer.GetLastTimestamp(), 0); +} Index: src/libchcore/Tests/TestsTSmartPath.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSmartPath.cpp (.../TestsTSmartPath.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/Tests/TestsTSmartPath.cpp (.../TestsTSmartPath.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,1253 +1,1253 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TPath.h" -#include "../TCoreException.h" -#include "../TPathContainer.h" - -using namespace chcore; - -TEST(TSmartPathTests, EmptyPathToString) -{ - TSmartPath tPath; - EXPECT_STREQ(tPath.ToString(), _T("")); -} - -TEST(TSmartPathTests, PathFromString) -{ - TSmartPath tPath; - tPath.FromString(_T("c:\\test")); - EXPECT_STREQ(tPath.ToString(), _T("c:\\test")); -} - -TEST(TSmartPathTests, PathFromNullString) -{ - TSmartPath tPath; - EXPECT_THROW(tPath.FromString(nullptr), TCoreException); -} - -TEST(TSmartPathTests, PathFromTStringToWString) -{ - TSmartPath tPath; - tPath.FromString(TString(_T("c:\\test"))); - EXPECT_EQ(tPath.ToWString(), TString(_T("c:\\test"))); -} - -TEST(TSmartPathTests, PathFromEmptyTStringToString) -{ - TSmartPath tPath; - tPath.FromString(TString()); - EXPECT_STREQ(tPath.ToString(), _T("")); -} - -// path comparison -TEST(TSmartPathTests, PathComparison) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\test path")); - path2.FromString(_T("C:\\Test Path")); - - EXPECT_TRUE(path1 == path2); -} - -TEST(TSmartPathTests, PathComparisonLTGT) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("C:\\Test Path")); - - EXPECT_TRUE(path1 < path2); - EXPECT_TRUE(path2 > path1); -} - -TEST(TSmartPathTests, PathClear) -{ - TSmartPath path; - - path.FromString(_T("c:\\First path")); - path.Clear(); - - EXPECT_STREQ(path.ToString(), _T("")); -} - -TEST(TSmartPathTests, AppendCopyWithSeparator) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("some directory")); - - TSmartPath retPath = path1.AppendCopy(path2, true); - EXPECT_STREQ(retPath.ToString(), _T("c:\\First path\\some directory")); -} - -TEST(TSmartPathTests, AppendCopyWithoutSeparator) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("some directory")); - - TSmartPath retPath = path1.AppendCopy(path2, false); - EXPECT_STREQ(retPath.ToString(), _T("c:\\First pathsome directory")); -} - - -TEST(TSmartPathTests, AppendWithSeparator) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("some directory")); - - path1.Append(path2, true); - EXPECT_STREQ(path1.ToString(), _T("c:\\First path\\some directory")); -} - -TEST(TSmartPathTests, AppendWithoutSeparator) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("some directory")); - - path1.Append(path2, false); - EXPECT_STREQ(path1.ToString(), _T("c:\\First pathsome directory")); -} - -TEST(TSmartPathTests, SplitPath) -{ - TSmartPath path; - TPathContainer vPaths; - - path.FromString(_T("c:\\First path\\some directory\\file.txt")); - path.SplitPath(vPaths); - - EXPECT_EQ(4, vPaths.GetCount()); - EXPECT_STREQ(_T("c:"), vPaths.GetAt(0).ToString()); - EXPECT_STREQ(_T("First path"), vPaths.GetAt(1).ToString()); - EXPECT_STREQ(_T("some directory"), vPaths.GetAt(2).ToString()); - EXPECT_STREQ(_T("file.txt"), vPaths.GetAt(3).ToString()); -} - -TEST(TSmartPathTests, SplitEmptyPath) -{ - TSmartPath path; - TPathContainer vPaths; - - path.FromString(_T("")); - path.SplitPath(vPaths); - - EXPECT_EQ(0, vPaths.GetCount()); -} - -TEST(TSmartPathTests, CompareLTGTCaseInsensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("C:\\Test Path")); - - EXPECT_TRUE(path1.Compare(path2, false) < 0); - EXPECT_TRUE(path2.Compare(path1, false) > 0); -} - -TEST(TSmartPathTests, CompareEQCaseInsensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("C:\\first Path")); - - EXPECT_TRUE(path1.Compare(path2, false) == 0); -} - -TEST(TSmartPathTests, CompareLTGTCaseSensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("C:\\Test Path")); - - EXPECT_TRUE(path1.Compare(path2, false) < 0); - EXPECT_TRUE(path2.Compare(path1, false) > 0); -} - -TEST(TSmartPathTests, CompareEQCaseSensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path")); - path2.FromString(_T("C:\\first Path")); - - EXPECT_TRUE(path1.Compare(path2, true) != 0); -} - -TEST(TSmartPathTests, CompareEQCaseSensitive2) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\first path")); - path2.FromString(_T("c:\\first path")); - - EXPECT_TRUE(path1.Compare(path2, true) == 0); -} - -TEST(TSmartPathTests, IsChildOf_CaseInsensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path\\second path")); - path2.FromString(_T("C:\\first path")); - - EXPECT_TRUE(path1.IsChildOf(path2, false)); -} - -TEST(TSmartPathTests, IsChildOf_CaseSensitive_NegativeCase) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\First path\\second path")); - path2.FromString(_T("C:\\first path")); - - EXPECT_FALSE(path1.IsChildOf(path2, true)); -} - -TEST(TSmartPathTests, IsChildOf_CaseSensitive_PositiveCase) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\first path\\second path")); - path2.FromString(_T("c:\\first path")); - - EXPECT_TRUE(path1.IsChildOf(path2, true)); -} - -TEST(TSmartPathTests, MakeRelativePath_CaseInensitive) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\first path\\second path")); - path2.FromString(_T("C:\\First Path")); - - EXPECT_TRUE(path1.MakeRelativePath(path2, false)); - EXPECT_STREQ(_T("\\second path"), path1.ToString()); -} - -TEST(TSmartPathTests, MakeRelativePath_CaseSensitive_NegativeCase) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\first path\\second path")); - path2.FromString(_T("C:\\First Path")); - - EXPECT_FALSE(path1.MakeRelativePath(path2, true)); - EXPECT_STREQ(_T("c:\\first path\\second path"), path1.ToString()); -} - -TEST(TSmartPathTests, MakeRelativePath_CaseSensitive_PositiveCase) -{ - TSmartPath path1; - TSmartPath path2; - - path1.FromString(_T("c:\\first path\\second path")); - path2.FromString(_T("c:\\first path")); - - EXPECT_TRUE(path1.MakeRelativePath(path2, true)); - EXPECT_STREQ(_T("\\second path"), path1.ToString()); -} - -TEST(TSmartPathTests, AppendIfNotExists_CaseInsensitive_PositiveCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path")); - - path2.AppendIfNotExists(_T("\\second path"), false); - EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); -} - -TEST(TSmartPathTests, AppendIfNotExists_CaseInsensitive_NegativeCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path\\Second Path")); - - path2.AppendIfNotExists(_T("\\second path"), false); - EXPECT_STREQ(_T("c:\\first path\\Second Path"), path2.ToString()); -} - - -TEST(TSmartPathTests, AppendIfNotExists_CaseSensitive_PositiveCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path")); - - path2.AppendIfNotExists(_T("\\second path"), true); - EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); -} - -TEST(TSmartPathTests, AppendIfNotExists_CaseSensitive_NegativeCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path\\second path")); - - path2.AppendIfNotExists(_T("\\second path"), true); - EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); -} - -TEST(TSmartPathTests, CutIfExists_CaseInsensitive_PositiveCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path")); - - path2.CutIfExists(_T("\\second path"), false); - EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); -} - -TEST(TSmartPathTests, CutIfExists_CaseInsensitive_NegativeCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path\\Second Path")); - - path2.CutIfExists(_T("\\second path"), false); - EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); -} - - -TEST(TSmartPathTests, CutIfExists_CaseSensitive_PositiveCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path")); - - path2.CutIfExists(_T("\\second path"), true); - EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); -} - -TEST(TSmartPathTests, CutIfExists_CaseSensitive_NegativeCase) -{ - TSmartPath path2; - - path2.FromString(_T("c:\\first path\\second path")); - - path2.CutIfExists(_T("\\second path"), true); - EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); -} - -TEST(TSmartPathTests, IsNetworkPath_Negative) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_FALSE(path.IsNetworkPath()); -} - -TEST(TSmartPathTests, IsNetworkPath_Positive) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.IsNetworkPath()); -} - -TEST(TSmartPathTests, IsDrive_Negative) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_FALSE(path.IsDrive()); -} - -TEST(TSmartPathTests, IsDrive_Negative_2) -{ - TSmartPath path; - path.FromString(_T("c:\\")); - - EXPECT_FALSE(path.IsDrive()); -} - -TEST(TSmartPathTests, IsDrive_Positive) -{ - TSmartPath path; - path.FromString(_T("c:")); - - EXPECT_TRUE(path.IsDrive()); -} - -TEST(TSmartPathTests, HasDrive_Positive) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_TRUE(path.HasDrive()); -} - -TEST(TSmartPathTests, HasDrive_Positive_2) -{ - TSmartPath path; - path.FromString(_T("c:\\")); - - EXPECT_TRUE(path.HasDrive()); -} - -TEST(TSmartPathTests, HasDrive_Positive_3) -{ - TSmartPath path; - path.FromString(_T("c:")); - - EXPECT_TRUE(path.HasDrive()); -} - -TEST(TSmartPathTests, HasDrive_Negative) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\share")); - - EXPECT_FALSE(path.HasDrive()); -} - -TEST(TSmartPathTests, GetDriveAndDriveLetterFromLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - TSmartPath pathDrive = path.GetDrive(); - wchar_t wchDrive = path.GetDriveLetter(); // makes drive letter uppercase - - EXPECT_STREQ(_T("c:"), pathDrive.ToString()); - EXPECT_EQ(_T('C'), wchDrive); -} - -TEST(TSmartPathTests, GetDriveAndDriveLetterFromNonLocalPath) -{ - TSmartPath path; - path.FromString(_T("\\serv01\\first path\\second path")); - - TSmartPath pathDrive = path.GetDrive(); - wchar_t wchDrive = path.GetDriveLetter(); // makes drive letter uppercase - - EXPECT_STREQ(_T(""), pathDrive.ToString()); - EXPECT_EQ(_T('\0'), wchDrive); -} - -TEST(TSmartPathTests, IsServerName_Negative) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_FALSE(path.IsServerName()); -} - -TEST(TSmartPathTests, IsServerName_Negative_2) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\")); - - EXPECT_FALSE(path.IsServerName()); -} - -TEST(TSmartPathTests, IsServerName_Positive) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01")); - - EXPECT_TRUE(path.IsServerName()); -} - -TEST(TSmartPathTests, HasServerName_Positive) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.HasServerName()); -} - -TEST(TSmartPathTests, HasServerName_Positive_2) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\")); - - EXPECT_TRUE(path.HasServerName()); -} - -TEST(TSmartPathTests, HasServerName_Positive_3) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01")); - - EXPECT_TRUE(path.HasServerName()); -} - -TEST(TSmartPathTests, HasServerName_Negative) -{ - TSmartPath path; - path.FromString(_T("c:\\path")); - - EXPECT_FALSE(path.HasServerName()); -} - -TEST(TSmartPathTests, GetServerName) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - TSmartPath pathServerName = path.GetServerName(); - - EXPECT_STREQ(_T("\\\\serv01"), pathServerName.ToString()); -} - -TEST(TSmartPathTests, GetServerNameFromLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - TSmartPath pathServerName = path.GetServerName(); - - EXPECT_STREQ(_T(""), pathServerName.ToString()); -} - -TEST(TSmartPathTests, HasFileRootLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_TRUE(path.HasFileRoot()); -} - -TEST(TSmartPathTests, HasFileRootRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.HasFileRoot()); -} - -TEST(TSmartPathTests, HasFileRootRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_TRUE(path.HasFileRoot()); -} - -TEST(TSmartPathTests, HasFileRootFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_FALSE(path.HasFileRoot()); -} - -TEST(TSmartPathTests, GetFileRootLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_STREQ(_T("c:\\first path\\"), path.GetFileRoot().ToString()); -} - -TEST(TSmartPathTests, GetFileRootRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_STREQ(_T("\\\\serv01\\first path\\"), path.GetFileRoot().ToString()); -} - -TEST(TSmartPathTests, GetFileRootRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_STREQ(_T("..\\"), path.GetFileRoot().ToString()); -} - -TEST(TSmartPathTests, GetFileRootFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_STREQ(_T(""), path.GetFileRoot().ToString()); -} - -// has/get file dir -TEST(TSmartPathTests, HasFileDirLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_TRUE(path.HasFileDir()); -} - -TEST(TSmartPathTests, HasFileDirRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.HasFileDir()); -} - -TEST(TSmartPathTests, HasFileDirRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_TRUE(path.HasFileDir()); -} - -TEST(TSmartPathTests, HasFileDirFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_FALSE(path.HasFileDir()); -} - -TEST(TSmartPathTests, GetFileDirLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_STREQ(_T("\\first path\\"), path.GetFileDir().ToString()); -} - -TEST(TSmartPathTests, GetFileDirRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_STREQ(_T("\\first path\\"), path.GetFileDir().ToString()); -} - -TEST(TSmartPathTests, GetFileDirRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_STREQ(_T("..\\"), path.GetFileDir().ToString()); -} - -TEST(TSmartPathTests, GetFileDirFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_STREQ(_T(""), path.GetFileDir().ToString()); -} - -// has/get file title -TEST(TSmartPathTests, HasFileTitleLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_TRUE(path.HasFileTitle()); -} - -TEST(TSmartPathTests, HasFileTitleRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.HasFileTitle()); -} - -TEST(TSmartPathTests, HasFileTitleRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_TRUE(path.HasFileTitle()); -} - -TEST(TSmartPathTests, HasFileTitleFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_TRUE(path.HasFileTitle()); -} - -TEST(TSmartPathTests, HasFileTitleFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory\\")); - - EXPECT_FALSE(path.HasFileTitle()); -} - -TEST(TSmartPathTests, GetFileTitleLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_STREQ(_T("second path"), path.GetFileTitle().ToString()); -} - -TEST(TSmartPathTests, GetFileTitleRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_STREQ(_T("second path"), path.GetFileTitle().ToString()); -} - -TEST(TSmartPathTests, GetFileTitleRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_STREQ(_T("file"), path.GetFileTitle().ToString()); -} - -TEST(TSmartPathTests, GetFileTitleFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_STREQ(_T("file"), path.GetFileTitle().ToString()); -} - -TEST(TSmartPathTests, GetFileTitleFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory\\")); - - EXPECT_STREQ(_T(""), path.GetFileTitle().ToString()); -} - -// has/get file name -TEST(TSmartPathTests, HasFileNameLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_TRUE(path.HasFileName()); -} - -TEST(TSmartPathTests, HasFileNameRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_TRUE(path.HasFileName()); -} - -TEST(TSmartPathTests, HasFileNameRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_TRUE(path.HasFileName()); -} - -TEST(TSmartPathTests, HasFileNameFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_TRUE(path.HasFileName()); -} - -TEST(TSmartPathTests, HasFileNameFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory\\")); - - EXPECT_FALSE(path.HasFileName()); -} - -TEST(TSmartPathTests, GetFileNameLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_STREQ(_T("second path"), path.GetFileName().ToString()); -} - -TEST(TSmartPathTests, GetFileNameRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_STREQ(_T("second path"), path.GetFileName().ToString()); -} - -TEST(TSmartPathTests, GetFileNameRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - EXPECT_STREQ(_T("file.txt"), path.GetFileName().ToString()); -} - -TEST(TSmartPathTests, GetFileNameFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - EXPECT_STREQ(_T("file.txt"), path.GetFileName().ToString()); -} - -TEST(TSmartPathTests, GetFileNameFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory\\")); - - EXPECT_STREQ(_T(""), path.GetFileName().ToString()); -} - -// delete filename -TEST(TSmartPathTests, DeleteFileNameLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - path.DeleteFileName(); - - EXPECT_STREQ(_T("c:\\first path\\"), path.ToString()); -} - -TEST(TSmartPathTests, DeleteFileNameRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - path.DeleteFileName(); - - EXPECT_STREQ(_T("\\\\serv01\\first path\\"), path.ToString()); -} - -TEST(TSmartPathTests, DeleteFileNameRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\file.txt")); - - path.DeleteFileName(); - - EXPECT_STREQ(_T("..\\"), path.ToString()); -} - -TEST(TSmartPathTests, DeleteFileNameFileNameOnly) -{ - TSmartPath path; - path.FromString(_T("file.txt")); - - path.DeleteFileName(); - - EXPECT_STREQ(_T(""), path.ToString()); -} - -TEST(TSmartPathTests, DeleteFileNameFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory\\")); - - path.DeleteFileName(); - - EXPECT_STREQ(_T("c:\\directory\\"), path.ToString()); -} - -// has/get file extension -TEST(TSmartPathTests, HasExtensionLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path.txt")); - - EXPECT_TRUE(path.HasExtension()); -} - -TEST(TSmartPathTests, HasExtensionRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path.txt")); - - EXPECT_TRUE(path.HasExtension()); -} - -TEST(TSmartPathTests, HasExtensionLocalPathNegative) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_FALSE(path.HasExtension()); -} - -TEST(TSmartPathTests, HasExtensionRemotePathNegatice) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_FALSE(path.HasExtension()); -} - -TEST(TSmartPathTests, HasExtensionRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\directory")); - - EXPECT_FALSE(path.HasExtension()); -} - -TEST(TSmartPathTests, HasExtensionFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext\\")); - - EXPECT_FALSE(path.HasExtension()); -} - -TEST(TSmartPathTests, GetExtensionLocalPath) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path.txt")); - - EXPECT_STREQ(_T(".txt"), path.GetExtension().ToString()); -} - -TEST(TSmartPathTests, GetExtensionRemotePath) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path.txt")); - - EXPECT_STREQ(_T(".txt"), path.GetExtension().ToString()); -} - -TEST(TSmartPathTests, GetExtensionLocalPathNegative) -{ - TSmartPath path; - path.FromString(_T("c:\\first path\\second path")); - - EXPECT_STREQ(_T(""), path.GetExtension().ToString()); -} - -TEST(TSmartPathTests, GetExtensionRemotePathNegatice) -{ - TSmartPath path; - path.FromString(_T("\\\\serv01\\first path\\second path")); - - EXPECT_STREQ(_T(""), path.GetExtension().ToString()); -} - -TEST(TSmartPathTests, GetExtensionRelativePath) -{ - TSmartPath path; - path.FromString(_T("..\\directory")); - - EXPECT_STREQ(_T(""), path.GetExtension().ToString()); -} - -TEST(TSmartPathTests, GetExtensionFileDirOnly) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext\\")); - - EXPECT_STREQ(_T(""), path.GetExtension().ToString()); -} - -// separator operations -TEST(TSmartPathTests, EndsWithSeparator_True) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext\\")); - - EXPECT_TRUE(path.EndsWithSeparator()); -} - -TEST(TSmartPathTests, EndsWithSeparator_False) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext")); - - EXPECT_FALSE(path.EndsWithSeparator()); -} - -TEST(TSmartPathTests, AppendSeparator_AlreadyExists) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext\\")); - path.AppendSeparatorIfDoesNotExist(); - EXPECT_STREQ(_T("c:\\directory.ext\\"), path.ToString()); -} - -TEST(TSmartPathTests, AppendSeparator_DoesNotExist) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext")); - path.AppendSeparatorIfDoesNotExist(); - EXPECT_STREQ(_T("c:\\directory.ext\\"), path.ToString()); -} - -TEST(TSmartPathTests, StripSeparator_AlreadyExists) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext\\")); - path.StripSeparatorAtEnd(); - EXPECT_STREQ(_T("c:\\directory.ext"), path.ToString()); -} - -TEST(TSmartPathTests, StripSeparator_DoesNotExist) -{ - TSmartPath path; - path.FromString(_T("c:\\directory.ext")); - path.StripSeparatorAtEnd(); - EXPECT_STREQ(_T("c:\\directory.ext"), path.ToString()); -} - -// separator at front -TEST(TSmartPathTests, StartsWithSeparator_True) -{ - TSmartPath path; - path.FromString(_T("\\directory.ext\\")); - - EXPECT_TRUE(path.StartsWithSeparator()); -} - -TEST(TSmartPathTests, StartsWithSeparator_False) -{ - TSmartPath path; - path.FromString(_T("directory.ext")); - - EXPECT_FALSE(path.StartsWithSeparator()); -} - -TEST(TSmartPathTests, PrependSeparator_AlreadyExists) -{ - TSmartPath path; - path.FromString(_T("\\directory.ext")); - path.PrependSeparatorIfDoesNotExist(); - EXPECT_STREQ(_T("\\directory.ext"), path.ToString()); -} - -TEST(TSmartPathTests, PrependSeparator_DoesNotExist) -{ - TSmartPath path; - path.FromString(_T("directory.ext")); - path.PrependSeparatorIfDoesNotExist(); - EXPECT_STREQ(_T("\\directory.ext"), path.ToString()); -} - -TEST(TSmartPathTests, StripSeparatorAtFront_AlreadyExists) -{ - TSmartPath path; - path.FromString(_T("\\directory.ext")); - path.StripSeparatorAtFront(); - EXPECT_STREQ(_T("directory.ext"), path.ToString()); -} - -TEST(TSmartPathTests, StripSeparatorAtFront_DoesNotExist) -{ - TSmartPath path; - path.FromString(_T("directory.ext")); - path.StripSeparatorAtFront(); - EXPECT_STREQ(_T("directory.ext"), path.ToString()); -} - -// isempty, get length -TEST(TSmartPathTests, IsEmpty_Empty) -{ - TSmartPath path; - path.FromString(_T("")); - EXPECT_TRUE(path.IsEmpty()); -} - -TEST(TSmartPathTests, IsEmpty_NotInitializedEmpty) -{ - TSmartPath path; - EXPECT_TRUE(path.IsEmpty()); -} - -TEST(TSmartPathTests, IsEmpty_NotEmpty) -{ - TSmartPath path; - path.FromString(_T("some path")); - EXPECT_FALSE(path.IsEmpty()); -} - -TEST(TSmartPathTests, GetLength_Empty) -{ - TSmartPath path; - path.FromString(_T("")); - EXPECT_EQ(0, path.GetLength()); -} - -TEST(TSmartPathTests, GetLength_NotInitializedEmpty) -{ - TSmartPath path; - EXPECT_EQ(0, path.GetLength()); -} - -TEST(TSmartPathTests, GetLength_NotEmpty) -{ - TSmartPath path; - path.FromString(_T("some path")); - EXPECT_EQ(9, path.GetLength()); -} - -/////////////////////////////////////////////////////////////////////////////// -TEST(TSmartPathTests, GetParent_FilePath) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\test.txt"); - - EXPECT_STREQ(L"c:\\windows\\", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_DirPath) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\"); - - EXPECT_STREQ(L"c:\\", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_NetFilePath) -{ - TSmartPath path; - path.FromString(L"\\\\SomeServer\\windows\\test.txt"); - - EXPECT_STREQ(L"\\\\SomeServer\\windows\\", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_NetDirPath) -{ - TSmartPath path; - path.FromString(L"\\\\SomeServer\\windows\\"); - - EXPECT_STREQ(L"\\\\SomeServer\\", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_ServerNameRootDir) -{ - TSmartPath path; - path.FromString(L"\\\\SomeServer\\"); - - EXPECT_STREQ(L"\\\\SomeServer", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_DiskRootDir) -{ - TSmartPath path; - path.FromString(L"c:\\"); - - EXPECT_STREQ(L"c:", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_ServerName) -{ - TSmartPath path; - path.FromString(L"\\\\SomeServer"); - - EXPECT_STREQ(L"", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, GetParent_Disk) -{ - TSmartPath path; - path.FromString(L"c:"); - - EXPECT_STREQ(L"", path.GetParent().ToString()); -} - -TEST(TSmartPathTests, StartsWith_SameCase_Positive) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"))); -} - -TEST(TSmartPathTests, StartsWith_NoCase_SameCase_Positive) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"), false)); -} - -TEST(TSmartPathTests, StartsWith_NoCase_DiffCase_Positive) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\Windows"), false)); -} - -TEST(TSmartPathTests, StartsWith_CaseSensitive_SameCase_Positive) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"), true)); -} - -TEST(TSmartPathTests, StartsWith_CaseSensitive_DiffCase_Positive) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"c:\\Windows"), true)); -} - -TEST(TSmartPathTests, StartsWith_SameCase_Negative) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"))); -} - -TEST(TSmartPathTests, StartsWith_NoCase_SameCase_Negative) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"), false)); -} - -TEST(TSmartPathTests, StartsWith_NoCase_DiffCase_Negative) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"\\Windows"), false)); -} - -TEST(TSmartPathTests, StartsWith_CaseSensitive_SameCase_Negative) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"), true)); -} - -TEST(TSmartPathTests, StartsWith_CaseSensitive_DiffCase_Negative) -{ - TSmartPath path; - path.FromString(L"c:\\windows\\file.txt"); - - EXPECT_FALSE(path.StartsWith(PathFromString(L"\\Windows"), true)); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TPath.h" +#include "../TCoreException.h" +#include "../TPathContainer.h" + +using namespace chcore; + +TEST(TSmartPathTests, EmptyPathToString) +{ + TSmartPath tPath; + EXPECT_STREQ(tPath.ToString(), _T("")); +} + +TEST(TSmartPathTests, PathFromString) +{ + TSmartPath tPath; + tPath.FromString(_T("c:\\test")); + EXPECT_STREQ(tPath.ToString(), _T("c:\\test")); +} + +TEST(TSmartPathTests, PathFromNullString) +{ + TSmartPath tPath; + EXPECT_THROW(tPath.FromString(nullptr), TCoreException); +} + +TEST(TSmartPathTests, PathFromTStringToWString) +{ + TSmartPath tPath; + tPath.FromString(TString(_T("c:\\test"))); + EXPECT_EQ(tPath.ToWString(), TString(_T("c:\\test"))); +} + +TEST(TSmartPathTests, PathFromEmptyTStringToString) +{ + TSmartPath tPath; + tPath.FromString(TString()); + EXPECT_STREQ(tPath.ToString(), _T("")); +} + +// path comparison +TEST(TSmartPathTests, PathComparison) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\test path")); + path2.FromString(_T("C:\\Test Path")); + + EXPECT_TRUE(path1 == path2); +} + +TEST(TSmartPathTests, PathComparisonLTGT) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("C:\\Test Path")); + + EXPECT_TRUE(path1 < path2); + EXPECT_TRUE(path2 > path1); +} + +TEST(TSmartPathTests, PathClear) +{ + TSmartPath path; + + path.FromString(_T("c:\\First path")); + path.Clear(); + + EXPECT_STREQ(path.ToString(), _T("")); +} + +TEST(TSmartPathTests, AppendCopyWithSeparator) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("some directory")); + + TSmartPath retPath = path1.AppendCopy(path2, true); + EXPECT_STREQ(retPath.ToString(), _T("c:\\First path\\some directory")); +} + +TEST(TSmartPathTests, AppendCopyWithoutSeparator) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("some directory")); + + TSmartPath retPath = path1.AppendCopy(path2, false); + EXPECT_STREQ(retPath.ToString(), _T("c:\\First pathsome directory")); +} + + +TEST(TSmartPathTests, AppendWithSeparator) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("some directory")); + + path1.Append(path2, true); + EXPECT_STREQ(path1.ToString(), _T("c:\\First path\\some directory")); +} + +TEST(TSmartPathTests, AppendWithoutSeparator) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("some directory")); + + path1.Append(path2, false); + EXPECT_STREQ(path1.ToString(), _T("c:\\First pathsome directory")); +} + +TEST(TSmartPathTests, SplitPath) +{ + TSmartPath path; + TPathContainer vPaths; + + path.FromString(_T("c:\\First path\\some directory\\file.txt")); + path.SplitPath(vPaths); + + EXPECT_EQ(4, vPaths.GetCount()); + EXPECT_STREQ(_T("c:"), vPaths.GetAt(0).ToString()); + EXPECT_STREQ(_T("First path"), vPaths.GetAt(1).ToString()); + EXPECT_STREQ(_T("some directory"), vPaths.GetAt(2).ToString()); + EXPECT_STREQ(_T("file.txt"), vPaths.GetAt(3).ToString()); +} + +TEST(TSmartPathTests, SplitEmptyPath) +{ + TSmartPath path; + TPathContainer vPaths; + + path.FromString(_T("")); + path.SplitPath(vPaths); + + EXPECT_EQ(0, vPaths.GetCount()); +} + +TEST(TSmartPathTests, CompareLTGTCaseInsensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("C:\\Test Path")); + + EXPECT_TRUE(path1.Compare(path2, false) < 0); + EXPECT_TRUE(path2.Compare(path1, false) > 0); +} + +TEST(TSmartPathTests, CompareEQCaseInsensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("C:\\first Path")); + + EXPECT_TRUE(path1.Compare(path2, false) == 0); +} + +TEST(TSmartPathTests, CompareLTGTCaseSensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("C:\\Test Path")); + + EXPECT_TRUE(path1.Compare(path2, false) < 0); + EXPECT_TRUE(path2.Compare(path1, false) > 0); +} + +TEST(TSmartPathTests, CompareEQCaseSensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path")); + path2.FromString(_T("C:\\first Path")); + + EXPECT_TRUE(path1.Compare(path2, true) != 0); +} + +TEST(TSmartPathTests, CompareEQCaseSensitive2) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\first path")); + path2.FromString(_T("c:\\first path")); + + EXPECT_TRUE(path1.Compare(path2, true) == 0); +} + +TEST(TSmartPathTests, IsChildOf_CaseInsensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path\\second path")); + path2.FromString(_T("C:\\first path")); + + EXPECT_TRUE(path1.IsChildOf(path2, false)); +} + +TEST(TSmartPathTests, IsChildOf_CaseSensitive_NegativeCase) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\First path\\second path")); + path2.FromString(_T("C:\\first path")); + + EXPECT_FALSE(path1.IsChildOf(path2, true)); +} + +TEST(TSmartPathTests, IsChildOf_CaseSensitive_PositiveCase) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\first path\\second path")); + path2.FromString(_T("c:\\first path")); + + EXPECT_TRUE(path1.IsChildOf(path2, true)); +} + +TEST(TSmartPathTests, MakeRelativePath_CaseInensitive) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\first path\\second path")); + path2.FromString(_T("C:\\First Path")); + + EXPECT_TRUE(path1.MakeRelativePath(path2, false)); + EXPECT_STREQ(_T("\\second path"), path1.ToString()); +} + +TEST(TSmartPathTests, MakeRelativePath_CaseSensitive_NegativeCase) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\first path\\second path")); + path2.FromString(_T("C:\\First Path")); + + EXPECT_FALSE(path1.MakeRelativePath(path2, true)); + EXPECT_STREQ(_T("c:\\first path\\second path"), path1.ToString()); +} + +TEST(TSmartPathTests, MakeRelativePath_CaseSensitive_PositiveCase) +{ + TSmartPath path1; + TSmartPath path2; + + path1.FromString(_T("c:\\first path\\second path")); + path2.FromString(_T("c:\\first path")); + + EXPECT_TRUE(path1.MakeRelativePath(path2, true)); + EXPECT_STREQ(_T("\\second path"), path1.ToString()); +} + +TEST(TSmartPathTests, AppendIfNotExists_CaseInsensitive_PositiveCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path")); + + path2.AppendIfNotExists(_T("\\second path"), false); + EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); +} + +TEST(TSmartPathTests, AppendIfNotExists_CaseInsensitive_NegativeCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path\\Second Path")); + + path2.AppendIfNotExists(_T("\\second path"), false); + EXPECT_STREQ(_T("c:\\first path\\Second Path"), path2.ToString()); +} + + +TEST(TSmartPathTests, AppendIfNotExists_CaseSensitive_PositiveCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path")); + + path2.AppendIfNotExists(_T("\\second path"), true); + EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); +} + +TEST(TSmartPathTests, AppendIfNotExists_CaseSensitive_NegativeCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path\\second path")); + + path2.AppendIfNotExists(_T("\\second path"), true); + EXPECT_STREQ(_T("c:\\first path\\second path"), path2.ToString()); +} + +TEST(TSmartPathTests, CutIfExists_CaseInsensitive_PositiveCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path")); + + path2.CutIfExists(_T("\\second path"), false); + EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); +} + +TEST(TSmartPathTests, CutIfExists_CaseInsensitive_NegativeCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path\\Second Path")); + + path2.CutIfExists(_T("\\second path"), false); + EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); +} + + +TEST(TSmartPathTests, CutIfExists_CaseSensitive_PositiveCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path")); + + path2.CutIfExists(_T("\\second path"), true); + EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); +} + +TEST(TSmartPathTests, CutIfExists_CaseSensitive_NegativeCase) +{ + TSmartPath path2; + + path2.FromString(_T("c:\\first path\\second path")); + + path2.CutIfExists(_T("\\second path"), true); + EXPECT_STREQ(_T("c:\\first path"), path2.ToString()); +} + +TEST(TSmartPathTests, IsNetworkPath_Negative) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_FALSE(path.IsNetworkPath()); +} + +TEST(TSmartPathTests, IsNetworkPath_Positive) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.IsNetworkPath()); +} + +TEST(TSmartPathTests, IsDrive_Negative) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_FALSE(path.IsDrive()); +} + +TEST(TSmartPathTests, IsDrive_Negative_2) +{ + TSmartPath path; + path.FromString(_T("c:\\")); + + EXPECT_FALSE(path.IsDrive()); +} + +TEST(TSmartPathTests, IsDrive_Positive) +{ + TSmartPath path; + path.FromString(_T("c:")); + + EXPECT_TRUE(path.IsDrive()); +} + +TEST(TSmartPathTests, HasDrive_Positive) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_TRUE(path.HasDrive()); +} + +TEST(TSmartPathTests, HasDrive_Positive_2) +{ + TSmartPath path; + path.FromString(_T("c:\\")); + + EXPECT_TRUE(path.HasDrive()); +} + +TEST(TSmartPathTests, HasDrive_Positive_3) +{ + TSmartPath path; + path.FromString(_T("c:")); + + EXPECT_TRUE(path.HasDrive()); +} + +TEST(TSmartPathTests, HasDrive_Negative) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\share")); + + EXPECT_FALSE(path.HasDrive()); +} + +TEST(TSmartPathTests, GetDriveAndDriveLetterFromLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + TSmartPath pathDrive = path.GetDrive(); + wchar_t wchDrive = path.GetDriveLetter(); // makes drive letter uppercase + + EXPECT_STREQ(_T("c:"), pathDrive.ToString()); + EXPECT_EQ(_T('C'), wchDrive); +} + +TEST(TSmartPathTests, GetDriveAndDriveLetterFromNonLocalPath) +{ + TSmartPath path; + path.FromString(_T("\\serv01\\first path\\second path")); + + TSmartPath pathDrive = path.GetDrive(); + wchar_t wchDrive = path.GetDriveLetter(); // makes drive letter uppercase + + EXPECT_STREQ(_T(""), pathDrive.ToString()); + EXPECT_EQ(_T('\0'), wchDrive); +} + +TEST(TSmartPathTests, IsServerName_Negative) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_FALSE(path.IsServerName()); +} + +TEST(TSmartPathTests, IsServerName_Negative_2) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\")); + + EXPECT_FALSE(path.IsServerName()); +} + +TEST(TSmartPathTests, IsServerName_Positive) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01")); + + EXPECT_TRUE(path.IsServerName()); +} + +TEST(TSmartPathTests, HasServerName_Positive) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.HasServerName()); +} + +TEST(TSmartPathTests, HasServerName_Positive_2) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\")); + + EXPECT_TRUE(path.HasServerName()); +} + +TEST(TSmartPathTests, HasServerName_Positive_3) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01")); + + EXPECT_TRUE(path.HasServerName()); +} + +TEST(TSmartPathTests, HasServerName_Negative) +{ + TSmartPath path; + path.FromString(_T("c:\\path")); + + EXPECT_FALSE(path.HasServerName()); +} + +TEST(TSmartPathTests, GetServerName) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + TSmartPath pathServerName = path.GetServerName(); + + EXPECT_STREQ(_T("\\\\serv01"), pathServerName.ToString()); +} + +TEST(TSmartPathTests, GetServerNameFromLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + TSmartPath pathServerName = path.GetServerName(); + + EXPECT_STREQ(_T(""), pathServerName.ToString()); +} + +TEST(TSmartPathTests, HasFileRootLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_TRUE(path.HasFileRoot()); +} + +TEST(TSmartPathTests, HasFileRootRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.HasFileRoot()); +} + +TEST(TSmartPathTests, HasFileRootRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_TRUE(path.HasFileRoot()); +} + +TEST(TSmartPathTests, HasFileRootFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_FALSE(path.HasFileRoot()); +} + +TEST(TSmartPathTests, GetFileRootLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_STREQ(_T("c:\\first path\\"), path.GetFileRoot().ToString()); +} + +TEST(TSmartPathTests, GetFileRootRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_STREQ(_T("\\\\serv01\\first path\\"), path.GetFileRoot().ToString()); +} + +TEST(TSmartPathTests, GetFileRootRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_STREQ(_T("..\\"), path.GetFileRoot().ToString()); +} + +TEST(TSmartPathTests, GetFileRootFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_STREQ(_T(""), path.GetFileRoot().ToString()); +} + +// has/get file dir +TEST(TSmartPathTests, HasFileDirLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_TRUE(path.HasFileDir()); +} + +TEST(TSmartPathTests, HasFileDirRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.HasFileDir()); +} + +TEST(TSmartPathTests, HasFileDirRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_TRUE(path.HasFileDir()); +} + +TEST(TSmartPathTests, HasFileDirFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_FALSE(path.HasFileDir()); +} + +TEST(TSmartPathTests, GetFileDirLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_STREQ(_T("\\first path\\"), path.GetFileDir().ToString()); +} + +TEST(TSmartPathTests, GetFileDirRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_STREQ(_T("\\first path\\"), path.GetFileDir().ToString()); +} + +TEST(TSmartPathTests, GetFileDirRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_STREQ(_T("..\\"), path.GetFileDir().ToString()); +} + +TEST(TSmartPathTests, GetFileDirFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_STREQ(_T(""), path.GetFileDir().ToString()); +} + +// has/get file title +TEST(TSmartPathTests, HasFileTitleLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_TRUE(path.HasFileTitle()); +} + +TEST(TSmartPathTests, HasFileTitleRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.HasFileTitle()); +} + +TEST(TSmartPathTests, HasFileTitleRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_TRUE(path.HasFileTitle()); +} + +TEST(TSmartPathTests, HasFileTitleFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_TRUE(path.HasFileTitle()); +} + +TEST(TSmartPathTests, HasFileTitleFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory\\")); + + EXPECT_FALSE(path.HasFileTitle()); +} + +TEST(TSmartPathTests, GetFileTitleLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_STREQ(_T("second path"), path.GetFileTitle().ToString()); +} + +TEST(TSmartPathTests, GetFileTitleRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_STREQ(_T("second path"), path.GetFileTitle().ToString()); +} + +TEST(TSmartPathTests, GetFileTitleRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_STREQ(_T("file"), path.GetFileTitle().ToString()); +} + +TEST(TSmartPathTests, GetFileTitleFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_STREQ(_T("file"), path.GetFileTitle().ToString()); +} + +TEST(TSmartPathTests, GetFileTitleFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory\\")); + + EXPECT_STREQ(_T(""), path.GetFileTitle().ToString()); +} + +// has/get file name +TEST(TSmartPathTests, HasFileNameLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_TRUE(path.HasFileName()); +} + +TEST(TSmartPathTests, HasFileNameRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_TRUE(path.HasFileName()); +} + +TEST(TSmartPathTests, HasFileNameRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_TRUE(path.HasFileName()); +} + +TEST(TSmartPathTests, HasFileNameFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_TRUE(path.HasFileName()); +} + +TEST(TSmartPathTests, HasFileNameFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory\\")); + + EXPECT_FALSE(path.HasFileName()); +} + +TEST(TSmartPathTests, GetFileNameLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_STREQ(_T("second path"), path.GetFileName().ToString()); +} + +TEST(TSmartPathTests, GetFileNameRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_STREQ(_T("second path"), path.GetFileName().ToString()); +} + +TEST(TSmartPathTests, GetFileNameRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + EXPECT_STREQ(_T("file.txt"), path.GetFileName().ToString()); +} + +TEST(TSmartPathTests, GetFileNameFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + EXPECT_STREQ(_T("file.txt"), path.GetFileName().ToString()); +} + +TEST(TSmartPathTests, GetFileNameFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory\\")); + + EXPECT_STREQ(_T(""), path.GetFileName().ToString()); +} + +// delete filename +TEST(TSmartPathTests, DeleteFileNameLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + path.DeleteFileName(); + + EXPECT_STREQ(_T("c:\\first path\\"), path.ToString()); +} + +TEST(TSmartPathTests, DeleteFileNameRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + path.DeleteFileName(); + + EXPECT_STREQ(_T("\\\\serv01\\first path\\"), path.ToString()); +} + +TEST(TSmartPathTests, DeleteFileNameRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\file.txt")); + + path.DeleteFileName(); + + EXPECT_STREQ(_T("..\\"), path.ToString()); +} + +TEST(TSmartPathTests, DeleteFileNameFileNameOnly) +{ + TSmartPath path; + path.FromString(_T("file.txt")); + + path.DeleteFileName(); + + EXPECT_STREQ(_T(""), path.ToString()); +} + +TEST(TSmartPathTests, DeleteFileNameFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory\\")); + + path.DeleteFileName(); + + EXPECT_STREQ(_T("c:\\directory\\"), path.ToString()); +} + +// has/get file extension +TEST(TSmartPathTests, HasExtensionLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path.txt")); + + EXPECT_TRUE(path.HasExtension()); +} + +TEST(TSmartPathTests, HasExtensionRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path.txt")); + + EXPECT_TRUE(path.HasExtension()); +} + +TEST(TSmartPathTests, HasExtensionLocalPathNegative) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_FALSE(path.HasExtension()); +} + +TEST(TSmartPathTests, HasExtensionRemotePathNegatice) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_FALSE(path.HasExtension()); +} + +TEST(TSmartPathTests, HasExtensionRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\directory")); + + EXPECT_FALSE(path.HasExtension()); +} + +TEST(TSmartPathTests, HasExtensionFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext\\")); + + EXPECT_FALSE(path.HasExtension()); +} + +TEST(TSmartPathTests, GetExtensionLocalPath) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path.txt")); + + EXPECT_STREQ(_T(".txt"), path.GetExtension().ToString()); +} + +TEST(TSmartPathTests, GetExtensionRemotePath) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path.txt")); + + EXPECT_STREQ(_T(".txt"), path.GetExtension().ToString()); +} + +TEST(TSmartPathTests, GetExtensionLocalPathNegative) +{ + TSmartPath path; + path.FromString(_T("c:\\first path\\second path")); + + EXPECT_STREQ(_T(""), path.GetExtension().ToString()); +} + +TEST(TSmartPathTests, GetExtensionRemotePathNegatice) +{ + TSmartPath path; + path.FromString(_T("\\\\serv01\\first path\\second path")); + + EXPECT_STREQ(_T(""), path.GetExtension().ToString()); +} + +TEST(TSmartPathTests, GetExtensionRelativePath) +{ + TSmartPath path; + path.FromString(_T("..\\directory")); + + EXPECT_STREQ(_T(""), path.GetExtension().ToString()); +} + +TEST(TSmartPathTests, GetExtensionFileDirOnly) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext\\")); + + EXPECT_STREQ(_T(""), path.GetExtension().ToString()); +} + +// separator operations +TEST(TSmartPathTests, EndsWithSeparator_True) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext\\")); + + EXPECT_TRUE(path.EndsWithSeparator()); +} + +TEST(TSmartPathTests, EndsWithSeparator_False) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext")); + + EXPECT_FALSE(path.EndsWithSeparator()); +} + +TEST(TSmartPathTests, AppendSeparator_AlreadyExists) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext\\")); + path.AppendSeparatorIfDoesNotExist(); + EXPECT_STREQ(_T("c:\\directory.ext\\"), path.ToString()); +} + +TEST(TSmartPathTests, AppendSeparator_DoesNotExist) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext")); + path.AppendSeparatorIfDoesNotExist(); + EXPECT_STREQ(_T("c:\\directory.ext\\"), path.ToString()); +} + +TEST(TSmartPathTests, StripSeparator_AlreadyExists) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext\\")); + path.StripSeparatorAtEnd(); + EXPECT_STREQ(_T("c:\\directory.ext"), path.ToString()); +} + +TEST(TSmartPathTests, StripSeparator_DoesNotExist) +{ + TSmartPath path; + path.FromString(_T("c:\\directory.ext")); + path.StripSeparatorAtEnd(); + EXPECT_STREQ(_T("c:\\directory.ext"), path.ToString()); +} + +// separator at front +TEST(TSmartPathTests, StartsWithSeparator_True) +{ + TSmartPath path; + path.FromString(_T("\\directory.ext\\")); + + EXPECT_TRUE(path.StartsWithSeparator()); +} + +TEST(TSmartPathTests, StartsWithSeparator_False) +{ + TSmartPath path; + path.FromString(_T("directory.ext")); + + EXPECT_FALSE(path.StartsWithSeparator()); +} + +TEST(TSmartPathTests, PrependSeparator_AlreadyExists) +{ + TSmartPath path; + path.FromString(_T("\\directory.ext")); + path.PrependSeparatorIfDoesNotExist(); + EXPECT_STREQ(_T("\\directory.ext"), path.ToString()); +} + +TEST(TSmartPathTests, PrependSeparator_DoesNotExist) +{ + TSmartPath path; + path.FromString(_T("directory.ext")); + path.PrependSeparatorIfDoesNotExist(); + EXPECT_STREQ(_T("\\directory.ext"), path.ToString()); +} + +TEST(TSmartPathTests, StripSeparatorAtFront_AlreadyExists) +{ + TSmartPath path; + path.FromString(_T("\\directory.ext")); + path.StripSeparatorAtFront(); + EXPECT_STREQ(_T("directory.ext"), path.ToString()); +} + +TEST(TSmartPathTests, StripSeparatorAtFront_DoesNotExist) +{ + TSmartPath path; + path.FromString(_T("directory.ext")); + path.StripSeparatorAtFront(); + EXPECT_STREQ(_T("directory.ext"), path.ToString()); +} + +// isempty, get length +TEST(TSmartPathTests, IsEmpty_Empty) +{ + TSmartPath path; + path.FromString(_T("")); + EXPECT_TRUE(path.IsEmpty()); +} + +TEST(TSmartPathTests, IsEmpty_NotInitializedEmpty) +{ + TSmartPath path; + EXPECT_TRUE(path.IsEmpty()); +} + +TEST(TSmartPathTests, IsEmpty_NotEmpty) +{ + TSmartPath path; + path.FromString(_T("some path")); + EXPECT_FALSE(path.IsEmpty()); +} + +TEST(TSmartPathTests, GetLength_Empty) +{ + TSmartPath path; + path.FromString(_T("")); + EXPECT_EQ(0, path.GetLength()); +} + +TEST(TSmartPathTests, GetLength_NotInitializedEmpty) +{ + TSmartPath path; + EXPECT_EQ(0, path.GetLength()); +} + +TEST(TSmartPathTests, GetLength_NotEmpty) +{ + TSmartPath path; + path.FromString(_T("some path")); + EXPECT_EQ(9, path.GetLength()); +} + +/////////////////////////////////////////////////////////////////////////////// +TEST(TSmartPathTests, GetParent_FilePath) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\test.txt"); + + EXPECT_STREQ(L"c:\\windows\\", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_DirPath) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\"); + + EXPECT_STREQ(L"c:\\", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_NetFilePath) +{ + TSmartPath path; + path.FromString(L"\\\\SomeServer\\windows\\test.txt"); + + EXPECT_STREQ(L"\\\\SomeServer\\windows\\", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_NetDirPath) +{ + TSmartPath path; + path.FromString(L"\\\\SomeServer\\windows\\"); + + EXPECT_STREQ(L"\\\\SomeServer\\", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_ServerNameRootDir) +{ + TSmartPath path; + path.FromString(L"\\\\SomeServer\\"); + + EXPECT_STREQ(L"\\\\SomeServer", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_DiskRootDir) +{ + TSmartPath path; + path.FromString(L"c:\\"); + + EXPECT_STREQ(L"c:", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_ServerName) +{ + TSmartPath path; + path.FromString(L"\\\\SomeServer"); + + EXPECT_STREQ(L"", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, GetParent_Disk) +{ + TSmartPath path; + path.FromString(L"c:"); + + EXPECT_STREQ(L"", path.GetParent().ToString()); +} + +TEST(TSmartPathTests, StartsWith_SameCase_Positive) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"))); +} + +TEST(TSmartPathTests, StartsWith_NoCase_SameCase_Positive) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"), false)); +} + +TEST(TSmartPathTests, StartsWith_NoCase_DiffCase_Positive) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\Windows"), false)); +} + +TEST(TSmartPathTests, StartsWith_CaseSensitive_SameCase_Positive) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_TRUE(path.StartsWith(PathFromString(L"c:\\windows"), true)); +} + +TEST(TSmartPathTests, StartsWith_CaseSensitive_DiffCase_Positive) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"c:\\Windows"), true)); +} + +TEST(TSmartPathTests, StartsWith_SameCase_Negative) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"))); +} + +TEST(TSmartPathTests, StartsWith_NoCase_SameCase_Negative) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"), false)); +} + +TEST(TSmartPathTests, StartsWith_NoCase_DiffCase_Negative) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"\\Windows"), false)); +} + +TEST(TSmartPathTests, StartsWith_CaseSensitive_SameCase_Negative) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"\\windows"), true)); +} + +TEST(TSmartPathTests, StartsWith_CaseSensitive_DiffCase_Negative) +{ + TSmartPath path; + path.FromString(L"c:\\windows\\file.txt"); + + EXPECT_FALSE(path.StartsWith(PathFromString(L"\\Windows"), true)); +} Index: src/libchcore/Tests/TestsTSparseRangeMap.cpp =================================================================== diff -u -r5efb534fc5440a7ab779d2514a00486ecb58e845 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSparseRangeMap.cpp (.../TestsTSparseRangeMap.cpp) (revision 5efb534fc5440a7ab779d2514a00486ecb58e845) +++ src/libchcore/Tests/TestsTSparseRangeMap.cpp (.../TestsTSparseRangeMap.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,89 +1,89 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "../TSparseRangeMap.h" - -using namespace chcore; - -TEST(TestsTSparseRangeMap, DefaultConstructor) -{ - TSparseRangeMap map; - EXPECT_EQ(0, map.GetRangeCount()); - EXPECT_EQ(false, map.OverlapsRange(0, 0)); -} - -TEST(TestsTSparseRangeMap, SingleRange) -{ - TSparseRangeMap map; - map.Insert(45, 59); - - file_size_t fsStart = 0; - file_size_t fsEnd = 0; - - EXPECT_EQ(1, map.GetRangeCount()); - map.GetRangeAt(0, fsStart, fsEnd); - EXPECT_EQ(45, fsStart); - EXPECT_EQ(59, fsEnd); - - EXPECT_EQ(false, map.OverlapsRange(44, 44)); - EXPECT_EQ(false, map.OverlapsRange(60, 60)); - EXPECT_EQ(true, map.OverlapsRange(45, 45)); - EXPECT_EQ(true, map.OverlapsRange(59, 59)); -} - -TEST(TestsTSparseRangeMap, MultipleUnrelatedRanges) -{ - TSparseRangeMap map; - map.Insert(45, 59); - map.Insert(63, 85); - map.Insert(92, 87); - - file_size_t fsStart = 0; - file_size_t fsEnd = 0; - - EXPECT_EQ(3, map.GetRangeCount()); - map.GetRangeAt(0, fsStart, fsEnd); - EXPECT_EQ(45, fsStart); - EXPECT_EQ(59, fsEnd); - map.GetRangeAt(1, fsStart, fsEnd); - EXPECT_EQ(63, fsStart); - EXPECT_EQ(85, fsEnd); - map.GetRangeAt(2, fsStart, fsEnd); - EXPECT_EQ(87, fsStart); - EXPECT_EQ(92, fsEnd); - - EXPECT_EQ(false, map.OverlapsRange(44, 44)); - EXPECT_EQ(false, map.OverlapsRange(60, 60)); - EXPECT_EQ(true, map.OverlapsRange(45, 45)); - EXPECT_EQ(true, map.OverlapsRange(59, 59)); - - EXPECT_EQ(false, map.OverlapsRange(62, 62)); - EXPECT_EQ(false, map.OverlapsRange(86, 86)); - EXPECT_EQ(true, map.OverlapsRange(63, 63)); - EXPECT_EQ(true, map.OverlapsRange(85, 85)); - - EXPECT_EQ(false, map.OverlapsRange(86, 86)); - EXPECT_EQ(false, map.OverlapsRange(93, 93)); - EXPECT_EQ(true, map.OverlapsRange(87, 87)); - EXPECT_EQ(true, map.OverlapsRange(92, 92)); -} - -TEST(TestsTSparseRangeMap, MultipleRelatedRanges) -{ - TSparseRangeMap map; - map.Insert(45, 59); - map.Insert(60, 85); - map.Insert(36, 50); - - file_size_t fsStart = 0; - file_size_t fsEnd = 0; - - EXPECT_EQ(1, map.GetRangeCount()); - map.GetRangeAt(0, fsStart, fsEnd); - EXPECT_EQ(36, fsStart); - EXPECT_EQ(85, fsEnd); - - EXPECT_EQ(false, map.OverlapsRange(35, 35)); - EXPECT_EQ(false, map.OverlapsRange(86, 86)); - EXPECT_EQ(true, map.OverlapsRange(36, 36)); - EXPECT_EQ(true, map.OverlapsRange(85, 85)); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "../TSparseRangeMap.h" + +using namespace chcore; + +TEST(TestsTSparseRangeMap, DefaultConstructor) +{ + TSparseRangeMap map; + EXPECT_EQ(0, map.GetRangeCount()); + EXPECT_EQ(false, map.OverlapsRange(0, 0)); +} + +TEST(TestsTSparseRangeMap, SingleRange) +{ + TSparseRangeMap map; + map.Insert(45, 59); + + file_size_t fsStart = 0; + file_size_t fsEnd = 0; + + EXPECT_EQ(1, map.GetRangeCount()); + map.GetRangeAt(0, fsStart, fsEnd); + EXPECT_EQ(45, fsStart); + EXPECT_EQ(59, fsEnd); + + EXPECT_EQ(false, map.OverlapsRange(44, 44)); + EXPECT_EQ(false, map.OverlapsRange(60, 60)); + EXPECT_EQ(true, map.OverlapsRange(45, 45)); + EXPECT_EQ(true, map.OverlapsRange(59, 59)); +} + +TEST(TestsTSparseRangeMap, MultipleUnrelatedRanges) +{ + TSparseRangeMap map; + map.Insert(45, 59); + map.Insert(63, 85); + map.Insert(92, 87); + + file_size_t fsStart = 0; + file_size_t fsEnd = 0; + + EXPECT_EQ(3, map.GetRangeCount()); + map.GetRangeAt(0, fsStart, fsEnd); + EXPECT_EQ(45, fsStart); + EXPECT_EQ(59, fsEnd); + map.GetRangeAt(1, fsStart, fsEnd); + EXPECT_EQ(63, fsStart); + EXPECT_EQ(85, fsEnd); + map.GetRangeAt(2, fsStart, fsEnd); + EXPECT_EQ(87, fsStart); + EXPECT_EQ(92, fsEnd); + + EXPECT_EQ(false, map.OverlapsRange(44, 44)); + EXPECT_EQ(false, map.OverlapsRange(60, 60)); + EXPECT_EQ(true, map.OverlapsRange(45, 45)); + EXPECT_EQ(true, map.OverlapsRange(59, 59)); + + EXPECT_EQ(false, map.OverlapsRange(62, 62)); + EXPECT_EQ(false, map.OverlapsRange(86, 86)); + EXPECT_EQ(true, map.OverlapsRange(63, 63)); + EXPECT_EQ(true, map.OverlapsRange(85, 85)); + + EXPECT_EQ(false, map.OverlapsRange(86, 86)); + EXPECT_EQ(false, map.OverlapsRange(93, 93)); + EXPECT_EQ(true, map.OverlapsRange(87, 87)); + EXPECT_EQ(true, map.OverlapsRange(92, 92)); +} + +TEST(TestsTSparseRangeMap, MultipleRelatedRanges) +{ + TSparseRangeMap map; + map.Insert(45, 59); + map.Insert(60, 85); + map.Insert(36, 50); + + file_size_t fsStart = 0; + file_size_t fsEnd = 0; + + EXPECT_EQ(1, map.GetRangeCount()); + map.GetRangeAt(0, fsStart, fsEnd); + EXPECT_EQ(36, fsStart); + EXPECT_EQ(85, fsEnd); + + EXPECT_EQ(false, map.OverlapsRange(35, 35)); + EXPECT_EQ(false, map.OverlapsRange(86, 86)); + EXPECT_EQ(true, map.OverlapsRange(36, 36)); + EXPECT_EQ(true, map.OverlapsRange(85, 85)); +} Index: src/libchcore/Tests/TestsTSpeedTracker.cpp =================================================================== diff -u -r9b8cccbee0fcfeca28a112cc0253a7641f73f74f -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTSpeedTracker.cpp (.../TestsTSpeedTracker.cpp) (revision 9b8cccbee0fcfeca28a112cc0253a7641f73f74f) +++ src/libchcore/Tests/TestsTSpeedTracker.cpp (.../TestsTSpeedTracker.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,227 +1,227 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TSpeedTracker.h" -#include "../TCoreException.h" - -using namespace chcore; - -TEST(TSpeedTrackerTests, FirstSample_DoesNotChangeSpeed) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(100, 0); // 100 bytes at timestamp 0 - EXPECT_DOUBLE_EQ(0.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, SingleCorrectSample_ExactSingleSampleBoundary) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); - tTracker.AddSample(8000, 100); // 100 bytes at timestamp 100 - - // should be a single sample of 80k/s (due to the normalization) - // with all other samples equal to 0 giving finally 8000/s; - // (or from a different perspective - we processes 8000 items in the entire - // second that we track) - EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, SingleCorrectSample_NotAtSampleBoundary) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); - tTracker.AddSample(8000, 333); // 100 bytes at timestamp 333 - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, ClearContents) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); - tTracker.AddSample(8000, 100); // 100 bytes at timestamp 333 - - tTracker.Clear(); - - EXPECT_DOUBLE_EQ(0.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleAlignedSamples_SampleRollOver) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 100); - tTracker.AddSample(4000, 500); - tTracker.AddSample(5000, 1500); // one second sample; should overwrite entire sample cache - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleUnAlignedSamplesWithNoPartialSamples_SampleRollOver) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 110); - tTracker.AddSample(4000, 530); - tTracker.AddSample(5000, 1530); // one second sample; should overwrite entire sample cache - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleUnAlignedSamplesWithPartialSamples_SampleRollOver) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 110); - tTracker.AddSample(4000, 140); // a partial sample (30ms) - tTracker.AddSample(5000, 1140); // one second sample; should overwrite entire sample cache - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleSamplesRecedingInTime_ThrowsException) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 110); - EXPECT_THROW(tTracker.AddSample(4000, 40), TCoreException); -} - -TEST(TSpeedTrackerTests, MultipleSamplesCornerCase_VeryLargeInterval) -{ - TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples - tTracker.AddSample(0, 0); // start - // interval exceeds 32bit by a lot (was causing problems on 32-bit windows) - EXPECT_NO_THROW(tTracker.AddSample(40000, 18446744073709551546)); -} - -TEST(TSpeedTrackerTests, SingleSampleWithEqualTrackTimeAndSampleTime) -{ - TSpeedTracker tTracker(1000, 1000); // track last second with 1 second samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 1000); - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleSamplesWithEqualTrackTimeAndSampleTime) -{ - TSpeedTracker tTracker(1000, 1000); // track last second with 1 second samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 1000); - tTracker.AddSample(1000, 1500); - tTracker.AddSample(30000, 1800); - - // processed 8000 items in entire second (as there were no other samples) - EXPECT_DOUBLE_EQ(32600, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleSamplesWithBigTrackTime) -{ - TSpeedTracker tTracker(5000, 1000); // track last 5 seconds with 1 second samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 900); - tTracker.AddSample(1000, 1700); // 800 - tTracker.AddSample(30000, 2600); // 900 - - // processed 39000 items in last 5s, so speed is 7800 - EXPECT_DOUBLE_EQ(7800, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleSamplesWithBigTrackTimeAndSampleTime) -{ - TSpeedTracker tTracker(5000, 5000); // track last 5 seconds with 1 second samples - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 900); - tTracker.AddSample(1000, 1700); // 800 - tTracker.AddSample(30000, 2600); // 900 - - // processed 39000 items in last 5s, so speed is 7800 - EXPECT_DOUBLE_EQ(7800, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleSamplesWithTrackTimeAndSampleTimeDoesntMatch) -{ - TSpeedTracker tTracker(1000, 300); // there should be 3 samples inside - tTracker.AddSample(0, 0); // start - tTracker.AddSample(8000, 400); - tTracker.AddSample(1000, 800); - tTracker.AddSample(27000, 900); - - // processed 39000 items in last 5s, so speed is 7800 - EXPECT_DOUBLE_EQ(40000, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, ConstructionWithBadParams) -{ - // zero length sample is not allowed - EXPECT_THROW(TSpeedTracker tTracker(5000, 0), TCoreException); - // tracking time less than sample time is not allowed - EXPECT_THROW(TSpeedTracker tTracker(0, 1000), TCoreException); -} - -TEST(TSpeedTrackerTests, MultipleVeryShortSamplesWithZeroIntervalData_CornerCase) -{ - TSpeedTracker tTracker(1000, 100); - tTracker.AddSample(0, 0); // start - tTracker.AddSample(80, 10); - tTracker.AddSample(120, 10); - tTracker.AddSample(10, 10); - tTracker.AddSample(50, 10); - tTracker.AddSample(0, 10); - tTracker.AddSample(0, 10); - tTracker.AddSample(10, 20); - tTracker.AddSample(10, 20); - tTracker.AddSample(10, 20); - tTracker.AddSample(0, 20); - tTracker.AddSample(10, 30); - tTracker.AddSample(10, 30); - tTracker.AddSample(0, 30); - tTracker.AddSample(10, 40); - tTracker.AddSample(20, 40); // <-- this sample might be skipped when calculating speed - tTracker.AddSample(0, 40); - tTracker.AddSample(0, 40); - - // 340 in 1000ms = 340 items/s - // however 320 is reported, because the sample (marked above) is not counted - // in the speed calculation (has the same timestamp as previous sample) - // and this is the last timestamp used in the sample list. - - EXPECT_DOUBLE_EQ(320, tTracker.GetSpeed()); -} - -TEST(TSpeedTrackerTests, MultipleVeryShortSamplesWithZeroIntervalData) -{ - TSpeedTracker tTracker(1000, 100); - tTracker.AddSample(0, 0); // start - tTracker.AddSample(80, 10); - tTracker.AddSample(120, 10); - tTracker.AddSample(10, 10); - tTracker.AddSample(50, 10); - tTracker.AddSample(0, 10); - tTracker.AddSample(0, 10); - tTracker.AddSample(10, 20); - tTracker.AddSample(10, 20); - tTracker.AddSample(10, 20); - tTracker.AddSample(0, 20); - tTracker.AddSample(10, 30); - tTracker.AddSample(10, 30); - tTracker.AddSample(0, 30); - tTracker.AddSample(10, 40); - tTracker.AddSample(20, 40); - tTracker.AddSample(0, 40); - tTracker.AddSample(0, 40); - tTracker.AddSample(0, 50); - - // 340 in 1000ms = 340 items/s - // this case is similar to MultipleVeryShortSamplesWithZeroIntervalData_CornerCase - // but here we have additional empty sample added at the end with newer timestamp - // that should trigger inclusion of the previous same-timestamp samples - - EXPECT_DOUBLE_EQ(340, tTracker.GetSpeed()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TSpeedTracker.h" +#include "../TCoreException.h" + +using namespace chcore; + +TEST(TSpeedTrackerTests, FirstSample_DoesNotChangeSpeed) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(100, 0); // 100 bytes at timestamp 0 + EXPECT_DOUBLE_EQ(0.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, SingleCorrectSample_ExactSingleSampleBoundary) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); + tTracker.AddSample(8000, 100); // 100 bytes at timestamp 100 + + // should be a single sample of 80k/s (due to the normalization) + // with all other samples equal to 0 giving finally 8000/s; + // (or from a different perspective - we processes 8000 items in the entire + // second that we track) + EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, SingleCorrectSample_NotAtSampleBoundary) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); + tTracker.AddSample(8000, 333); // 100 bytes at timestamp 333 + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, ClearContents) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); + tTracker.AddSample(8000, 100); // 100 bytes at timestamp 333 + + tTracker.Clear(); + + EXPECT_DOUBLE_EQ(0.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleAlignedSamples_SampleRollOver) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 100); + tTracker.AddSample(4000, 500); + tTracker.AddSample(5000, 1500); // one second sample; should overwrite entire sample cache + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleUnAlignedSamplesWithNoPartialSamples_SampleRollOver) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 110); + tTracker.AddSample(4000, 530); + tTracker.AddSample(5000, 1530); // one second sample; should overwrite entire sample cache + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleUnAlignedSamplesWithPartialSamples_SampleRollOver) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 110); + tTracker.AddSample(4000, 140); // a partial sample (30ms) + tTracker.AddSample(5000, 1140); // one second sample; should overwrite entire sample cache + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(5000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleSamplesRecedingInTime_ThrowsException) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 110); + EXPECT_THROW(tTracker.AddSample(4000, 40), TCoreException); +} + +TEST(TSpeedTrackerTests, MultipleSamplesCornerCase_VeryLargeInterval) +{ + TSpeedTracker tTracker(1000, 100); // track last second with 100ms samples + tTracker.AddSample(0, 0); // start + // interval exceeds 32bit by a lot (was causing problems on 32-bit windows) + EXPECT_NO_THROW(tTracker.AddSample(40000, 18446744073709551546)); +} + +TEST(TSpeedTrackerTests, SingleSampleWithEqualTrackTimeAndSampleTime) +{ + TSpeedTracker tTracker(1000, 1000); // track last second with 1 second samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 1000); + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(8000.0, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleSamplesWithEqualTrackTimeAndSampleTime) +{ + TSpeedTracker tTracker(1000, 1000); // track last second with 1 second samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 1000); + tTracker.AddSample(1000, 1500); + tTracker.AddSample(30000, 1800); + + // processed 8000 items in entire second (as there were no other samples) + EXPECT_DOUBLE_EQ(32600, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleSamplesWithBigTrackTime) +{ + TSpeedTracker tTracker(5000, 1000); // track last 5 seconds with 1 second samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 900); + tTracker.AddSample(1000, 1700); // 800 + tTracker.AddSample(30000, 2600); // 900 + + // processed 39000 items in last 5s, so speed is 7800 + EXPECT_DOUBLE_EQ(7800, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleSamplesWithBigTrackTimeAndSampleTime) +{ + TSpeedTracker tTracker(5000, 5000); // track last 5 seconds with 1 second samples + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 900); + tTracker.AddSample(1000, 1700); // 800 + tTracker.AddSample(30000, 2600); // 900 + + // processed 39000 items in last 5s, so speed is 7800 + EXPECT_DOUBLE_EQ(7800, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleSamplesWithTrackTimeAndSampleTimeDoesntMatch) +{ + TSpeedTracker tTracker(1000, 300); // there should be 3 samples inside + tTracker.AddSample(0, 0); // start + tTracker.AddSample(8000, 400); + tTracker.AddSample(1000, 800); + tTracker.AddSample(27000, 900); + + // processed 39000 items in last 5s, so speed is 7800 + EXPECT_DOUBLE_EQ(40000, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, ConstructionWithBadParams) +{ + // zero length sample is not allowed + EXPECT_THROW(TSpeedTracker tTracker(5000, 0), TCoreException); + // tracking time less than sample time is not allowed + EXPECT_THROW(TSpeedTracker tTracker(0, 1000), TCoreException); +} + +TEST(TSpeedTrackerTests, MultipleVeryShortSamplesWithZeroIntervalData_CornerCase) +{ + TSpeedTracker tTracker(1000, 100); + tTracker.AddSample(0, 0); // start + tTracker.AddSample(80, 10); + tTracker.AddSample(120, 10); + tTracker.AddSample(10, 10); + tTracker.AddSample(50, 10); + tTracker.AddSample(0, 10); + tTracker.AddSample(0, 10); + tTracker.AddSample(10, 20); + tTracker.AddSample(10, 20); + tTracker.AddSample(10, 20); + tTracker.AddSample(0, 20); + tTracker.AddSample(10, 30); + tTracker.AddSample(10, 30); + tTracker.AddSample(0, 30); + tTracker.AddSample(10, 40); + tTracker.AddSample(20, 40); // <-- this sample might be skipped when calculating speed + tTracker.AddSample(0, 40); + tTracker.AddSample(0, 40); + + // 340 in 1000ms = 340 items/s + // however 320 is reported, because the sample (marked above) is not counted + // in the speed calculation (has the same timestamp as previous sample) + // and this is the last timestamp used in the sample list. + + EXPECT_DOUBLE_EQ(320, tTracker.GetSpeed()); +} + +TEST(TSpeedTrackerTests, MultipleVeryShortSamplesWithZeroIntervalData) +{ + TSpeedTracker tTracker(1000, 100); + tTracker.AddSample(0, 0); // start + tTracker.AddSample(80, 10); + tTracker.AddSample(120, 10); + tTracker.AddSample(10, 10); + tTracker.AddSample(50, 10); + tTracker.AddSample(0, 10); + tTracker.AddSample(0, 10); + tTracker.AddSample(10, 20); + tTracker.AddSample(10, 20); + tTracker.AddSample(10, 20); + tTracker.AddSample(0, 20); + tTracker.AddSample(10, 30); + tTracker.AddSample(10, 30); + tTracker.AddSample(0, 30); + tTracker.AddSample(10, 40); + tTracker.AddSample(20, 40); + tTracker.AddSample(0, 40); + tTracker.AddSample(0, 40); + tTracker.AddSample(0, 50); + + // 340 in 1000ms = 340 items/s + // this case is similar to MultipleVeryShortSamplesWithZeroIntervalData_CornerCase + // but here we have additional empty sample added at the end with newer timestamp + // that should trigger inclusion of the previous same-timestamp samples + + EXPECT_DOUBLE_EQ(340, tTracker.GetSpeed()); +} Index: src/libchcore/Tests/TestsTString.cpp =================================================================== diff -u -r8068e0c351055554340ac9755d1bc846893bf2b8 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTString.cpp (.../TestsTString.cpp) (revision 8068e0c351055554340ac9755d1bc846893bf2b8) +++ src/libchcore/Tests/TestsTString.cpp (.../TestsTString.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,654 +1,654 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TString.h" -#include "../TStringException.h" -#include "../TStringArray.h" -#include "../TCoreException.h" - -using namespace chcore; - -TEST(TStringTests, DefaultConstructor_CheckEmptyString) -{ - TString strEmpty; - EXPECT_EQ(strEmpty.IsEmpty(), true); -} - -TEST(TStringTests, WcharConstructor_CompareContent) -{ - TString strValue(L"Some test string"); - EXPECT_EQ(strValue, L"Some test string"); -} - -TEST(TStringTests, WcharConstructorWithNullValue_CompareContent) -{ - TString strValue(nullptr); - EXPECT_EQ(strValue, L""); -} - -TEST(TStringTests, WcharRangeConstructor_CompareContent) -{ - const wchar_t* pszText = L"Some test string"; - TString strValue(pszText, pszText + 5); - EXPECT_EQ(strValue, L"Some "); -} - -TEST(TStringTests, WcharRangeConstructor_WithUnsupportedNullValues) -{ - const wchar_t* pszText = L"Some test string"; - EXPECT_THROW(TString strValue(pszText, (const wchar_t*)nullptr), TStringException); - EXPECT_THROW(TString strValue((const wchar_t*)nullptr, pszText), TStringException); -} - -TEST(TStringTests, WcharRangeConstructor_WithSupportedNullValues_CompareContent) -{ - TString strValue((const wchar_t*)nullptr, (const wchar_t*)nullptr); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, WcharRangeConstructor_WithTooLongString) -{ - const wchar_t* pszText = L"Some test string"; - EXPECT_THROW(TString strValue(pszText, pszText + 5, 4), TStringException); -} - -TEST(TStringTests, WcharRangeConstructorWithMaxStringLen_CompareContent) -{ - const wchar_t* pszText = L"Some test string"; - TString strValue(pszText, pszText + 5, 5); - EXPECT_EQ(strValue, _T("Some ")); -} - -TEST(TStringTests, Construct_FromWchar_SpecificLen) -{ - const wchar_t* pszText = L"Some test string\0XXXXXXXXXXXX"; - TString strValue(pszText, 5); - EXPECT_EQ(strValue, _T("Some ")); -} - -TEST(TStringTests, Construct_FromWchar_LenTooLong) -{ - const wchar_t* pszText = L"Some test string\0XXXXXXXXXXXX"; - TString strValue(pszText, 5000); - EXPECT_EQ(strValue, _T("Some test string")); -} - -TEST(TStringTests, AssignmentOperator_WithNormalValue) -{ - TString strValue; - strValue = _T("Some sample string"); - EXPECT_EQ(strValue, _T("Some sample string")); -} - -TEST(TStringTests, AssignmentOperator_WithNullValue) -{ - TString strValue; - strValue = nullptr; - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, AssignmentOperator_WithTString) -{ - TString strValue(_T("Some initial string")); - strValue = TString(_T("Overwriting string")); - EXPECT_EQ(strValue, _T("Overwriting string")); -} - -TEST(TStringTests, AssignmentOperator_WithEmptyTString) -{ - TString strValue(_T("Some initial string")); - strValue = TString(); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, OperatorAdd_WithPtrToString) -{ - TString strValue = TString(_T("Text: ")) + _T("Some test string"); - EXPECT_EQ(strValue, _T("Text: Some test string")); -} - -TEST(TStringTests, OperatorAdd_WithNullPtrToString) -{ - TString strValue = TString(_T("Text: ")) + (const wchar_t*)nullptr; - EXPECT_EQ(strValue, _T("Text: ")); -} - -TEST(TStringTests, OperatorAdd_EmptyWithEmptyPtrToString) -{ - TString strValue = TString() + _T(""); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, OperatorAdd_EmptyWithNullPtrToString) -{ - TString strValue = TString() + (const wchar_t*)nullptr; - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, OperatorAdd_WithTString) -{ - TString strValue = TString(_T("Text: ")) + TString(_T("Some test string")); - EXPECT_EQ(strValue, _T("Text: Some test string")); -} - -TEST(TStringTests, OperatorInplaceAdd_WithPtrToString) -{ - TString strValue(_T("Text: ")); - strValue += _T("Some test string"); - EXPECT_EQ(strValue, _T("Text: Some test string")); -} - -TEST(TStringTests, OperatorInplaceAdd_WithNullPtrToString) -{ - TString strValue(_T("Text: ")); - strValue += (const wchar_t*)nullptr; - EXPECT_EQ(strValue, _T("Text: ")); -} - -TEST(TStringTests, OperatorInplaceAdd_EmptyWithEmptyPtrToString) -{ - TString strValue; - strValue += _T(""); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, OperatorInplaceAdd_EmptyWithNullPtrToString) -{ - TString strValue; - strValue += (const wchar_t*)nullptr; - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, OperatorInplaceAdd_WithTString) -{ - TString strValue(_T("Text: ")); - strValue += TString(_T("Some test string")); - EXPECT_EQ(strValue, _T("Text: Some test string")); -} - -// comparisons -TEST(PtrToStringTests, OperatorLT_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue < _T("The other string")); -} - -TEST(PtrToStringTests, OperatorLTE_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue <= _T("Some string2")); - EXPECT_TRUE(strValue <= _T("Some string")); -} - -TEST(PtrToStringTests, OperatorEQ_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue == _T("Some string")); -} - -TEST(PtrToStringTests, OperatorGT_WithPtrToString) -{ - TString strValue(_T("The string")); - EXPECT_TRUE(strValue > _T("Some other string")); -} - -TEST(PtrToStringTests, OperatorGTE_WithPtrToString) -{ - TString strValue(_T("The string")); - EXPECT_TRUE(strValue >= _T("The string")); - EXPECT_TRUE(strValue >= _T("The string")); -} - -// comparisons with TStrings -TEST(TStringTests, OperatorLT_WithTString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue < TString(_T("The other string"))); -} - -TEST(TStringTests, OperatorLTE_WithTString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue <= TString(_T("Some string2"))); - EXPECT_TRUE(strValue <= TString(_T("Some string"))); -} - -TEST(TStringTests, OperatorEQ_WithTString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue == TString(_T("Some string"))); -} - -TEST(TStringTests, OperatorGT_WithTString) -{ - TString strValue(_T("The string")); - EXPECT_TRUE(strValue > TString(_T("Some other string"))); -} - -TEST(TStringTests, OperatorGTE_WithTString) -{ - TString strValue(_T("The string")); - EXPECT_TRUE(strValue >= TString(_T("The string"))); - EXPECT_TRUE(strValue >= TString(_T("The string"))); -} - -// cast -TEST(TStringTests, CastToPtrWcharT) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, CastEmptyToPtrWcharT) -{ - TString strValue; - EXPECT_EQ(strValue, _T("")); -} - -// append -TEST(TStringTests, AppendString_WithPtrToString) -{ - TString strValue(_T("Some string")); - strValue.Append(_T("... appended.")); - EXPECT_EQ(strValue, _T("Some string... appended.")); -} - -TEST(TStringTests, AppendString_WithNullPtrToString) -{ - TString strValue(_T("Some string")); - strValue.Append((const wchar_t*)nullptr); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, AppendString_WithTString) -{ - TString strValue(_T("Some string")); - strValue.Append(TString(_T("... appended."))); - EXPECT_EQ(strValue, _T("Some string... appended.")); -} - -TEST(TStringTests, AppendString_WithReallocate) -{ - TString strValue(_T("Some string with up to 64 characters - 123456789012345678901")); - strValue.Append(_T("... appended.")); - EXPECT_EQ(strValue, _T("Some string with up to 64 characters - 123456789012345678901... appended.")); -} - -// left, right, mid -TEST(TStringTests, Left) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.Left(3), _T("Som")); - EXPECT_EQ(strValue.Left(0), _T("")); - EXPECT_EQ(strValue.Left(100), _T("Some string")); -} - -TEST(TStringTests, Right) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.Right(3), _T("ing")); - EXPECT_EQ(strValue.Right(0), _T("")); - EXPECT_EQ(strValue.Right(100), _T("Some string")); -} - -TEST(TStringTests, Mid) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.Mid(3), _T("e string")); - EXPECT_EQ(strValue.Mid(3, 2), _T("e ")); - EXPECT_EQ(strValue.Mid(100, 50), _T("")); -} - -TEST(TStringTests, MidRange) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.MidRange(3, 4), _T("e")); - EXPECT_EQ(strValue.MidRange(3, 5), _T("e ")); - EXPECT_EQ(strValue.MidRange(3, 50), _T("e string")); - - EXPECT_EQ(strValue.MidRange(3, 2), _T("")); - EXPECT_EQ(strValue.MidRange(50, 55), _T("")); - EXPECT_EQ(strValue.MidRange(50, 0), _T("")); -} - -// left self, right self, mid self -TEST(TStringTests, LeftSelf_NormalCase) -{ - TString strValue(_T("Some string")); - strValue.LeftSelf(3); - EXPECT_EQ(strValue, _T("Som")); -} - -TEST(TStringTests, LeftSelf_ZeroLength) -{ - TString strValue(_T("Some string")); - strValue.LeftSelf(0); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, LeftSelf_LongerThanInput) -{ - TString strValue(_T("Some string")); - strValue.LeftSelf(100); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, RightSelf_NormalCase) -{ - TString strValue(_T("Some string")); - strValue.RightSelf(3); - EXPECT_EQ(strValue, _T("ing")); -} - -TEST(TStringTests, RightSelf_ZeroLength) -{ - TString strValue(_T("Some string")); - strValue.RightSelf(0); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, RightSelf_LongerThanInput) -{ - TString strValue(_T("Some string")); - strValue.RightSelf(100); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, MidSelf_NormalCase) -{ - TString strValue(_T("Some string")); - strValue.MidSelf(3); - EXPECT_EQ(strValue, _T("e string")); -} - -TEST(TStringTests, MidSelf_ZeroLength) -{ - TString strValue(_T("Some string")); - strValue.MidSelf(3, 2); - EXPECT_EQ(strValue, _T("e ")); -} - -TEST(TStringTests, MidSelf_LongerThanInput) -{ - TString strValue(_T("Some string")); - strValue.MidSelf(100, 50); - EXPECT_EQ(strValue, _T("")); -} - -// delete -TEST(TStringTests, Delete_Normal) -{ - TString strValue(_T("Some string")); - strValue.Delete(1, 2); - EXPECT_EQ(strValue, _T("Se string")); -} - -TEST(TStringTests, Delete_TooMuch) -{ - TString strValue(_T("Some string")); - strValue.Delete(1, 200); - EXPECT_EQ(strValue, _T("S")); -} - -TEST(TStringTests, Delete_OutOfRange) -{ - TString strValue(_T("Some string")); - strValue.Delete(50, 3); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, Delete_ZeroLength) -{ - TString strValue(_T("Some string")); - strValue.Delete(1, 0); - EXPECT_EQ(strValue, _T("Some string")); -} - -TEST(TStringTests, Delete_OnEmptyString) -{ - TString strValue; - strValue.Delete(1, 0); - EXPECT_EQ(strValue, _T("")); -} - -// split -TEST(TStringTests, Split_NormalStringSingleSeparator) -{ - TString strData(_T("A;B;c;d;e;%$;;;")); - TStringArray arrSplitted; - strData.Split(_T(";"), arrSplitted); - EXPECT_EQ(arrSplitted.GetAt(0), _T("A")); - EXPECT_EQ(arrSplitted.GetAt(1), _T("B")); - EXPECT_EQ(arrSplitted.GetAt(2), _T("c")); - EXPECT_EQ(arrSplitted.GetAt(3), _T("d")); - EXPECT_EQ(arrSplitted.GetAt(4), _T("e")); - EXPECT_EQ(arrSplitted.GetAt(5), _T("%$")); - EXPECT_EQ(arrSplitted.GetAt(6), _T("")); - EXPECT_EQ(arrSplitted.GetAt(7), _T("")); - EXPECT_EQ(arrSplitted.GetAt(8), _T("")); - EXPECT_THROW(arrSplitted.GetAt(9), TCoreException); -} - -TEST(TStringTests, Split_NormalStringMultipleSeparators) -{ - TString strData(_T("A;B;c:d-e;%$;^;")); - TStringArray arrSplitted; - strData.Split(_T(";:-^"), arrSplitted); - EXPECT_EQ(arrSplitted.GetAt(0), _T("A")); - EXPECT_EQ(arrSplitted.GetAt(1), _T("B")); - EXPECT_EQ(arrSplitted.GetAt(2), _T("c")); - EXPECT_EQ(arrSplitted.GetAt(3), _T("d")); - EXPECT_EQ(arrSplitted.GetAt(4), _T("e")); - EXPECT_EQ(arrSplitted.GetAt(5), _T("%$")); - EXPECT_EQ(arrSplitted.GetAt(6), _T("")); - EXPECT_EQ(arrSplitted.GetAt(7), _T("")); - EXPECT_EQ(arrSplitted.GetAt(8), _T("")); - EXPECT_THROW(arrSplitted.GetAt(9), TCoreException); -} - -TEST(TStringTests, CompareCaseSensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_LT(strValue.Compare(_T("The string")), 0); - EXPECT_GT(strValue.Compare(_T("A string")), 0); - EXPECT_EQ(strValue.Compare(_T("Some string")), 0); -} - -TEST(TStringTests, CompareCaseInsensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_LT(strValue.CompareNoCase(_T("the strIng")), 0); - EXPECT_GT(strValue.CompareNoCase(_T("a sTring")), 0); - EXPECT_EQ(strValue.CompareNoCase(_T("soMe String")), 0); -} - - -TEST(TStringTests, CompareCaseSensitive_WithTString) -{ - TString strValue(_T("Some string")); - EXPECT_LT(strValue.Compare(TString(_T("The string"))), 0); - EXPECT_GT(strValue.Compare(TString(_T("A string"))), 0); - EXPECT_EQ(strValue.Compare(TString(_T("Some string"))), 0); -} - -TEST(TStringTests, CompareCaseInsensitive_WithTString) -{ - TString strValue(_T("Some string")); - EXPECT_LT(strValue.CompareNoCase(TString(_T("the strIng"))), 0); - EXPECT_GT(strValue.CompareNoCase(TString(_T("a sTring"))), 0); - EXPECT_EQ(strValue.CompareNoCase(TString(_T("soMe String"))), 0); -} - -// starts with -TEST(TStringTests, StartsWithCaseSensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue.StartsWith(_T("Some"))); - EXPECT_FALSE(strValue.StartsWith(_T("some"))); -} - -TEST(TStringTests, StartsWithCaseInsensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue.StartsWithNoCase(_T("Some"))); - EXPECT_TRUE(strValue.StartsWithNoCase(_T("some"))); -} - -// ends with -TEST(TStringTests, EndsWithCaseSensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue.EndsWith(_T("string"))); - EXPECT_FALSE(strValue.EndsWith(_T("String"))); -} - -TEST(TStringTests, EndsWithCaseInsensitive_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_TRUE(strValue.EndsWithNoCase(_T("string"))); - EXPECT_TRUE(strValue.EndsWithNoCase(_T("String"))); -} - -// find first/last of -TEST(TStringTests, FindFirstOf_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.FindFirstOf(_T("er"), 3), 3); - EXPECT_EQ(strValue.FindFirstOf(_T("er"), 4), 7); - EXPECT_EQ(strValue.FindFirstOf(_T(""), 0), TString::npos); - EXPECT_EQ(strValue.FindFirstOf(nullptr, 0), TString::npos); -} - -TEST(TStringTests, FindLastOf_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.FindLastOf(_T("er")), 7); - EXPECT_EQ(strValue.FindLastOf(_T("")), TString::npos); - EXPECT_EQ(strValue.FindLastOf(nullptr), TString::npos); -} - -// find and replace -TEST(TStringTests, Find_WithPtrToString) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.Find(_T("tri"), 6), 6); - EXPECT_EQ(strValue.Find(_T("tri"), 7), TString::npos); - EXPECT_EQ(strValue.Find(_T(""), 0), TString::npos); - EXPECT_EQ(strValue.Find(nullptr, 0), TString::npos); -} - -TEST(TStringTests, Find_SearchStringLongerThanThis) -{ - TString strValue(_T("Some string")); - EXPECT_EQ(strValue.Find(_T("Some longer string"), 0), TString::npos); -} - -TEST(TStringTests, Replace_WithPtrToString) -{ - TString strValue(_T("Some string")); - strValue.Replace(_T("tri"), _T("o")); - EXPECT_EQ(strValue, _T("Some song")); -} - -TEST(TStringTests, Replace_EmptyStringWithPtrToString) -{ - TString strValue; - strValue.Replace(_T(""), _T("o")); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, Replace_EmptyStringWithNullPtrToString) -{ - TString strValue; - strValue.Replace(_T(""), nullptr); - EXPECT_EQ(strValue, _T("")); -} - -// get at -TEST(TStringTests, GetAtWithBool) -{ - TString strValue(_T("Some string")); - wchar_t wch = 0; - - EXPECT_TRUE(strValue.GetAt(3, wch)); - EXPECT_EQ(wch, _T('e')); - - EXPECT_FALSE(strValue.GetAt(20, wch)); - EXPECT_EQ(wch, _T('\0')); -} - -TEST(TStringTests, GetAtWithoutBool) -{ - TString strValue(_T("Some string")); - - EXPECT_EQ(strValue.GetAt(3), _T('e')); - EXPECT_EQ(strValue.GetAt(20), _T('\0')); -} - -// get buffer, release buffer -TEST(TStringTests, GetAndReleaseBuffer) -{ - TString strValue(_T("Some string")); - wchar_t* pszBuffer = strValue.GetBuffer(5); - pszBuffer[4] = _T('\0'); - strValue.ReleaseBuffer(); - - EXPECT_EQ(strValue.GetLength(), 4); -} - -TEST(TStringTests, GetAndReleaseBufferSetLength) -{ - TString strValue(_T("Some string")); - wchar_t* pszBuffer = strValue.GetBuffer(5); - pszBuffer[4] = _T('t'); - strValue.ReleaseBufferSetLength(1); - - EXPECT_EQ(strValue.GetLength(), 1); - EXPECT_EQ(strValue, _T("S")); -} - -// clear, isempty, getlength -TEST(TStringTests, ClearAndIsEmpty) -{ - TString strValue(_T("Some string")); - - strValue.Clear(); - - EXPECT_EQ(strValue, _T("")); - EXPECT_TRUE(strValue.IsEmpty()); -} - -TEST(TStringTests, GetLength) -{ - TString strValue(_T("Some string")); - - EXPECT_EQ(strValue.GetLength(), 11); -} - -// corner cases and detected bugs -TEST(TStringTests, AssignEmptyStringToAlreadyInitializedTString) -{ - TString strValue(_T("Some string")); - - // with this we had infinite recurrence - EXPECT_NO_THROW(strValue = _T("")); - EXPECT_EQ(strValue, _T("")); -} - -TEST(TStringTests, TrimRightSelf) -{ - TString strValue(_T("Some string")); - - strValue.TrimRightSelf(L"gn"); - EXPECT_EQ(strValue, L"Some stri"); -} - -TEST(TStringTests, ReplaceAffectingOtherStringInstancesBug) -{ - TString strValue(_T("Some string")); - TString strSecond(strValue); - - strValue.Replace(_T("Some "), _T("No ")); - - EXPECT_EQ(strSecond, _T("Some string")); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TString.h" +#include "../TStringException.h" +#include "../TStringArray.h" +#include "../TCoreException.h" + +using namespace chcore; + +TEST(TStringTests, DefaultConstructor_CheckEmptyString) +{ + TString strEmpty; + EXPECT_EQ(strEmpty.IsEmpty(), true); +} + +TEST(TStringTests, WcharConstructor_CompareContent) +{ + TString strValue(L"Some test string"); + EXPECT_EQ(strValue, L"Some test string"); +} + +TEST(TStringTests, WcharConstructorWithNullValue_CompareContent) +{ + TString strValue(nullptr); + EXPECT_EQ(strValue, L""); +} + +TEST(TStringTests, WcharRangeConstructor_CompareContent) +{ + const wchar_t* pszText = L"Some test string"; + TString strValue(pszText, pszText + 5); + EXPECT_EQ(strValue, L"Some "); +} + +TEST(TStringTests, WcharRangeConstructor_WithUnsupportedNullValues) +{ + const wchar_t* pszText = L"Some test string"; + EXPECT_THROW(TString strValue(pszText, (const wchar_t*)nullptr), TStringException); + EXPECT_THROW(TString strValue((const wchar_t*)nullptr, pszText), TStringException); +} + +TEST(TStringTests, WcharRangeConstructor_WithSupportedNullValues_CompareContent) +{ + TString strValue((const wchar_t*)nullptr, (const wchar_t*)nullptr); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, WcharRangeConstructor_WithTooLongString) +{ + const wchar_t* pszText = L"Some test string"; + EXPECT_THROW(TString strValue(pszText, pszText + 5, 4), TStringException); +} + +TEST(TStringTests, WcharRangeConstructorWithMaxStringLen_CompareContent) +{ + const wchar_t* pszText = L"Some test string"; + TString strValue(pszText, pszText + 5, 5); + EXPECT_EQ(strValue, _T("Some ")); +} + +TEST(TStringTests, Construct_FromWchar_SpecificLen) +{ + const wchar_t* pszText = L"Some test string\0XXXXXXXXXXXX"; + TString strValue(pszText, 5); + EXPECT_EQ(strValue, _T("Some ")); +} + +TEST(TStringTests, Construct_FromWchar_LenTooLong) +{ + const wchar_t* pszText = L"Some test string\0XXXXXXXXXXXX"; + TString strValue(pszText, 5000); + EXPECT_EQ(strValue, _T("Some test string")); +} + +TEST(TStringTests, AssignmentOperator_WithNormalValue) +{ + TString strValue; + strValue = _T("Some sample string"); + EXPECT_EQ(strValue, _T("Some sample string")); +} + +TEST(TStringTests, AssignmentOperator_WithNullValue) +{ + TString strValue; + strValue = nullptr; + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, AssignmentOperator_WithTString) +{ + TString strValue(_T("Some initial string")); + strValue = TString(_T("Overwriting string")); + EXPECT_EQ(strValue, _T("Overwriting string")); +} + +TEST(TStringTests, AssignmentOperator_WithEmptyTString) +{ + TString strValue(_T("Some initial string")); + strValue = TString(); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, OperatorAdd_WithPtrToString) +{ + TString strValue = TString(_T("Text: ")) + _T("Some test string"); + EXPECT_EQ(strValue, _T("Text: Some test string")); +} + +TEST(TStringTests, OperatorAdd_WithNullPtrToString) +{ + TString strValue = TString(_T("Text: ")) + (const wchar_t*)nullptr; + EXPECT_EQ(strValue, _T("Text: ")); +} + +TEST(TStringTests, OperatorAdd_EmptyWithEmptyPtrToString) +{ + TString strValue = TString() + _T(""); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, OperatorAdd_EmptyWithNullPtrToString) +{ + TString strValue = TString() + (const wchar_t*)nullptr; + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, OperatorAdd_WithTString) +{ + TString strValue = TString(_T("Text: ")) + TString(_T("Some test string")); + EXPECT_EQ(strValue, _T("Text: Some test string")); +} + +TEST(TStringTests, OperatorInplaceAdd_WithPtrToString) +{ + TString strValue(_T("Text: ")); + strValue += _T("Some test string"); + EXPECT_EQ(strValue, _T("Text: Some test string")); +} + +TEST(TStringTests, OperatorInplaceAdd_WithNullPtrToString) +{ + TString strValue(_T("Text: ")); + strValue += (const wchar_t*)nullptr; + EXPECT_EQ(strValue, _T("Text: ")); +} + +TEST(TStringTests, OperatorInplaceAdd_EmptyWithEmptyPtrToString) +{ + TString strValue; + strValue += _T(""); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, OperatorInplaceAdd_EmptyWithNullPtrToString) +{ + TString strValue; + strValue += (const wchar_t*)nullptr; + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, OperatorInplaceAdd_WithTString) +{ + TString strValue(_T("Text: ")); + strValue += TString(_T("Some test string")); + EXPECT_EQ(strValue, _T("Text: Some test string")); +} + +// comparisons +TEST(PtrToStringTests, OperatorLT_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue < _T("The other string")); +} + +TEST(PtrToStringTests, OperatorLTE_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue <= _T("Some string2")); + EXPECT_TRUE(strValue <= _T("Some string")); +} + +TEST(PtrToStringTests, OperatorEQ_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue == _T("Some string")); +} + +TEST(PtrToStringTests, OperatorGT_WithPtrToString) +{ + TString strValue(_T("The string")); + EXPECT_TRUE(strValue > _T("Some other string")); +} + +TEST(PtrToStringTests, OperatorGTE_WithPtrToString) +{ + TString strValue(_T("The string")); + EXPECT_TRUE(strValue >= _T("The string")); + EXPECT_TRUE(strValue >= _T("The string")); +} + +// comparisons with TStrings +TEST(TStringTests, OperatorLT_WithTString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue < TString(_T("The other string"))); +} + +TEST(TStringTests, OperatorLTE_WithTString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue <= TString(_T("Some string2"))); + EXPECT_TRUE(strValue <= TString(_T("Some string"))); +} + +TEST(TStringTests, OperatorEQ_WithTString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue == TString(_T("Some string"))); +} + +TEST(TStringTests, OperatorGT_WithTString) +{ + TString strValue(_T("The string")); + EXPECT_TRUE(strValue > TString(_T("Some other string"))); +} + +TEST(TStringTests, OperatorGTE_WithTString) +{ + TString strValue(_T("The string")); + EXPECT_TRUE(strValue >= TString(_T("The string"))); + EXPECT_TRUE(strValue >= TString(_T("The string"))); +} + +// cast +TEST(TStringTests, CastToPtrWcharT) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, CastEmptyToPtrWcharT) +{ + TString strValue; + EXPECT_EQ(strValue, _T("")); +} + +// append +TEST(TStringTests, AppendString_WithPtrToString) +{ + TString strValue(_T("Some string")); + strValue.Append(_T("... appended.")); + EXPECT_EQ(strValue, _T("Some string... appended.")); +} + +TEST(TStringTests, AppendString_WithNullPtrToString) +{ + TString strValue(_T("Some string")); + strValue.Append((const wchar_t*)nullptr); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, AppendString_WithTString) +{ + TString strValue(_T("Some string")); + strValue.Append(TString(_T("... appended."))); + EXPECT_EQ(strValue, _T("Some string... appended.")); +} + +TEST(TStringTests, AppendString_WithReallocate) +{ + TString strValue(_T("Some string with up to 64 characters - 123456789012345678901")); + strValue.Append(_T("... appended.")); + EXPECT_EQ(strValue, _T("Some string with up to 64 characters - 123456789012345678901... appended.")); +} + +// left, right, mid +TEST(TStringTests, Left) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.Left(3), _T("Som")); + EXPECT_EQ(strValue.Left(0), _T("")); + EXPECT_EQ(strValue.Left(100), _T("Some string")); +} + +TEST(TStringTests, Right) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.Right(3), _T("ing")); + EXPECT_EQ(strValue.Right(0), _T("")); + EXPECT_EQ(strValue.Right(100), _T("Some string")); +} + +TEST(TStringTests, Mid) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.Mid(3), _T("e string")); + EXPECT_EQ(strValue.Mid(3, 2), _T("e ")); + EXPECT_EQ(strValue.Mid(100, 50), _T("")); +} + +TEST(TStringTests, MidRange) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.MidRange(3, 4), _T("e")); + EXPECT_EQ(strValue.MidRange(3, 5), _T("e ")); + EXPECT_EQ(strValue.MidRange(3, 50), _T("e string")); + + EXPECT_EQ(strValue.MidRange(3, 2), _T("")); + EXPECT_EQ(strValue.MidRange(50, 55), _T("")); + EXPECT_EQ(strValue.MidRange(50, 0), _T("")); +} + +// left self, right self, mid self +TEST(TStringTests, LeftSelf_NormalCase) +{ + TString strValue(_T("Some string")); + strValue.LeftSelf(3); + EXPECT_EQ(strValue, _T("Som")); +} + +TEST(TStringTests, LeftSelf_ZeroLength) +{ + TString strValue(_T("Some string")); + strValue.LeftSelf(0); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, LeftSelf_LongerThanInput) +{ + TString strValue(_T("Some string")); + strValue.LeftSelf(100); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, RightSelf_NormalCase) +{ + TString strValue(_T("Some string")); + strValue.RightSelf(3); + EXPECT_EQ(strValue, _T("ing")); +} + +TEST(TStringTests, RightSelf_ZeroLength) +{ + TString strValue(_T("Some string")); + strValue.RightSelf(0); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, RightSelf_LongerThanInput) +{ + TString strValue(_T("Some string")); + strValue.RightSelf(100); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, MidSelf_NormalCase) +{ + TString strValue(_T("Some string")); + strValue.MidSelf(3); + EXPECT_EQ(strValue, _T("e string")); +} + +TEST(TStringTests, MidSelf_ZeroLength) +{ + TString strValue(_T("Some string")); + strValue.MidSelf(3, 2); + EXPECT_EQ(strValue, _T("e ")); +} + +TEST(TStringTests, MidSelf_LongerThanInput) +{ + TString strValue(_T("Some string")); + strValue.MidSelf(100, 50); + EXPECT_EQ(strValue, _T("")); +} + +// delete +TEST(TStringTests, Delete_Normal) +{ + TString strValue(_T("Some string")); + strValue.Delete(1, 2); + EXPECT_EQ(strValue, _T("Se string")); +} + +TEST(TStringTests, Delete_TooMuch) +{ + TString strValue(_T("Some string")); + strValue.Delete(1, 200); + EXPECT_EQ(strValue, _T("S")); +} + +TEST(TStringTests, Delete_OutOfRange) +{ + TString strValue(_T("Some string")); + strValue.Delete(50, 3); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, Delete_ZeroLength) +{ + TString strValue(_T("Some string")); + strValue.Delete(1, 0); + EXPECT_EQ(strValue, _T("Some string")); +} + +TEST(TStringTests, Delete_OnEmptyString) +{ + TString strValue; + strValue.Delete(1, 0); + EXPECT_EQ(strValue, _T("")); +} + +// split +TEST(TStringTests, Split_NormalStringSingleSeparator) +{ + TString strData(_T("A;B;c;d;e;%$;;;")); + TStringArray arrSplitted; + strData.Split(_T(";"), arrSplitted); + EXPECT_EQ(arrSplitted.GetAt(0), _T("A")); + EXPECT_EQ(arrSplitted.GetAt(1), _T("B")); + EXPECT_EQ(arrSplitted.GetAt(2), _T("c")); + EXPECT_EQ(arrSplitted.GetAt(3), _T("d")); + EXPECT_EQ(arrSplitted.GetAt(4), _T("e")); + EXPECT_EQ(arrSplitted.GetAt(5), _T("%$")); + EXPECT_EQ(arrSplitted.GetAt(6), _T("")); + EXPECT_EQ(arrSplitted.GetAt(7), _T("")); + EXPECT_EQ(arrSplitted.GetAt(8), _T("")); + EXPECT_THROW(arrSplitted.GetAt(9), TCoreException); +} + +TEST(TStringTests, Split_NormalStringMultipleSeparators) +{ + TString strData(_T("A;B;c:d-e;%$;^;")); + TStringArray arrSplitted; + strData.Split(_T(";:-^"), arrSplitted); + EXPECT_EQ(arrSplitted.GetAt(0), _T("A")); + EXPECT_EQ(arrSplitted.GetAt(1), _T("B")); + EXPECT_EQ(arrSplitted.GetAt(2), _T("c")); + EXPECT_EQ(arrSplitted.GetAt(3), _T("d")); + EXPECT_EQ(arrSplitted.GetAt(4), _T("e")); + EXPECT_EQ(arrSplitted.GetAt(5), _T("%$")); + EXPECT_EQ(arrSplitted.GetAt(6), _T("")); + EXPECT_EQ(arrSplitted.GetAt(7), _T("")); + EXPECT_EQ(arrSplitted.GetAt(8), _T("")); + EXPECT_THROW(arrSplitted.GetAt(9), TCoreException); +} + +TEST(TStringTests, CompareCaseSensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_LT(strValue.Compare(_T("The string")), 0); + EXPECT_GT(strValue.Compare(_T("A string")), 0); + EXPECT_EQ(strValue.Compare(_T("Some string")), 0); +} + +TEST(TStringTests, CompareCaseInsensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_LT(strValue.CompareNoCase(_T("the strIng")), 0); + EXPECT_GT(strValue.CompareNoCase(_T("a sTring")), 0); + EXPECT_EQ(strValue.CompareNoCase(_T("soMe String")), 0); +} + + +TEST(TStringTests, CompareCaseSensitive_WithTString) +{ + TString strValue(_T("Some string")); + EXPECT_LT(strValue.Compare(TString(_T("The string"))), 0); + EXPECT_GT(strValue.Compare(TString(_T("A string"))), 0); + EXPECT_EQ(strValue.Compare(TString(_T("Some string"))), 0); +} + +TEST(TStringTests, CompareCaseInsensitive_WithTString) +{ + TString strValue(_T("Some string")); + EXPECT_LT(strValue.CompareNoCase(TString(_T("the strIng"))), 0); + EXPECT_GT(strValue.CompareNoCase(TString(_T("a sTring"))), 0); + EXPECT_EQ(strValue.CompareNoCase(TString(_T("soMe String"))), 0); +} + +// starts with +TEST(TStringTests, StartsWithCaseSensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue.StartsWith(_T("Some"))); + EXPECT_FALSE(strValue.StartsWith(_T("some"))); +} + +TEST(TStringTests, StartsWithCaseInsensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue.StartsWithNoCase(_T("Some"))); + EXPECT_TRUE(strValue.StartsWithNoCase(_T("some"))); +} + +// ends with +TEST(TStringTests, EndsWithCaseSensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue.EndsWith(_T("string"))); + EXPECT_FALSE(strValue.EndsWith(_T("String"))); +} + +TEST(TStringTests, EndsWithCaseInsensitive_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_TRUE(strValue.EndsWithNoCase(_T("string"))); + EXPECT_TRUE(strValue.EndsWithNoCase(_T("String"))); +} + +// find first/last of +TEST(TStringTests, FindFirstOf_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.FindFirstOf(_T("er"), 3), 3); + EXPECT_EQ(strValue.FindFirstOf(_T("er"), 4), 7); + EXPECT_EQ(strValue.FindFirstOf(_T(""), 0), TString::npos); + EXPECT_EQ(strValue.FindFirstOf(nullptr, 0), TString::npos); +} + +TEST(TStringTests, FindLastOf_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.FindLastOf(_T("er")), 7); + EXPECT_EQ(strValue.FindLastOf(_T("")), TString::npos); + EXPECT_EQ(strValue.FindLastOf(nullptr), TString::npos); +} + +// find and replace +TEST(TStringTests, Find_WithPtrToString) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.Find(_T("tri"), 6), 6); + EXPECT_EQ(strValue.Find(_T("tri"), 7), TString::npos); + EXPECT_EQ(strValue.Find(_T(""), 0), TString::npos); + EXPECT_EQ(strValue.Find(nullptr, 0), TString::npos); +} + +TEST(TStringTests, Find_SearchStringLongerThanThis) +{ + TString strValue(_T("Some string")); + EXPECT_EQ(strValue.Find(_T("Some longer string"), 0), TString::npos); +} + +TEST(TStringTests, Replace_WithPtrToString) +{ + TString strValue(_T("Some string")); + strValue.Replace(_T("tri"), _T("o")); + EXPECT_EQ(strValue, _T("Some song")); +} + +TEST(TStringTests, Replace_EmptyStringWithPtrToString) +{ + TString strValue; + strValue.Replace(_T(""), _T("o")); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, Replace_EmptyStringWithNullPtrToString) +{ + TString strValue; + strValue.Replace(_T(""), nullptr); + EXPECT_EQ(strValue, _T("")); +} + +// get at +TEST(TStringTests, GetAtWithBool) +{ + TString strValue(_T("Some string")); + wchar_t wch = 0; + + EXPECT_TRUE(strValue.GetAt(3, wch)); + EXPECT_EQ(wch, _T('e')); + + EXPECT_FALSE(strValue.GetAt(20, wch)); + EXPECT_EQ(wch, _T('\0')); +} + +TEST(TStringTests, GetAtWithoutBool) +{ + TString strValue(_T("Some string")); + + EXPECT_EQ(strValue.GetAt(3), _T('e')); + EXPECT_EQ(strValue.GetAt(20), _T('\0')); +} + +// get buffer, release buffer +TEST(TStringTests, GetAndReleaseBuffer) +{ + TString strValue(_T("Some string")); + wchar_t* pszBuffer = strValue.GetBuffer(5); + pszBuffer[4] = _T('\0'); + strValue.ReleaseBuffer(); + + EXPECT_EQ(strValue.GetLength(), 4); +} + +TEST(TStringTests, GetAndReleaseBufferSetLength) +{ + TString strValue(_T("Some string")); + wchar_t* pszBuffer = strValue.GetBuffer(5); + pszBuffer[4] = _T('t'); + strValue.ReleaseBufferSetLength(1); + + EXPECT_EQ(strValue.GetLength(), 1); + EXPECT_EQ(strValue, _T("S")); +} + +// clear, isempty, getlength +TEST(TStringTests, ClearAndIsEmpty) +{ + TString strValue(_T("Some string")); + + strValue.Clear(); + + EXPECT_EQ(strValue, _T("")); + EXPECT_TRUE(strValue.IsEmpty()); +} + +TEST(TStringTests, GetLength) +{ + TString strValue(_T("Some string")); + + EXPECT_EQ(strValue.GetLength(), 11); +} + +// corner cases and detected bugs +TEST(TStringTests, AssignEmptyStringToAlreadyInitializedTString) +{ + TString strValue(_T("Some string")); + + // with this we had infinite recurrence + EXPECT_NO_THROW(strValue = _T("")); + EXPECT_EQ(strValue, _T("")); +} + +TEST(TStringTests, TrimRightSelf) +{ + TString strValue(_T("Some string")); + + strValue.TrimRightSelf(L"gn"); + EXPECT_EQ(strValue, L"Some stri"); +} + +TEST(TStringTests, ReplaceAffectingOtherStringInstancesBug) +{ + TString strValue(_T("Some string")); + TString strSecond(strValue); + + strValue.Replace(_T("Some "), _T("No ")); + + EXPECT_EQ(strSecond, _T("Some string")); +} Index: src/libchcore/Tests/TestsTStringPattern.cpp =================================================================== diff -u -rfcf6698a5e67445b1a68627fa94837b1ad97284e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTStringPattern.cpp (.../TestsTStringPattern.cpp) (revision fcf6698a5e67445b1a68627fa94837b1ad97284e) +++ src/libchcore/Tests/TestsTStringPattern.cpp (.../TestsTStringPattern.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,114 +1,114 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TStringPattern.h" - -using namespace chcore; - -TEST(TestsTStringPattern, DefaultConstruction) -{ - TStringPattern patternEmpty; - EXPECT_STREQ(L"", patternEmpty.ToString().c_str()); - EXPECT_STREQ(L"", patternEmpty.GetPattern().c_str()); - EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); -} - -TEST(TestsTStringPattern, PatternConstruction) -{ - TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); - EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); - EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); - EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); -} - -TEST(TestsTStringPattern, SetPattern) -{ - TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); - - patternEmpty.SetPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_STREQ(L"*.bat", patternEmpty.ToString().c_str()); - EXPECT_STREQ(L"*.bat", patternEmpty.GetPattern().c_str()); - EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); -} - -TEST(TestsTStringPattern, CreateFromSerializedString) -{ - TStringPattern patternEmpty = TStringPattern::CreateFromString(L"WC;*.*"); - - EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); - EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); - EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); -} - -TEST(TestsTStringPattern, FromStringString) -{ - TStringPattern patternEmpty; - patternEmpty.FromString(L"WC;*.*"); - - EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); - EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); - EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); -} - -TEST(TestsTStringPattern, Matches_Positive_StarDotBat) -{ - TStringPattern patternEmpty(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_TRUE(patternEmpty.Matches(L"autorun.bat")); -} - -TEST(TestsTStringPattern, Matches_Negative_StarDotBat) -{ - TStringPattern patternEmpty(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_FALSE(patternEmpty.Matches(L"autorun.batx")); -} - -TEST(TestsTStringPattern, Matches_Positive_StarDotStar) -{ - TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_TRUE(patternEmpty.Matches(L"autorun.bat")); -} - -TEST(TestsTStringPattern, Matches_Negative_StarDotStar) -{ - TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_FALSE(patternEmpty.Matches(L"autorun")); -} - -/////////////////////////////////////////////////////////// -// Multiple asterisks - -TEST(TestsTStringPattern, Matches_Positive_MultiStar) -{ - TStringPattern patternEmpty(L"ad*bo*", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_TRUE(patternEmpty.Matches(L"addon-boo.bat")); -} - -TEST(TestsTStringPattern, Matches_Negative_MultiStar) -{ - TStringPattern patternEmpty(L"ad*bo*", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_FALSE(patternEmpty.Matches(L"addon-doo.bat")); -} - -//////////////////////////////////////////////////////////// -// asterisks - -TEST(TestsTStringPattern, Matches_Positive_QuestionMultiPos) -{ - TStringPattern patternEmpty(L"a??b?r", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_TRUE(patternEmpty.Matches(L"arbbar")); -} - -TEST(TestsTStringPattern, Matches_Negative_QuestionMultiPos) -{ - TStringPattern patternEmpty(L"a??b?r", TStringPattern::EPatternType::eType_Wildcard); - - EXPECT_FALSE(patternEmpty.Matches(L"arbxar")); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TStringPattern.h" + +using namespace chcore; + +TEST(TestsTStringPattern, DefaultConstruction) +{ + TStringPattern patternEmpty; + EXPECT_STREQ(L"", patternEmpty.ToString().c_str()); + EXPECT_STREQ(L"", patternEmpty.GetPattern().c_str()); + EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); +} + +TEST(TestsTStringPattern, PatternConstruction) +{ + TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); + EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); + EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); + EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); +} + +TEST(TestsTStringPattern, SetPattern) +{ + TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); + + patternEmpty.SetPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_STREQ(L"*.bat", patternEmpty.ToString().c_str()); + EXPECT_STREQ(L"*.bat", patternEmpty.GetPattern().c_str()); + EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); +} + +TEST(TestsTStringPattern, CreateFromSerializedString) +{ + TStringPattern patternEmpty = TStringPattern::CreateFromString(L"WC;*.*"); + + EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); + EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); + EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); +} + +TEST(TestsTStringPattern, FromStringString) +{ + TStringPattern patternEmpty; + patternEmpty.FromString(L"WC;*.*"); + + EXPECT_STREQ(L"*.*", patternEmpty.ToString().c_str()); + EXPECT_STREQ(L"*.*", patternEmpty.GetPattern().c_str()); + EXPECT_EQ(TStringPattern::EPatternType::eType_Wildcard, patternEmpty.GetPatternType()); +} + +TEST(TestsTStringPattern, Matches_Positive_StarDotBat) +{ + TStringPattern patternEmpty(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_TRUE(patternEmpty.Matches(L"autorun.bat")); +} + +TEST(TestsTStringPattern, Matches_Negative_StarDotBat) +{ + TStringPattern patternEmpty(L"*.bat", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_FALSE(patternEmpty.Matches(L"autorun.batx")); +} + +TEST(TestsTStringPattern, Matches_Positive_StarDotStar) +{ + TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_TRUE(patternEmpty.Matches(L"autorun.bat")); +} + +TEST(TestsTStringPattern, Matches_Negative_StarDotStar) +{ + TStringPattern patternEmpty(L"*.*", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_FALSE(patternEmpty.Matches(L"autorun")); +} + +/////////////////////////////////////////////////////////// +// Multiple asterisks + +TEST(TestsTStringPattern, Matches_Positive_MultiStar) +{ + TStringPattern patternEmpty(L"ad*bo*", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_TRUE(patternEmpty.Matches(L"addon-boo.bat")); +} + +TEST(TestsTStringPattern, Matches_Negative_MultiStar) +{ + TStringPattern patternEmpty(L"ad*bo*", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_FALSE(patternEmpty.Matches(L"addon-doo.bat")); +} + +//////////////////////////////////////////////////////////// +// asterisks + +TEST(TestsTStringPattern, Matches_Positive_QuestionMultiPos) +{ + TStringPattern patternEmpty(L"a??b?r", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_TRUE(patternEmpty.Matches(L"arbbar")); +} + +TEST(TestsTStringPattern, Matches_Negative_QuestionMultiPos) +{ + TStringPattern patternEmpty(L"a??b?r", TStringPattern::EPatternType::eType_Wildcard); + + EXPECT_FALSE(patternEmpty.Matches(L"arbxar")); +} Index: src/libchcore/Tests/TestsTStringPatternArray.cpp =================================================================== diff -u -rfcf6698a5e67445b1a68627fa94837b1ad97284e -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/Tests/TestsTStringPatternArray.cpp (.../TestsTStringPatternArray.cpp) (revision fcf6698a5e67445b1a68627fa94837b1ad97284e) +++ src/libchcore/Tests/TestsTStringPatternArray.cpp (.../TestsTStringPatternArray.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,149 +1,149 @@ -#include "stdafx.h" -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "../TStringPatternArray.h" -#include "../TStringArray.h" - -using namespace chcore; - -TEST(TestsTStringPatternArray, DefaultConstruction) -{ - TStringPatternArray arrPatterns; - - EXPECT_EQ(0, arrPatterns.GetCount()); -} - -TEST(TestsTStringPatternArray, AddElements) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_EQ(2, arrPatterns.GetCount()); - EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(0).ToString().c_str()); - EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(1).ToString().c_str()); -} - -TEST(TestsTStringPatternArray, InsertAt) -{ - TStringPatternArray arrPatterns; - - arrPatterns.InsertAt(0, TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.InsertAt(0, TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_EQ(2, arrPatterns.GetCount()); - EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(1).ToString().c_str()); - EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(0).ToString().c_str()); -} - -TEST(TestsTStringPatternArray, SetAt) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - arrPatterns.SetAt(0, TStringPattern(L"*.com", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_EQ(2, arrPatterns.GetCount()); - EXPECT_STREQ(L"*.com", arrPatterns.GetAt(0).ToString().c_str()); - EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(1).ToString().c_str()); -} - -TEST(TestsTStringPatternArray, RemoveAt) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - arrPatterns.RemoveAt(0); - - EXPECT_EQ(1, arrPatterns.GetCount()); - EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(0).ToString().c_str()); -} - -TEST(TestsTStringPatternArray, Clear) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - arrPatterns.Clear(); - - EXPECT_EQ(0, arrPatterns.GetCount()); -} - -///////////////////////////////////////////////// -// matches any -TEST(TestsTStringPatternArray, MatchesAny_Positive) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_TRUE(arrPatterns.MatchesAny(L"autostart.bat")); -} - -TEST(TestsTStringPatternArray, MatchesAny_Negative) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_FALSE(arrPatterns.MatchesAny(L"autostart.com")); -} - -///////////////////////////////////////////////// -// matches all -TEST(TestsTStringPatternArray, MatchesAll_Positive) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_TRUE(arrPatterns.MatchesAll(L"autostart.bat")); -} - -TEST(TestsTStringPatternArray, MatchesAll_Negative) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); - - EXPECT_FALSE(arrPatterns.MatchesAll(L"autostart.exe")); -} - -///////////////////////////////////////////////// -// serialization -TEST(TestsTStringPatternArray, ToStringArray) -{ - TStringPatternArray arrPatterns; - - arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); - arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); - - TStringArray arrElements = arrPatterns.ToSerializedStringArray(); - EXPECT_EQ(2, arrElements.GetCount()); - EXPECT_STREQ(L"*.bat", arrElements.GetAt(0).c_str()); - EXPECT_STREQ(L"autostart.*", arrElements.GetAt(1).c_str()); -} - -TEST(TestsTStringPatternArray, FromStringArray) -{ - TStringArray arrElements; - arrElements.Add(L"*.bat"); - arrElements.Add(L"autostart.*"); - - TStringPatternArray arrPatterns; - arrPatterns.FromStringArray(arrElements); - - EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(0).ToString().c_str()); - EXPECT_STREQ(L"autostart.*", arrPatterns.GetAt(1).ToString().c_str()); -} +#include "stdafx.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "../TStringPatternArray.h" +#include "../TStringArray.h" + +using namespace chcore; + +TEST(TestsTStringPatternArray, DefaultConstruction) +{ + TStringPatternArray arrPatterns; + + EXPECT_EQ(0, arrPatterns.GetCount()); +} + +TEST(TestsTStringPatternArray, AddElements) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_EQ(2, arrPatterns.GetCount()); + EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(0).ToString().c_str()); + EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(1).ToString().c_str()); +} + +TEST(TestsTStringPatternArray, InsertAt) +{ + TStringPatternArray arrPatterns; + + arrPatterns.InsertAt(0, TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.InsertAt(0, TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_EQ(2, arrPatterns.GetCount()); + EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(1).ToString().c_str()); + EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(0).ToString().c_str()); +} + +TEST(TestsTStringPatternArray, SetAt) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + arrPatterns.SetAt(0, TStringPattern(L"*.com", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_EQ(2, arrPatterns.GetCount()); + EXPECT_STREQ(L"*.com", arrPatterns.GetAt(0).ToString().c_str()); + EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(1).ToString().c_str()); +} + +TEST(TestsTStringPatternArray, RemoveAt) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + arrPatterns.RemoveAt(0); + + EXPECT_EQ(1, arrPatterns.GetCount()); + EXPECT_STREQ(L"*.exe", arrPatterns.GetAt(0).ToString().c_str()); +} + +TEST(TestsTStringPatternArray, Clear) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + arrPatterns.Clear(); + + EXPECT_EQ(0, arrPatterns.GetCount()); +} + +///////////////////////////////////////////////// +// matches any +TEST(TestsTStringPatternArray, MatchesAny_Positive) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_TRUE(arrPatterns.MatchesAny(L"autostart.bat")); +} + +TEST(TestsTStringPatternArray, MatchesAny_Negative) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"*.exe", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_FALSE(arrPatterns.MatchesAny(L"autostart.com")); +} + +///////////////////////////////////////////////// +// matches all +TEST(TestsTStringPatternArray, MatchesAll_Positive) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_TRUE(arrPatterns.MatchesAll(L"autostart.bat")); +} + +TEST(TestsTStringPatternArray, MatchesAll_Negative) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); + + EXPECT_FALSE(arrPatterns.MatchesAll(L"autostart.exe")); +} + +///////////////////////////////////////////////// +// serialization +TEST(TestsTStringPatternArray, ToStringArray) +{ + TStringPatternArray arrPatterns; + + arrPatterns.Add(TStringPattern(L"*.bat", TStringPattern::EPatternType::eType_Wildcard)); + arrPatterns.Add(TStringPattern(L"autostart.*", TStringPattern::EPatternType::eType_Wildcard)); + + TStringArray arrElements = arrPatterns.ToSerializedStringArray(); + EXPECT_EQ(2, arrElements.GetCount()); + EXPECT_STREQ(L"*.bat", arrElements.GetAt(0).c_str()); + EXPECT_STREQ(L"autostart.*", arrElements.GetAt(1).c_str()); +} + +TEST(TestsTStringPatternArray, FromStringArray) +{ + TStringArray arrElements; + arrElements.Add(L"*.bat"); + arrElements.Add(L"autostart.*"); + + TStringPatternArray arrPatterns; + arrPatterns.FromStringArray(arrElements); + + EXPECT_STREQ(L"*.bat", arrPatterns.GetAt(0).ToString().c_str()); + EXPECT_STREQ(L"autostart.*", arrPatterns.GetAt(1).ToString().c_str()); +} Index: src/libchcore/libchcore.vc140.vcxproj =================================================================== diff -u -r3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/libchcore.vc140.vcxproj (.../libchcore.vc140.vcxproj) (revision 3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4) +++ src/libchcore/libchcore.vc140.vcxproj (.../libchcore.vc140.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,969 +1,969 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - Testing Debug - Win32 - - - Testing Debug - x64 - - - Testing Release - Win32 - - - Testing Release - x64 - - - - libchcore - {CBBF380B-7B16-4A1E-8194-758DAD7D8011} - libchcore - Win32Proj - - - - DynamicLibrary - v120_xp - Unicode - true - - - DynamicLibrary - v120_xp - Unicode - true - - - DynamicLibrary - v120_xp - Unicode - - - DynamicLibrary - v120_xp - Unicode - - - DynamicLibrary - Unicode - true - v120_xp - - - DynamicLibrary - Unicode - true - v120_xp - - - DynamicLibrary - Unicode - v120_xp - - - DynamicLibrary - Unicode - v120_xp - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.51106.1 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - NativeRecommendedRules.ruleset - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - NativeRecommendedRules.ruleset - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - MachineX86 - "$(OutDir)" - true - - - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - MachineX86 - gmock32d.lib;%(AdditionalDependencies) - "$(OutDir)" - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - X64 - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - false - ProgramDatabase - 4512;4714 - false - true - ../../ext - true - - - true - Windows - MachineX64 - "$(OutDir)" - false - - - - - X64 - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - false - ProgramDatabase - 4512;4714 - false - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - true - - - true - Windows - MachineX64 - gmock64d.lib;%(AdditionalDependencies) - "$(OutDir)" - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - true - true - MachineX86 - "$(OutDir)" - true - - - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - true - true - MachineX86 - gmock32.lib;%(AdditionalDependencies) - "$(OutDir)" - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - X64 - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ../../ext - 4512;4714 - true - - - true - Windows - true - true - MachineX64 - "$(OutDir)" - false - - - - - X64 - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - 4512;4714 - true - - - true - Windows - true - true - MachineX64 - gmock64.lib;%(AdditionalDependencies) - "$(OutDir)" - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - true - true - true - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - - - - - - - - - - - - - - - - - - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - false - - - - - false - false - - - - - false - false - - - - - false - false - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - {d41831f5-b2a5-4c92-9f15-1d9ab04722cc} - - - {df9957d4-3d95-4ac3-ad3f-dcbea058f79d} - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + Testing Debug + Win32 + + + Testing Debug + x64 + + + Testing Release + Win32 + + + Testing Release + x64 + + + + libchcore + {CBBF380B-7B16-4A1E-8194-758DAD7D8011} + libchcore + Win32Proj + + + + DynamicLibrary + v120_xp + Unicode + true + + + DynamicLibrary + v120_xp + Unicode + true + + + DynamicLibrary + v120_xp + Unicode + + + DynamicLibrary + v120_xp + Unicode + + + DynamicLibrary + Unicode + true + v120_xp + + + DynamicLibrary + Unicode + true + v120_xp + + + DynamicLibrary + Unicode + v120_xp + + + DynamicLibrary + Unicode + v120_xp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>11.0.51106.1 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + NativeRecommendedRules.ruleset + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + NativeRecommendedRules.ruleset + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + MachineX86 + "$(OutDir)" + true + + + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + MachineX86 + gmock32d.lib;%(AdditionalDependencies) + "$(OutDir)" + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + X64 + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + false + ProgramDatabase + 4512;4714 + false + true + ../../ext + true + + + true + Windows + MachineX64 + "$(OutDir)" + false + + + + + X64 + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + false + ProgramDatabase + 4512;4714 + false + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + true + + + true + Windows + MachineX64 + gmock64d.lib;%(AdditionalDependencies) + "$(OutDir)" + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + true + true + MachineX86 + "$(OutDir)" + true + + + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + true + true + MachineX86 + gmock32.lib;%(AdditionalDependencies) + "$(OutDir)" + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + X64 + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ../../ext + 4512;4714 + true + + + true + Windows + true + true + MachineX64 + "$(OutDir)" + false + + + + + X64 + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBCHCORE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + 4512;4714 + true + + + true + Windows + true + true + MachineX64 + gmock64.lib;%(AdditionalDependencies) + "$(OutDir)" + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + true + true + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + false + + + + + false + false + + + + + false + false + + + + + false + false + + + + Create + Create + Create + Create + Create + Create + Create + Create + + + + + + {d41831f5-b2a5-4c92-9f15-1d9ab04722cc} + + + {df9957d4-3d95-4ac3-ad3f-dcbea058f79d} + + + + + + + + \ No newline at end of file Index: src/libchcore/libchcore.vc140.vcxproj.filters =================================================================== diff -u -r3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/libchcore.vc140.vcxproj.filters (.../libchcore.vc140.vcxproj.filters) (revision 3d7d129eda4a42e9f9318ae6b6f3b873dc9290d4) +++ src/libchcore/libchcore.vc140.vcxproj.filters (.../libchcore.vc140.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,1028 +1,1028 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {e160d2cd-2a88-40ef-97b4-6b7d3b7ed6b1} - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - {fc917d04-8853-43b8-b72c-d3e79ede544c} - - - {291aa467-7b12-4be2-9740-45afb314fe7b} - - - {0f791663-0a08-4f3f-89b5-7b5f40a467ee} - - - {76d85b5b-fa45-4693-9701-d6b5fce941df} - - - {1fddd996-c723-4b09-9c98-868df98fe204} - - - {2a642b1a-83b2-4643-ac85-d040e8904d4d} - - - {3ce71f46-ef32-4c71-9ac0-bcb36d6b6e99} - - - {0b6550bf-a20b-4f12-9469-bd3e3bfa40fa} - - - {e6da867d-b0bd-42d5-a0c8-43542984582f} - - - {e4894f9f-1e1d-451a-9a02-60b9d682b60f} - - - {0f10fd6b-7813-419a-a276-cedaa42bc7bc} - - - {d920c603-b44c-47ce-89c3-ead84fc29116} - - - {b7eef53f-fb70-4f50-aa6d-0a699bb20f25} - - - {28670d3c-b5d8-4acb-91aa-c886efae641c} - - - {9d121063-367c-4424-8009-12b3635e0fed} - - - {30d60be9-a936-4191-a66d-64e127f3d258} - - - {49c9ae7e-1bc4-4875-8512-e92e0c00fb19} - - - {02c88ac8-15f7-4372-9f47-247ecbada7db} - - - {3de9b5f5-44fa-4e4b-9a63-f93d940d537a} - - - {a77c6575-b7b7-4683-9295-d5173da8c76b} - - - {b5e932b3-5a5a-465b-8ade-3354c81e1996} - - - {953a12ea-2aa5-4c7a-a310-a461ce8b962f} - - - {64486dcc-0c2a-468c-9498-c4ff0c2183af} - - - {076cbf8f-0110-48a9-9cbe-9929534ba1d1} - - - {70510fff-69c9-4ba7-beb1-55024077e6b5} - - - {4d6af45e-ee39-4520-830b-1eff232b8f0a} - - - {2bf8bd08-c6de-45fd-a047-8c90c07ac481} - - - {202d13d3-126b-4811-8c1c-a14b4f0476b7} - - - {301c07b0-8112-4a01-9e47-9b32f6637be8} - - - {2e089b8f-c085-4bce-a342-64c2611a717a} - - - {94659973-1dd0-4e22-83c6-2fc26d3bf56e} - - - {cc825cb7-bb97-45eb-86ed-ac031e1ca9e6} - - - {712c0e1a-c6e3-4aab-8322-a9eea42e6d81} - - - {da2a09b3-c940-46ca-8161-a9f97fddf23e} - - - {0015d34a-19cb-41da-a52d-1aedece5682c} - - - {1412ea6d-b28c-4a96-b076-3094c476ce45} - - - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\Task - - - Source Files\Task - - - Source Files\Task - - - Source Files\Task Manager - - - Source Files\Task Manager - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Library files - - - Source Files\Library files - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Feedback - - - Source Files\Feedback - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\Task - - - Source Files\Task Manager - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools\Config - - - Source Files\Tools\Config\details - - - Source Files\Tools\Config\details - - - Source Files\Tools\Config - - - Source Files\Tools\Config - - - Source Files\Tools\ModificationTrackers - - - Source Files\Tools\ModificationTrackers - - - Source Files\Serialization - - - Source Files\Task - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Feedback - - - Source Files\Stats - - - Source Files\Stats - - - Source Files\Stats - - - Source Files\Feedback - - - Source Files\Feedback - - - Source Files\Serialization\Fake - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools\DebugTrace - - - Source Files\Task Config - - - Source Files\Task Config - - - Source Files\Task Config - - - Source Files\Feedback - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Filesystems - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Filesystems - - - Source Files\Filesystems - - - Source Files\Filesystems\Local - - - Source Files\Filesystems\Local - - - Source Files\Filesystems\Local - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Filesystems\Exceptions - - - Source Files\Feedback - - - Source Files\SubTasks - - - Source Files\Task Config - - - Source Files\Library files - - - Source Files\Tools - - - Tests - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers - - - Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - - Source Files\Shared - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Tools\Queues - - - Source Files\Tools\Threading - - - Source Files\Filesystems\OverlappedIO\Data Buffer\BufferConfig - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\ThreadSupport - - - Source Files\Tools\Threading - - - Source Files\Tools\Threading - - - Source Files\Tools\Threading - - - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\Task - - - Source Files\Task - - - Source Files\Task - - - Source Files\Task Manager - - - Source Files\Task Manager - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Library files - - - Source Files\Library files - - - Source Files\Library files - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Feedback - - - Source Files\Feedback - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite\SQLite Schemas - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization\SQLite - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\Serialization - - - Source Files\SubTasks - - - Source Files\SubTasks - - - Source Files\Task Manager - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools\SQLite - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools\Config - - - Source Files\Tools\Config\details - - - Source Files\Tools\Config\details - - - Source Files\Tools\Config - - - Source Files\Tools\Config - - - Source Files\Serialization - - - Source Files\Task - - - Source Files\Tools - - - Tests - - - Tests - - - Tests - - - Tests - - - Tests - - - Tests - - - Tests - - - Tests - - - Source Files\Tools - - - Tests - - - Source Files\Tools - - - Source Files\Feedback - - - Source Files\Stats - - - Source Files\Stats - - - Source Files\Stats - - - Source Files\Feedback - - - Source Files\Serialization\Fake - - - Source Files\Tools - - - Source Files\Task Config - - - Source Files\Task Config - - - Tests - - - Tests - - - Source Files\Tools - - - Source Files\Tools - - - Tests - - - Tests - - - Tests - - - Source Files\Filesystems - - - Source Files\Filesystems - - - Source Files\Filesystems - - - Source Files\Filesystems\Local - - - Source Files\Filesystems\Local - - - Source Files\Filesystems\Local - - - Source Files\Tools - - - Tests - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Tools\Exceptions - - - Source Files\Filesystems\Exceptions - - - Source Files\Feedback - - - Source Files\SubTasks - - - Tests - - - Source Files\Task Config - - - Tests\TaskConfig - - - Source Files\Library files - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Tests\DataBuffer - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers - - - Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex - - - Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\Feedback Wrappers - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\Data Buffer\BufferConfig - - - Source Files\Filesystems\OverlappedIO\ReaderWriter - - - Source Files\Filesystems\OverlappedIO\ThreadSupport - - - Source Files\Tools\Threading - - - Source Files\Tools\Threading - - - - - Resource Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {e160d2cd-2a88-40ef-97b4-6b7d3b7ed6b1} + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + {fc917d04-8853-43b8-b72c-d3e79ede544c} + + + {291aa467-7b12-4be2-9740-45afb314fe7b} + + + {0f791663-0a08-4f3f-89b5-7b5f40a467ee} + + + {76d85b5b-fa45-4693-9701-d6b5fce941df} + + + {1fddd996-c723-4b09-9c98-868df98fe204} + + + {2a642b1a-83b2-4643-ac85-d040e8904d4d} + + + {3ce71f46-ef32-4c71-9ac0-bcb36d6b6e99} + + + {0b6550bf-a20b-4f12-9469-bd3e3bfa40fa} + + + {e6da867d-b0bd-42d5-a0c8-43542984582f} + + + {e4894f9f-1e1d-451a-9a02-60b9d682b60f} + + + {0f10fd6b-7813-419a-a276-cedaa42bc7bc} + + + {d920c603-b44c-47ce-89c3-ead84fc29116} + + + {b7eef53f-fb70-4f50-aa6d-0a699bb20f25} + + + {28670d3c-b5d8-4acb-91aa-c886efae641c} + + + {9d121063-367c-4424-8009-12b3635e0fed} + + + {30d60be9-a936-4191-a66d-64e127f3d258} + + + {49c9ae7e-1bc4-4875-8512-e92e0c00fb19} + + + {02c88ac8-15f7-4372-9f47-247ecbada7db} + + + {3de9b5f5-44fa-4e4b-9a63-f93d940d537a} + + + {a77c6575-b7b7-4683-9295-d5173da8c76b} + + + {b5e932b3-5a5a-465b-8ade-3354c81e1996} + + + {953a12ea-2aa5-4c7a-a310-a461ce8b962f} + + + {64486dcc-0c2a-468c-9498-c4ff0c2183af} + + + {076cbf8f-0110-48a9-9cbe-9929534ba1d1} + + + {70510fff-69c9-4ba7-beb1-55024077e6b5} + + + {4d6af45e-ee39-4520-830b-1eff232b8f0a} + + + {2bf8bd08-c6de-45fd-a047-8c90c07ac481} + + + {202d13d3-126b-4811-8c1c-a14b4f0476b7} + + + {301c07b0-8112-4a01-9e47-9b32f6637be8} + + + {2e089b8f-c085-4bce-a342-64c2611a717a} + + + {94659973-1dd0-4e22-83c6-2fc26d3bf56e} + + + {cc825cb7-bb97-45eb-86ed-ac031e1ca9e6} + + + {712c0e1a-c6e3-4aab-8322-a9eea42e6d81} + + + {da2a09b3-c940-46ca-8161-a9f97fddf23e} + + + {0015d34a-19cb-41da-a52d-1aedece5682c} + + + {1412ea6d-b28c-4a96-b076-3094c476ce45} + + + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\Task + + + Source Files\Task + + + Source Files\Task + + + Source Files\Task Manager + + + Source Files\Task Manager + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Library files + + + Source Files\Library files + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Feedback + + + Source Files\Feedback + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\Task + + + Source Files\Task Manager + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools\Config + + + Source Files\Tools\Config\details + + + Source Files\Tools\Config\details + + + Source Files\Tools\Config + + + Source Files\Tools\Config + + + Source Files\Tools\ModificationTrackers + + + Source Files\Tools\ModificationTrackers + + + Source Files\Serialization + + + Source Files\Task + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Feedback + + + Source Files\Stats + + + Source Files\Stats + + + Source Files\Stats + + + Source Files\Feedback + + + Source Files\Feedback + + + Source Files\Serialization\Fake + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools\DebugTrace + + + Source Files\Task Config + + + Source Files\Task Config + + + Source Files\Task Config + + + Source Files\Feedback + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Filesystems + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Filesystems + + + Source Files\Filesystems + + + Source Files\Filesystems\Local + + + Source Files\Filesystems\Local + + + Source Files\Filesystems\Local + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Filesystems\Exceptions + + + Source Files\Feedback + + + Source Files\SubTasks + + + Source Files\Task Config + + + Source Files\Library files + + + Source Files\Tools + + + Tests + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers + + + Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + + Source Files\Shared + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Tools\Queues + + + Source Files\Tools\Threading + + + Source Files\Filesystems\OverlappedIO\Data Buffer\BufferConfig + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\ThreadSupport + + + Source Files\Tools\Threading + + + Source Files\Tools\Threading + + + Source Files\Tools\Threading + + + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\Task + + + Source Files\Task + + + Source Files\Task + + + Source Files\Task Manager + + + Source Files\Task Manager + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Library files + + + Source Files\Library files + + + Source Files\Library files + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Feedback + + + Source Files\Feedback + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite\SQLite Schemas + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization\SQLite + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\Serialization + + + Source Files\SubTasks + + + Source Files\SubTasks + + + Source Files\Task Manager + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools\SQLite + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools\Config + + + Source Files\Tools\Config\details + + + Source Files\Tools\Config\details + + + Source Files\Tools\Config + + + Source Files\Tools\Config + + + Source Files\Serialization + + + Source Files\Task + + + Source Files\Tools + + + Tests + + + Tests + + + Tests + + + Tests + + + Tests + + + Tests + + + Tests + + + Tests + + + Source Files\Tools + + + Tests + + + Source Files\Tools + + + Source Files\Feedback + + + Source Files\Stats + + + Source Files\Stats + + + Source Files\Stats + + + Source Files\Feedback + + + Source Files\Serialization\Fake + + + Source Files\Tools + + + Source Files\Task Config + + + Source Files\Task Config + + + Tests + + + Tests + + + Source Files\Tools + + + Source Files\Tools + + + Tests + + + Tests + + + Tests + + + Source Files\Filesystems + + + Source Files\Filesystems + + + Source Files\Filesystems + + + Source Files\Filesystems\Local + + + Source Files\Filesystems\Local + + + Source Files\Filesystems\Local + + + Source Files\Tools + + + Tests + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Tools\Exceptions + + + Source Files\Filesystems\Exceptions + + + Source Files\Feedback + + + Source Files\SubTasks + + + Tests + + + Source Files\Task Config + + + Tests\TaskConfig + + + Source Files\Library files + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Tests\DataBuffer + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers + + + Source Files\Filesystems\OverlappedIO\Data Buffer\Buffers + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Simple + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex + + + Source Files\Filesystems\OverlappedIO\ReaderWriter\Queues\Complex + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\Feedback Wrappers + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\Data Buffer\BufferConfig + + + Source Files\Filesystems\OverlappedIO\ReaderWriter + + + Source Files\Filesystems\OverlappedIO\ThreadSupport + + + Source Files\Tools\Threading + + + Source Files\Tools\Threading + + + + + Resource Files + + \ No newline at end of file Index: src/libchcore/res/libchcore.rc2 =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libchcore/res/libchcore.rc2 (.../libchcore.rc2) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/libchcore/res/libchcore.rc2 (.../libchcore.rc2) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -// -// ch.rc2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - -#include "../common/version.h" - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x29L -#else - FILEFLAGS 0x28L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Core Copy Handler functionalities" - VALUE "CompanyName", " " - VALUE "FileDescription", "Copy Handler Core" - VALUE "FileVersion", PRODUCT_VERSION - VALUE "LegalCopyright", COPYRIGHT_INFO - VALUE "LegalTrademarks", " " - VALUE "OriginalFilename", "libchcore.dll" - VALUE "ProductName", "Copy Handler" - VALUE "ProductVersion", PRODUCT_VERSION - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -///////////////////////////////////////////////////////////////////////////// +// +// ch.rc2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + +#include "../common/version.h" + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x29L +#else + FILEFLAGS 0x28L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Core Copy Handler functionalities" + VALUE "CompanyName", " " + VALUE "FileDescription", "Copy Handler Core" + VALUE "FileVersion", PRODUCT_VERSION + VALUE "LegalCopyright", COPYRIGHT_INFO + VALUE "LegalTrademarks", " " + VALUE "OriginalFilename", "libchcore.dll" + VALUE "ProductName", "Copy Handler" + VALUE "ProductVersion", PRODUCT_VERSION + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +///////////////////////////////////////////////////////////////////////////// Index: src/libictranslate/libictranslate.def =================================================================== diff -u -rbee51aca3d5d9b67ecac4f528a3203738cc63455 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libictranslate/libictranslate.def (.../libictranslate.def) (revision bee51aca3d5d9b67ecac4f528a3203738cc63455) +++ src/libictranslate/libictranslate.def (.../libictranslate.def) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,6 +1,6 @@ -; libictranslate.def : Declares the module parameters for the DLL. - -LIBRARY "libictranslate" - -EXPORTS - ; Explicit exports can go here +; libictranslate.def : Declares the module parameters for the DLL. + +LIBRARY "libictranslate" + +EXPORTS + ; Explicit exports can go here Index: src/libictranslate/libictranslate.rc =================================================================== diff -u -rbee51aca3d5d9b67ecac4f528a3203738cc63455 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libictranslate/libictranslate.rc (.../libictranslate.rc) (revision bee51aca3d5d9b67ecac4f528a3203738cc63455) +++ src/libictranslate/libictranslate.rc (.../libictranslate.rc) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,84 +1,84 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#ifndef APSTUDIO_INVOKED -#include "targetver.h" -#endif -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#ifndef APSTUDIO_INVOKED\r\n" - "#include ""targetver.h""\r\n" - "#endif\r\n" - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#define _AFX_NO_SPLITTER_RESOURCES\r\n" - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1250)\r\n" - "#include ""res\\libictranslate.rc2"" // non-Microsoft Visual C++ edited resources\r\n" -#ifndef _AFXDLL - "#include ""afxres.rc"" // Standard components\r\n" -#endif - "#endif\r\n" - "\0" -END - -///////////////////////////////////////////////////////////////////////////// -#endif // APSTUDIO_INVOKED - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 -#pragma code_page(1250) - -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_SPLITTER_RESOURCES -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 -#pragma code_page(1250) -#include "res\\libictranslate.rc2" // non-Microsoft Visual C++ edited resources -#ifndef _AFXDLL -#include "afxres.rc" // Standard components -#endif -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#ifndef APSTUDIO_INVOKED +#include "targetver.h" +#endif +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#ifndef APSTUDIO_INVOKED\r\n" + "#include ""targetver.h""\r\n" + "#endif\r\n" + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1250)\r\n" + "#include ""res\\libictranslate.rc2"" // non-Microsoft Visual C++ edited resources\r\n" +#ifndef _AFXDLL + "#include ""afxres.rc"" // Standard components\r\n" +#endif + "#endif\r\n" + "\0" +END + +///////////////////////////////////////////////////////////////////////////// +#endif // APSTUDIO_INVOKED + + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE 9, 1 +#pragma code_page(1250) + +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE 9, 1 +#pragma code_page(1250) +#include "res\\libictranslate.rc2" // non-Microsoft Visual C++ edited resources +#ifndef _AFXDLL +#include "afxres.rc" // Standard components +#endif +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + Index: src/libictranslate/libictranslate.vc140.vcxproj =================================================================== diff -u -rf0b3178897bcff99beb7fde44dfe952ccbf40bec -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libictranslate/libictranslate.vc140.vcxproj (.../libictranslate.vc140.vcxproj) (revision f0b3178897bcff99beb7fde44dfe952ccbf40bec) +++ src/libictranslate/libictranslate.vc140.vcxproj (.../libictranslate.vc140.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,601 +1,601 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - Testing Debug - Win32 - - - Testing Debug - x64 - - - Testing Release - Win32 - - - Testing Release - x64 - - - - libictranslate - {DD1F3242-7EE4-4F41-8B8D-D833300C445F} - libictranslate - MFCDLLProj - - - - DynamicLibrary - v120_xp - Dynamic - Unicode - true - - - DynamicLibrary - v120_xp - Dynamic - Unicode - true - - - DynamicLibrary - v120_xp - Dynamic - Unicode - - - DynamicLibrary - v120_xp - Dynamic - Unicode - - - DynamicLibrary - v120_xp - Dynamic - Unicode - true - - - DynamicLibrary - v120_xp - Dynamic - Unicode - true - - - DynamicLibrary - v120_xp - Dynamic - Unicode - - - DynamicLibrary - v120_xp - Dynamic - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.51106.1 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - - _DEBUG;%(PreprocessorDefinitions) - false - - - Disabled - WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - NoExtensions - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - MachineX86 - true - - - - - _DEBUG;%(PreprocessorDefinitions) - false - - - Disabled - WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - NoExtensions - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - MachineX86 - gmock32d.lib - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - _DEBUG;%(PreprocessorDefinitions) - false - X64 - - - Disabled - WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - MachineX64 - false - - - - - _DEBUG;%(PreprocessorDefinitions) - false - X64 - - - Disabled - WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - MachineX64 - gmock64d.lib - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - NDEBUG;%(PreprocessorDefinitions) - false - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - NoExtensions - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - true - true - MachineX86 - true - - - - - NDEBUG;%(PreprocessorDefinitions) - false - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - NoExtensions - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - true - true - MachineX86 - gmock32.lib - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - NDEBUG;%(PreprocessorDefinitions) - false - X64 - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - true - true - MachineX64 - false - - - - - NDEBUG;%(PreprocessorDefinitions) - false - X64 - - - MaxSpeed - true - WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(IntDir);%(AdditionalIncludeDirectories) - - - "$(OutDir)" - true - Windows - true - true - MachineX64 - gmock64.lib - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - true - true - true - true - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - - - - - - - - - - - false - false - - - - - false - false - - - - - false - false - - - - - false - false - - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + Testing Debug + Win32 + + + Testing Debug + x64 + + + Testing Release + Win32 + + + Testing Release + x64 + + + + libictranslate + {DD1F3242-7EE4-4F41-8B8D-D833300C445F} + libictranslate + MFCDLLProj + + + + DynamicLibrary + v120_xp + Dynamic + Unicode + true + + + DynamicLibrary + v120_xp + Dynamic + Unicode + true + + + DynamicLibrary + v120_xp + Dynamic + Unicode + + + DynamicLibrary + v120_xp + Dynamic + Unicode + + + DynamicLibrary + v120_xp + Dynamic + Unicode + true + + + DynamicLibrary + v120_xp + Dynamic + Unicode + true + + + DynamicLibrary + v120_xp + Dynamic + Unicode + + + DynamicLibrary + v120_xp + Dynamic + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>11.0.51106.1 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + + _DEBUG;%(PreprocessorDefinitions) + false + + + Disabled + WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + NoExtensions + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + MachineX86 + true + + + + + _DEBUG;%(PreprocessorDefinitions) + false + + + Disabled + WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + NoExtensions + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + MachineX86 + gmock32d.lib + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + _DEBUG;%(PreprocessorDefinitions) + false + X64 + + + Disabled + WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + MachineX64 + false + + + + + _DEBUG;%(PreprocessorDefinitions) + false + X64 + + + Disabled + WIN32;_WINDOWS;_DEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + MachineX64 + gmock64d.lib + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + NDEBUG;%(PreprocessorDefinitions) + false + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + NoExtensions + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + true + true + MachineX86 + true + + + + + NDEBUG;%(PreprocessorDefinitions) + false + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + NoExtensions + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + true + true + MachineX86 + gmock32.lib + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + NDEBUG;%(PreprocessorDefinitions) + false + X64 + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + true + true + MachineX64 + false + + + + + NDEBUG;%(PreprocessorDefinitions) + false + X64 + + + MaxSpeed + true + WIN32;_WINDOWS;NDEBUG;_AFXEXT;_CRT_SECURE_NO_DEPRECATE;LIBICTRANSLATE_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include; + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + "$(OutDir)" + true + Windows + true + true + MachineX64 + gmock64.lib + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + true + true + true + true + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + + + + + + + + + + + false + false + + + + + false + false + + + + + false + false + + + + + false + false + + + + + + Create + Create + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file Index: src/libictranslate/libictranslate.vc140.vcxproj.filters =================================================================== diff -u -ra27d1acf1bda3c25b6dcce0d0eb0278009ce63ae -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libictranslate/libictranslate.vc140.vcxproj.filters (.../libictranslate.vc140.vcxproj.filters) (revision a27d1acf1bda3c25b6dcce0d0eb0278009ce63ae) +++ src/libictranslate/libictranslate.vc140.vcxproj.filters (.../libictranslate.vc140.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,103 +1,103 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - {5f24c877-aafc-40b9-b4c5-a80951ace0df} - - - {7cfe7547-95e2-4cc7-8432-af0116adf961} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Tests - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - - - Source Files - - - Resource Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - Source Files\Tools - - - - - Resource Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + {5f24c877-aafc-40b9-b4c5-a80951ace0df} + + + {7cfe7547-95e2-4cc7-8432-af0116adf961} + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Tests + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + + + Source Files + + + Resource Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + Source Files\Tools + + + + + Resource Files + + \ No newline at end of file Index: src/libictranslate/res/libictranslate.rc2 =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/libictranslate/res/libictranslate.rc2 (.../libictranslate.rc2) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/libictranslate/res/libictranslate.rc2 (.../libictranslate.rc2) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -// -// libictranslate.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED -#error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - -#include "../common/version.h" - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x29L -#else - FILEFLAGS 0x28L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Library supporting translation of Copy Handler to various languages" - VALUE "CompanyName", " " - VALUE "FileDescription", "Copy Handler Translation Library" - VALUE "FileVersion", PRODUCT_VERSION - VALUE "LegalCopyright", COPYRIGHT_INFO - VALUE "LegalTrademarks", " " - VALUE "OriginalFilename", "libictranslate.dll" - VALUE "ProductName", "Copy Handler" - VALUE "ProductVersion", PRODUCT_VERSION - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -///////////////////////////////////////////////////////////////////////////// +// +// libictranslate.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED +#error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + +#include "../common/version.h" + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x29L +#else + FILEFLAGS 0x28L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Library supporting translation of Copy Handler to various languages" + VALUE "CompanyName", " " + VALUE "FileDescription", "Copy Handler Translation Library" + VALUE "FileVersion", PRODUCT_VERSION + VALUE "LegalCopyright", COPYRIGHT_INFO + VALUE "LegalTrademarks", " " + VALUE "OriginalFilename", "libictranslate.dll" + VALUE "ProductName", "Copy Handler" + VALUE "ProductVersion", PRODUCT_VERSION + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +///////////////////////////////////////////////////////////////////////////// Index: src/liblogger/TAsyncMultiLogger.cpp =================================================================== diff -u -raa18f0444eecb7f31ecc142bf53509c48ac77b35 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TAsyncMultiLogger.cpp (.../TAsyncMultiLogger.cpp) (revision aa18f0444eecb7f31ecc142bf53509c48ac77b35) +++ src/liblogger/TAsyncMultiLogger.cpp (.../TAsyncMultiLogger.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,149 +1,149 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TAsyncMultiLogger.h" -#include -#include -#include - -namespace logger -{ - TAsyncMultiLoggerPtr TAsyncMultiLogger::GetInstance() - { - static TAsyncMultiLoggerPtr Logger(new TAsyncMultiLogger); - return Logger; - } - - TAsyncMultiLogger::TAsyncMultiLogger() : - m_spStopEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), - m_spStoppedEvent(CreateEvent(nullptr, TRUE, TRUE, nullptr), CloseHandle), - m_spGlobalRotationInfo(std::make_shared()) - { - if (!m_spStopEvent) - throw std::runtime_error("Cannot create stop event"); - } - - TAsyncMultiLogger::~TAsyncMultiLogger() - { - FinishLogging(); - } - - void TAsyncMultiLogger::FinishLogging() - { - SetEvent(m_spStopEvent.get()); - if(m_hThread) - { - WaitForSingleObject(m_spStoppedEvent.get(), INFINITE); - - // NOTE: for some unknown reason we can't wait for the thread event in shell extension even when the thread - // exited successfully. For that reason we're synchronizing thread exit with m_spStoppedEvent. - //WaitForSingleObject(m_hThread, INFINITE); - CloseHandle(m_hThread); - m_hThread = nullptr; - } - - m_setLoggerData.clear(); - } - - TLogFileDataPtr TAsyncMultiLogger::CreateLoggerData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig) - { - TLogFileDataPtr spLogFileData = std::make_shared(pszLogPath, spLoggerConfig, m_spGlobalRotationInfo); - - boost::unique_lock lock(m_mutex); - m_setLoggerData.insert(spLogFileData); - - if(!m_hThread) - m_hThread = CreateThread(nullptr, 0, &LoggingThread, this, 0, nullptr); - - return spLogFileData; - } - - TLoggerRotationInfoPtr TAsyncMultiLogger::GetRotationInfo() const - { - return m_spGlobalRotationInfo; - } - - void TAsyncMultiLogger::SetMaxLogSize(unsigned int uiMaxLogSize) - { - m_spGlobalRotationInfo->SetMaxLogSize(uiMaxLogSize); - } - - void TAsyncMultiLogger::SetMaxRotatedCount(unsigned int uiMaxRotatedCount) - { - m_spGlobalRotationInfo->SetRotatedCount(uiMaxRotatedCount); - } - - DWORD TAsyncMultiLogger::LoggingThread(void* pParam) - { - TAsyncMultiLogger* pAsyncLogger = (TAsyncMultiLogger*)pParam; - - ResetEvent(pAsyncLogger->m_spStoppedEvent.get()); - - try - { - std::vector vHandles; - - bool bStopProcessing = false; - do - { - { - boost::unique_lock lock(pAsyncLogger->m_mutex); - vHandles.clear(); - vHandles.push_back(pAsyncLogger->m_spStopEvent.get()); - - std::transform(pAsyncLogger->m_setLoggerData.begin(), pAsyncLogger->m_setLoggerData.end(), std::back_inserter(vHandles), [](const TLogFileDataPtr& rData) { return rData->GetEntriesEvent().get(); }); - } - - DWORD dwWaitResult = WaitForMultipleObjectsEx(boost::numeric_cast(vHandles.size()), &vHandles[ 0 ], FALSE, 500, FALSE); - if(dwWaitResult == WAIT_OBJECT_0) - { - bStopProcessing = true; - break; - } - - std::vector vLogs; - { - boost::shared_lock lock(pAsyncLogger->m_mutex); - vLogs.insert(vLogs.begin(), pAsyncLogger->m_setLoggerData.begin(), pAsyncLogger->m_setLoggerData.end()); - } - - for(const TLogFileDataPtr& spLogData : vLogs) - { - try - { - spLogData->StoreLogEntries(); - spLogData->CloseUnusedFile(); - } - catch(const std::exception& e) - { - e; - ATLTRACE(e.what()); - } - } - } - while(!bStopProcessing); - } - catch(const std::exception&) - { - } - - SetEvent(pAsyncLogger->m_spStoppedEvent.get()); - return 0; - } -} +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TAsyncMultiLogger.h" +#include +#include +#include + +namespace logger +{ + TAsyncMultiLoggerPtr TAsyncMultiLogger::GetInstance() + { + static TAsyncMultiLoggerPtr Logger(new TAsyncMultiLogger); + return Logger; + } + + TAsyncMultiLogger::TAsyncMultiLogger() : + m_spStopEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), + m_spStoppedEvent(CreateEvent(nullptr, TRUE, TRUE, nullptr), CloseHandle), + m_spGlobalRotationInfo(std::make_shared()) + { + if (!m_spStopEvent) + throw std::runtime_error("Cannot create stop event"); + } + + TAsyncMultiLogger::~TAsyncMultiLogger() + { + FinishLogging(); + } + + void TAsyncMultiLogger::FinishLogging() + { + SetEvent(m_spStopEvent.get()); + if(m_hThread) + { + WaitForSingleObject(m_spStoppedEvent.get(), INFINITE); + + // NOTE: for some unknown reason we can't wait for the thread event in shell extension even when the thread + // exited successfully. For that reason we're synchronizing thread exit with m_spStoppedEvent. + //WaitForSingleObject(m_hThread, INFINITE); + CloseHandle(m_hThread); + m_hThread = nullptr; + } + + m_setLoggerData.clear(); + } + + TLogFileDataPtr TAsyncMultiLogger::CreateLoggerData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig) + { + TLogFileDataPtr spLogFileData = std::make_shared(pszLogPath, spLoggerConfig, m_spGlobalRotationInfo); + + boost::unique_lock lock(m_mutex); + m_setLoggerData.insert(spLogFileData); + + if(!m_hThread) + m_hThread = CreateThread(nullptr, 0, &LoggingThread, this, 0, nullptr); + + return spLogFileData; + } + + TLoggerRotationInfoPtr TAsyncMultiLogger::GetRotationInfo() const + { + return m_spGlobalRotationInfo; + } + + void TAsyncMultiLogger::SetMaxLogSize(unsigned int uiMaxLogSize) + { + m_spGlobalRotationInfo->SetMaxLogSize(uiMaxLogSize); + } + + void TAsyncMultiLogger::SetMaxRotatedCount(unsigned int uiMaxRotatedCount) + { + m_spGlobalRotationInfo->SetRotatedCount(uiMaxRotatedCount); + } + + DWORD TAsyncMultiLogger::LoggingThread(void* pParam) + { + TAsyncMultiLogger* pAsyncLogger = (TAsyncMultiLogger*)pParam; + + ResetEvent(pAsyncLogger->m_spStoppedEvent.get()); + + try + { + std::vector vHandles; + + bool bStopProcessing = false; + do + { + { + boost::unique_lock lock(pAsyncLogger->m_mutex); + vHandles.clear(); + vHandles.push_back(pAsyncLogger->m_spStopEvent.get()); + + std::transform(pAsyncLogger->m_setLoggerData.begin(), pAsyncLogger->m_setLoggerData.end(), std::back_inserter(vHandles), [](const TLogFileDataPtr& rData) { return rData->GetEntriesEvent().get(); }); + } + + DWORD dwWaitResult = WaitForMultipleObjectsEx(boost::numeric_cast(vHandles.size()), &vHandles[ 0 ], FALSE, 500, FALSE); + if(dwWaitResult == WAIT_OBJECT_0) + { + bStopProcessing = true; + break; + } + + std::vector vLogs; + { + boost::shared_lock lock(pAsyncLogger->m_mutex); + vLogs.insert(vLogs.begin(), pAsyncLogger->m_setLoggerData.begin(), pAsyncLogger->m_setLoggerData.end()); + } + + for(const TLogFileDataPtr& spLogData : vLogs) + { + try + { + spLogData->StoreLogEntries(); + spLogData->CloseUnusedFile(); + } + catch(const std::exception& e) + { + e; + ATLTRACE(e.what()); + } + } + } + while(!bStopProcessing); + } + catch(const std::exception&) + { + } + + SetEvent(pAsyncLogger->m_spStoppedEvent.get()); + return 0; + } +} Index: src/liblogger/TAsyncMultiLogger.h =================================================================== diff -u -r0e09682e3d8fe604066820a5e283361f9f088704 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TAsyncMultiLogger.h (.../TAsyncMultiLogger.h) (revision 0e09682e3d8fe604066820a5e283361f9f088704) +++ src/liblogger/TAsyncMultiLogger.h (.../TAsyncMultiLogger.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,68 +1,68 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TASYNCMULTILOGGER_H__ -#define __TASYNCMULTILOGGER_H__ - -#include "TLogFileData.h" -#include -#include -#include "TLoggerRotationInfo.h" -#include "liblogger.h" - -namespace logger -{ - class TAsyncMultiLogger; - - using TAsyncMultiLoggerPtr = std::shared_ptr; - - class LIBLOGGER_API TAsyncMultiLogger - { - public: - static TAsyncMultiLoggerPtr GetInstance(); - - public: - TAsyncMultiLogger(); - ~TAsyncMultiLogger(); - - void FinishLogging(); - TLogFileDataPtr CreateLoggerData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig); - - TLoggerRotationInfoPtr GetRotationInfo() const; - void SetMaxLogSize(unsigned int uiMaxLogSize); - void SetMaxRotatedCount(unsigned int uiMaxRotatedCount); - - private: - static DWORD __stdcall LoggingThread(void* pParam); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::unordered_set m_setLoggerData; - boost::shared_mutex m_mutex; - - std::shared_ptr m_spStopEvent; - std::shared_ptr m_spStoppedEvent; - HANDLE m_hThread = nullptr; - - TLoggerRotationInfoPtr m_spGlobalRotationInfo; -#pragma warning(pop) - }; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TASYNCMULTILOGGER_H__ +#define __TASYNCMULTILOGGER_H__ + +#include "TLogFileData.h" +#include +#include +#include "TLoggerRotationInfo.h" +#include "liblogger.h" + +namespace logger +{ + class TAsyncMultiLogger; + + using TAsyncMultiLoggerPtr = std::shared_ptr; + + class LIBLOGGER_API TAsyncMultiLogger + { + public: + static TAsyncMultiLoggerPtr GetInstance(); + + public: + TAsyncMultiLogger(); + ~TAsyncMultiLogger(); + + void FinishLogging(); + TLogFileDataPtr CreateLoggerData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig); + + TLoggerRotationInfoPtr GetRotationInfo() const; + void SetMaxLogSize(unsigned int uiMaxLogSize); + void SetMaxRotatedCount(unsigned int uiMaxRotatedCount); + + private: + static DWORD __stdcall LoggingThread(void* pParam); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::unordered_set m_setLoggerData; + boost::shared_mutex m_mutex; + + std::shared_ptr m_spStopEvent; + std::shared_ptr m_spStoppedEvent; + HANDLE m_hThread = nullptr; + + TLoggerRotationInfoPtr m_spGlobalRotationInfo; +#pragma warning(pop) + }; +} + +#endif Index: src/liblogger/TLogFile.cpp =================================================================== diff -u -rde48778626a2e3f6a09a43f0211b2a04eba36fed -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogFile.cpp (.../TLogFile.cpp) (revision de48778626a2e3f6a09a43f0211b2a04eba36fed) +++ src/liblogger/TLogFile.cpp (.../TLogFile.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,200 +1,200 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLogFile.h" -#include -#include -#include -#include - -namespace logger -{ - namespace internal - { - TLogFile::TLogFile(PCTSTR pszPath, const TLoggerRotationInfoPtr& spRotationInfo) : - m_strLogPath(pszPath ? pszPath : L""), - m_spFileHandle(), - m_spRotationInfo(spRotationInfo) - { - if (!pszPath) - throw std::invalid_argument("pszPath"); - if (!spRotationInfo) - throw std::invalid_argument("spRotationInfo"); - - ScanForRotatedLogs(); - } - - void TLogFile::Write(std::list& rListEntries) - { - if (rListEntries.empty()) - return; - - try - { - std::wstring_convert> utf8Converter; - - for (const std::wstring& rstrEntry : rListEntries) - { - std::string strUtf8Line = utf8Converter.to_bytes(rstrEntry); - - size_t stEntryLen = strUtf8Line.length(); - if (NeedRotation(stEntryLen)) - RotateFile(); - - DWORD dwWritten = 0; - if (!WriteFile(GetFileHandle(), strUtf8Line.c_str(), boost::numeric_cast(stEntryLen), &dwWritten, nullptr)) - throw std::runtime_error("Cannot write to log, system error"); - } - } - catch (const std::exception&) - { - rListEntries.clear(); - return; - } - - m_timeLastWriteTime = time(nullptr); - rListEntries.clear(); - } - - void TLogFile::CloseIfUnused() - { - if (time(nullptr) - m_timeLastWriteTime > MaxHandleCacheTime) - CloseLogFile(); - } - - void TLogFile::CloseLogFile() - { - m_spFileHandle.reset(); - } - - const std::vector& TLogFile::GetRotatedLogs() const - { - return m_vRotatedFiles; - } - - std::wstring TLogFile::GetLogPath() const - { - return m_strLogPath; - } - - HANDLE TLogFile::GetFileHandle() - { - if (m_spFileHandle != nullptr) - return m_spFileHandle.get(); - - HANDLE hFile = CreateFile(m_strLogPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (hFile == INVALID_HANDLE_VALUE) - throw std::runtime_error("Cannot open log file"); - - m_spFileHandle.reset(hFile, CloseHandle); - - LARGE_INTEGER liSeek = { 0 }; - - BOOL bRes = SetFilePointerEx(hFile, liSeek, nullptr, SEEK_END); - if (!bRes) - throw std::runtime_error("Cannot seek to the end of log file"); - - return m_spFileHandle.get(); - } - - unsigned long long TLogFile::GetCurrentLogSize() - { - LARGE_INTEGER liSize = { 0 }; - if (!GetFileSizeEx(GetFileHandle(), &liSize)) - throw std::runtime_error("Cannot determine current log size"); - - return liSize.QuadPart; - } - - void TLogFile::RotateFile() - { - m_spFileHandle.reset(); - - std::wstring pathNew = m_strLogPath; - if (boost::iends_with(pathNew, L".log")) - pathNew.erase(pathNew.end() - 4, pathNew.end()); - - boost::posix_time::ptime timeNow = boost::posix_time::microsec_clock::local_time(); - boost::posix_time::wtime_facet* facet = new boost::posix_time::wtime_facet(); - facet->format(L"%Y%m%d%H%M%S%f"); - std::wstringstream stream; - stream.imbue(std::locale(std::locale::classic(), facet)); - stream << timeNow; - pathNew += L"."; - pathNew += stream.str().c_str(); - pathNew += L".log"; - - if (!MoveFile(m_strLogPath.c_str(), pathNew.c_str()) && GetLastError() != ERROR_FILE_NOT_FOUND) - throw std::runtime_error("Cannot rotate file"); - - m_vRotatedFiles.push_back(std::move(pathNew)); - RemoveObsoleteRotatedLogs(); - } - - void TLogFile::RemoveObsoleteRotatedLogs() - { - while (m_vRotatedFiles.size() > m_spRotationInfo->GetMaxRotatedCount()) - { - auto iterRotatedFile = m_vRotatedFiles.begin(); - if (!DeleteFile(iterRotatedFile->c_str())) - break; - - m_vRotatedFiles.erase(iterRotatedFile); - } - } - - void TLogFile::ScanForRotatedLogs() - { - std::wstring strSearchMask = m_strLogPath; - std::wstring strDir; - - size_t stDirPos = strSearchMask.find_last_of(L"\\/"); - if (stDirPos != std::wstring::npos) - strDir = strSearchMask.substr(0, stDirPos + 1); - - if (boost::iends_with(strSearchMask, L".log")) - strSearchMask.erase(strSearchMask.end() - 4, strSearchMask.end()); - strSearchMask += L".*.log"; - - std::vector vPaths; - WIN32_FIND_DATA wfd = { 0 }; - - HANDLE hFind = FindFirstFile(strSearchMask.c_str(), &wfd); - BOOL bFound = (hFind != INVALID_HANDLE_VALUE); - while (bFound) - { - std::wstring strLogFullPath = strDir + wfd.cFileName; - vPaths.push_back(strLogFullPath); - - bFound = FindNextFile(hFind, &wfd); - } - - std::sort(vPaths.begin(), vPaths.end(), [](const std::wstring& path1, const std::wstring& path2) { return boost::ilexicographical_compare(path1, path2); }); - std::swap(m_vRotatedFiles, vPaths); - } - - bool TLogFile::NeedRotation(size_t stDataSize) - { - unsigned long long ullCurrentSize = GetCurrentLogSize(); - unsigned long long ullMaxLogSize = m_spRotationInfo->GetMaxLogSize(); - - return ullCurrentSize + stDataSize > ullMaxLogSize; - } - } -} +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLogFile.h" +#include +#include +#include +#include + +namespace logger +{ + namespace internal + { + TLogFile::TLogFile(PCTSTR pszPath, const TLoggerRotationInfoPtr& spRotationInfo) : + m_strLogPath(pszPath ? pszPath : L""), + m_spFileHandle(), + m_spRotationInfo(spRotationInfo) + { + if (!pszPath) + throw std::invalid_argument("pszPath"); + if (!spRotationInfo) + throw std::invalid_argument("spRotationInfo"); + + ScanForRotatedLogs(); + } + + void TLogFile::Write(std::list& rListEntries) + { + if (rListEntries.empty()) + return; + + try + { + std::wstring_convert> utf8Converter; + + for (const std::wstring& rstrEntry : rListEntries) + { + std::string strUtf8Line = utf8Converter.to_bytes(rstrEntry); + + size_t stEntryLen = strUtf8Line.length(); + if (NeedRotation(stEntryLen)) + RotateFile(); + + DWORD dwWritten = 0; + if (!WriteFile(GetFileHandle(), strUtf8Line.c_str(), boost::numeric_cast(stEntryLen), &dwWritten, nullptr)) + throw std::runtime_error("Cannot write to log, system error"); + } + } + catch (const std::exception&) + { + rListEntries.clear(); + return; + } + + m_timeLastWriteTime = time(nullptr); + rListEntries.clear(); + } + + void TLogFile::CloseIfUnused() + { + if (time(nullptr) - m_timeLastWriteTime > MaxHandleCacheTime) + CloseLogFile(); + } + + void TLogFile::CloseLogFile() + { + m_spFileHandle.reset(); + } + + const std::vector& TLogFile::GetRotatedLogs() const + { + return m_vRotatedFiles; + } + + std::wstring TLogFile::GetLogPath() const + { + return m_strLogPath; + } + + HANDLE TLogFile::GetFileHandle() + { + if (m_spFileHandle != nullptr) + return m_spFileHandle.get(); + + HANDLE hFile = CreateFile(m_strLogPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (hFile == INVALID_HANDLE_VALUE) + throw std::runtime_error("Cannot open log file"); + + m_spFileHandle.reset(hFile, CloseHandle); + + LARGE_INTEGER liSeek = { 0 }; + + BOOL bRes = SetFilePointerEx(hFile, liSeek, nullptr, SEEK_END); + if (!bRes) + throw std::runtime_error("Cannot seek to the end of log file"); + + return m_spFileHandle.get(); + } + + unsigned long long TLogFile::GetCurrentLogSize() + { + LARGE_INTEGER liSize = { 0 }; + if (!GetFileSizeEx(GetFileHandle(), &liSize)) + throw std::runtime_error("Cannot determine current log size"); + + return liSize.QuadPart; + } + + void TLogFile::RotateFile() + { + m_spFileHandle.reset(); + + std::wstring pathNew = m_strLogPath; + if (boost::iends_with(pathNew, L".log")) + pathNew.erase(pathNew.end() - 4, pathNew.end()); + + boost::posix_time::ptime timeNow = boost::posix_time::microsec_clock::local_time(); + boost::posix_time::wtime_facet* facet = new boost::posix_time::wtime_facet(); + facet->format(L"%Y%m%d%H%M%S%f"); + std::wstringstream stream; + stream.imbue(std::locale(std::locale::classic(), facet)); + stream << timeNow; + pathNew += L"."; + pathNew += stream.str().c_str(); + pathNew += L".log"; + + if (!MoveFile(m_strLogPath.c_str(), pathNew.c_str()) && GetLastError() != ERROR_FILE_NOT_FOUND) + throw std::runtime_error("Cannot rotate file"); + + m_vRotatedFiles.push_back(std::move(pathNew)); + RemoveObsoleteRotatedLogs(); + } + + void TLogFile::RemoveObsoleteRotatedLogs() + { + while (m_vRotatedFiles.size() > m_spRotationInfo->GetMaxRotatedCount()) + { + auto iterRotatedFile = m_vRotatedFiles.begin(); + if (!DeleteFile(iterRotatedFile->c_str())) + break; + + m_vRotatedFiles.erase(iterRotatedFile); + } + } + + void TLogFile::ScanForRotatedLogs() + { + std::wstring strSearchMask = m_strLogPath; + std::wstring strDir; + + size_t stDirPos = strSearchMask.find_last_of(L"\\/"); + if (stDirPos != std::wstring::npos) + strDir = strSearchMask.substr(0, stDirPos + 1); + + if (boost::iends_with(strSearchMask, L".log")) + strSearchMask.erase(strSearchMask.end() - 4, strSearchMask.end()); + strSearchMask += L".*.log"; + + std::vector vPaths; + WIN32_FIND_DATA wfd = { 0 }; + + HANDLE hFind = FindFirstFile(strSearchMask.c_str(), &wfd); + BOOL bFound = (hFind != INVALID_HANDLE_VALUE); + while (bFound) + { + std::wstring strLogFullPath = strDir + wfd.cFileName; + vPaths.push_back(strLogFullPath); + + bFound = FindNextFile(hFind, &wfd); + } + + std::sort(vPaths.begin(), vPaths.end(), [](const std::wstring& path1, const std::wstring& path2) { return boost::ilexicographical_compare(path1, path2); }); + std::swap(m_vRotatedFiles, vPaths); + } + + bool TLogFile::NeedRotation(size_t stDataSize) + { + unsigned long long ullCurrentSize = GetCurrentLogSize(); + unsigned long long ullMaxLogSize = m_spRotationInfo->GetMaxLogSize(); + + return ullCurrentSize + stDataSize > ullMaxLogSize; + } + } +} Index: src/liblogger/TLogFile.h =================================================================== diff -u -rde48778626a2e3f6a09a43f0211b2a04eba36fed -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogFile.h (.../TLogFile.h) (revision de48778626a2e3f6a09a43f0211b2a04eba36fed) +++ src/liblogger/TLogFile.h (.../TLogFile.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,67 +1,67 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGFILE_H__ -#define __TLOGFILE_H__ - -#include -#include "TLoggerRotationInfo.h" -#include -#include - -namespace logger -{ - namespace internal - { - class TLogFile - { - public: - static const time_t MaxHandleCacheTime = 60; - - public: - TLogFile(PCTSTR pszPath, const TLoggerRotationInfoPtr& spRotationInfo); - - void Write(std::list& pszData); - void CloseIfUnused(); - void CloseLogFile(); - - const std::vector& GetRotatedLogs() const; - std::wstring GetLogPath() const; - - private: - HANDLE GetFileHandle(); - unsigned long long GetCurrentLogSize(); - void RotateFile(); - void RemoveObsoleteRotatedLogs(); - void ScanForRotatedLogs(); - bool NeedRotation(size_t stDataSize); - - private: - std::wstring m_strLogPath; - - time_t m_timeLastWriteTime = 0; - std::shared_ptr m_spFileHandle; - - // rotation - TLoggerRotationInfoPtr m_spRotationInfo; - std::vector m_vRotatedFiles; - }; - } -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGFILE_H__ +#define __TLOGFILE_H__ + +#include +#include "TLoggerRotationInfo.h" +#include +#include + +namespace logger +{ + namespace internal + { + class TLogFile + { + public: + static const time_t MaxHandleCacheTime = 60; + + public: + TLogFile(PCTSTR pszPath, const TLoggerRotationInfoPtr& spRotationInfo); + + void Write(std::list& pszData); + void CloseIfUnused(); + void CloseLogFile(); + + const std::vector& GetRotatedLogs() const; + std::wstring GetLogPath() const; + + private: + HANDLE GetFileHandle(); + unsigned long long GetCurrentLogSize(); + void RotateFile(); + void RemoveObsoleteRotatedLogs(); + void ScanForRotatedLogs(); + bool NeedRotation(size_t stDataSize); + + private: + std::wstring m_strLogPath; + + time_t m_timeLastWriteTime = 0; + std::shared_ptr m_spFileHandle; + + // rotation + TLoggerRotationInfoPtr m_spRotationInfo; + std::vector m_vRotatedFiles; + }; + } +} + +#endif Index: src/liblogger/TLogFileData.cpp =================================================================== diff -u -rde48778626a2e3f6a09a43f0211b2a04eba36fed -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogFileData.cpp (.../TLogFileData.cpp) (revision de48778626a2e3f6a09a43f0211b2a04eba36fed) +++ src/liblogger/TLogFileData.cpp (.../TLogFileData.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,95 +1,95 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLogFileData.h" -#include "TLoggerPaths.h" - -namespace logger -{ - TLogFileData::TLogFileData() : - m_spHasEntriesEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), - m_spLoggerConfig(std::make_shared()), - m_spLogFile() - { - } - - TLogFileData::TLogFileData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig, const TLoggerRotationInfoPtr& spRotationInfo) : - m_spHasEntriesEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), - m_spLoggerConfig(spLoggerConfig), - m_spLogFile(std::make_unique(pszLogPath, spRotationInfo)) - { - if(m_spHasEntriesEvent.get() == INVALID_HANDLE_VALUE) - throw std::runtime_error("Cannot create file data event"); - if(!spLoggerConfig) - throw std::runtime_error("spLoggerConfig"); - } - - TMultiLoggerConfigPtr TLogFileData::GetMultiLoggerConfig() const - { - return m_spLoggerConfig; - } - - void TLogFileData::GetAllLogPaths(TLoggerPaths& rLoggerPaths) const - { - rLoggerPaths.Clear(); - - for(const std::wstring& strPath : m_spLogFile->GetRotatedLogs()) - { - rLoggerPaths.Add(strPath.c_str()); - } - rLoggerPaths.Add(m_spLogFile->GetLogPath().c_str()); - } - - std::shared_ptr TLogFileData::GetEntriesEvent() const - { - return m_spHasEntriesEvent; - } - - void TLogFileData::PushLogEntry(std::wstring strLine) - { - if(m_spLogFile) - { - boost::unique_lock lock(m_mutex); - m_listEntries.push_back(strLine); - SetEvent(m_spHasEntriesEvent.get()); - } - } - - void TLogFileData::StoreLogEntries() - { - if(m_spLogFile) - { - std::list listEntries; - - { - boost::unique_lock lock(m_mutex); - std::swap(listEntries, m_listEntries); - ResetEvent(m_spHasEntriesEvent.get()); - } - - m_spLogFile->Write(listEntries); - } - } - - void TLogFileData::CloseUnusedFile() - { - if(m_spLogFile) - m_spLogFile->CloseIfUnused(); - } -} +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLogFileData.h" +#include "TLoggerPaths.h" + +namespace logger +{ + TLogFileData::TLogFileData() : + m_spHasEntriesEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), + m_spLoggerConfig(std::make_shared()), + m_spLogFile() + { + } + + TLogFileData::TLogFileData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig, const TLoggerRotationInfoPtr& spRotationInfo) : + m_spHasEntriesEvent(CreateEvent(nullptr, TRUE, FALSE, nullptr), CloseHandle), + m_spLoggerConfig(spLoggerConfig), + m_spLogFile(std::make_unique(pszLogPath, spRotationInfo)) + { + if(m_spHasEntriesEvent.get() == INVALID_HANDLE_VALUE) + throw std::runtime_error("Cannot create file data event"); + if(!spLoggerConfig) + throw std::runtime_error("spLoggerConfig"); + } + + TMultiLoggerConfigPtr TLogFileData::GetMultiLoggerConfig() const + { + return m_spLoggerConfig; + } + + void TLogFileData::GetAllLogPaths(TLoggerPaths& rLoggerPaths) const + { + rLoggerPaths.Clear(); + + for(const std::wstring& strPath : m_spLogFile->GetRotatedLogs()) + { + rLoggerPaths.Add(strPath.c_str()); + } + rLoggerPaths.Add(m_spLogFile->GetLogPath().c_str()); + } + + std::shared_ptr TLogFileData::GetEntriesEvent() const + { + return m_spHasEntriesEvent; + } + + void TLogFileData::PushLogEntry(std::wstring strLine) + { + if(m_spLogFile) + { + boost::unique_lock lock(m_mutex); + m_listEntries.push_back(strLine); + SetEvent(m_spHasEntriesEvent.get()); + } + } + + void TLogFileData::StoreLogEntries() + { + if(m_spLogFile) + { + std::list listEntries; + + { + boost::unique_lock lock(m_mutex); + std::swap(listEntries, m_listEntries); + ResetEvent(m_spHasEntriesEvent.get()); + } + + m_spLogFile->Write(listEntries); + } + } + + void TLogFileData::CloseUnusedFile() + { + if(m_spLogFile) + m_spLogFile->CloseIfUnused(); + } +} Index: src/liblogger/TLogFileData.h =================================================================== diff -u -rde48778626a2e3f6a09a43f0211b2a04eba36fed -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogFileData.h (.../TLogFileData.h) (revision de48778626a2e3f6a09a43f0211b2a04eba36fed) +++ src/liblogger/TLogFileData.h (.../TLogFileData.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,69 +1,69 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGFILEDATA_H__ -#define __TLOGFILEDATA_H__ - -#include -#include -#include -#include "TLogFile.h" -#include "TMultiLoggerConfig.h" -#include "liblogger.h" - -namespace logger -{ - class TLoggerPaths; - - class LIBLOGGER_API TLogFileData - { - public: - TLogFileData(); - TLogFileData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig, const TLoggerRotationInfoPtr& spRotationInfo); - - TMultiLoggerConfigPtr GetMultiLoggerConfig() const; - void GetAllLogPaths(TLoggerPaths& rLoggerPaths) const; - - private: - void PushLogEntry(std::wstring strLine); - - std::shared_ptr GetEntriesEvent() const; - void StoreLogEntries(); - void CloseUnusedFile(); - - private: -#pragma warning(push) -#pragma warning(disable: 4251) - std::list m_listEntries; - boost::shared_mutex m_mutex; - - std::shared_ptr m_spHasEntriesEvent; - - TMultiLoggerConfigPtr m_spLoggerConfig; - - std::unique_ptr m_spLogFile; -#pragma warning(pop) - - friend class TLogRecord; - friend class TAsyncMultiLogger; - }; - - using TLogFileDataPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGFILEDATA_H__ +#define __TLOGFILEDATA_H__ + +#include +#include +#include +#include "TLogFile.h" +#include "TMultiLoggerConfig.h" +#include "liblogger.h" + +namespace logger +{ + class TLoggerPaths; + + class LIBLOGGER_API TLogFileData + { + public: + TLogFileData(); + TLogFileData(PCTSTR pszLogPath, const TMultiLoggerConfigPtr& spLoggerConfig, const TLoggerRotationInfoPtr& spRotationInfo); + + TMultiLoggerConfigPtr GetMultiLoggerConfig() const; + void GetAllLogPaths(TLoggerPaths& rLoggerPaths) const; + + private: + void PushLogEntry(std::wstring strLine); + + std::shared_ptr GetEntriesEvent() const; + void StoreLogEntries(); + void CloseUnusedFile(); + + private: +#pragma warning(push) +#pragma warning(disable: 4251) + std::list m_listEntries; + boost::shared_mutex m_mutex; + + std::shared_ptr m_spHasEntriesEvent; + + TMultiLoggerConfigPtr m_spLoggerConfig; + + std::unique_ptr m_spLogFile; +#pragma warning(pop) + + friend class TLogRecord; + friend class TAsyncMultiLogger; + }; + + using TLogFileDataPtr = std::shared_ptr; +} + +#endif Index: src/liblogger/TLogRecord.h =================================================================== diff -u -r16ea740ddcaeb5a99dc90061ae0f0a2f89aa0d74 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogRecord.h (.../TLogRecord.h) (revision 16ea740ddcaeb5a99dc90061ae0f0a2f89aa0d74) +++ src/liblogger/TLogRecord.h (.../TLogRecord.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,93 +1,93 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGRECORD_H__ -#define __TLOGRECORD_H__ - -#include -#include "TLogFileData.h" -#include -#include - -namespace logger -{ - class TLogRecord : public std::wstringstream - { - public: - TLogRecord(const TLogFileDataPtr& spFileData, ESeverityLevel eLevel, const std::wstring& wstrChannel); - TLogRecord(const TLogRecord&) = delete; - TLogRecord(TLogRecord&& rSrc); - - TLogRecord& operator=(const TLogRecord&) = delete; - TLogRecord& operator=(TLogRecord&&) = delete; - - ~TLogRecord(); - - bool IsEnabled() const; - void Disable(); - - private: - TLogFileDataPtr m_spFileData; - bool m_bEnabled = true; - }; - - inline TLogRecord::TLogRecord(TLogRecord&& rSrc) : - std::wstringstream(std::move(rSrc)), - m_spFileData(std::move(rSrc.m_spFileData)) - { - } - - inline TLogRecord::TLogRecord(const TLogFileDataPtr& spFileData, ESeverityLevel eLevel, const std::wstring& wstrChannel) : - m_spFileData(spFileData) - { - boost::posix_time::wtime_facet* facet = new boost::posix_time::wtime_facet(); - facet->format(L"%Y-%m-%d %H:%M:%S.%f"); - imbue(std::locale(std::locale::classic(), facet)); - - DWORD dwThreadId = GetCurrentThreadId(); - - *this << boost::posix_time::microsec_clock::local_time() << L" [" << SeverityLevelToString(eLevel) << L"] " << wstrChannel << L"[" << dwThreadId << L"]: "; - } - - inline TLogRecord::~TLogRecord() - { - *this << L"\r\n"; - m_spFileData->PushLogEntry(str()); - } - - inline bool TLogRecord::IsEnabled() const - { - return m_bEnabled; - } - - inline void TLogRecord::Disable() - { - m_bEnabled = false; - } -} - -#ifdef _MFC_VER - -inline std::wostream& operator<<(std::wostream &os, const CString& str) -{ - return os << (PCTSTR)str; -} - -#endif - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGRECORD_H__ +#define __TLOGRECORD_H__ + +#include +#include "TLogFileData.h" +#include +#include + +namespace logger +{ + class TLogRecord : public std::wstringstream + { + public: + TLogRecord(const TLogFileDataPtr& spFileData, ESeverityLevel eLevel, const std::wstring& wstrChannel); + TLogRecord(const TLogRecord&) = delete; + TLogRecord(TLogRecord&& rSrc); + + TLogRecord& operator=(const TLogRecord&) = delete; + TLogRecord& operator=(TLogRecord&&) = delete; + + ~TLogRecord(); + + bool IsEnabled() const; + void Disable(); + + private: + TLogFileDataPtr m_spFileData; + bool m_bEnabled = true; + }; + + inline TLogRecord::TLogRecord(TLogRecord&& rSrc) : + std::wstringstream(std::move(rSrc)), + m_spFileData(std::move(rSrc.m_spFileData)) + { + } + + inline TLogRecord::TLogRecord(const TLogFileDataPtr& spFileData, ESeverityLevel eLevel, const std::wstring& wstrChannel) : + m_spFileData(spFileData) + { + boost::posix_time::wtime_facet* facet = new boost::posix_time::wtime_facet(); + facet->format(L"%Y-%m-%d %H:%M:%S.%f"); + imbue(std::locale(std::locale::classic(), facet)); + + DWORD dwThreadId = GetCurrentThreadId(); + + *this << boost::posix_time::microsec_clock::local_time() << L" [" << SeverityLevelToString(eLevel) << L"] " << wstrChannel << L"[" << dwThreadId << L"]: "; + } + + inline TLogRecord::~TLogRecord() + { + *this << L"\r\n"; + m_spFileData->PushLogEntry(str()); + } + + inline bool TLogRecord::IsEnabled() const + { + return m_bEnabled; + } + + inline void TLogRecord::Disable() + { + m_bEnabled = false; + } +} + +#ifdef _MFC_VER + +inline std::wostream& operator<<(std::wostream &os, const CString& str) +{ + return os << (PCTSTR)str; +} + +#endif + +#endif Index: src/liblogger/TLogger.h =================================================================== diff -u -r134983cab6122e3fff73994a6f9c417aaeab3bc2 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLogger.h (.../TLogger.h) (revision 134983cab6122e3fff73994a6f9c417aaeab3bc2) +++ src/liblogger/TLogger.h (.../TLogger.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,89 +1,89 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGGER_H__ -#define __TLOGGER_H__ - -#include "TLoggerLevelConfig.h" -#include -#include "TLogFileData.h" -#include "SeverityLevels.h" -#include "TMultiLoggerConfig.h" -#include "TLogRecord.h" - -namespace logger -{ - class TLogger - { - public: - TLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel); - - TLogFileDataPtr GetLogFileData() const; - ESeverityLevel GetMinSeverity() const; - TLogRecord OpenLogRecord(ESeverityLevel eLevel) const; - - private: - TLoggerLevelConfigPtr m_spLoggerConfig; - TLogFileDataPtr m_spFileData; - std::wstring m_strChannel; - - friend class TLoggerFactory; - }; - - inline TLogger::TLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel) : - m_spFileData(spFileData), - m_spLoggerConfig(spFileData->GetMultiLoggerConfig()->GetLoggerConfig(pszChannel)), - m_strChannel(pszChannel) - { - if(!spFileData) - throw std::invalid_argument("spFileData"); - } - - inline TLogFileDataPtr TLogger::GetLogFileData() const - { - return m_spFileData; - } - - inline ESeverityLevel TLogger::GetMinSeverity() const - { - return m_spLoggerConfig->GetMinSeverityLevel(); - } - - inline TLogRecord TLogger::OpenLogRecord(ESeverityLevel eLevel) const - { - return TLogRecord(m_spFileData, eLevel, m_strChannel); - } - - using TLoggerPtr = std::unique_ptr; - - inline TLoggerPtr MakeLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel) - { - return std::make_unique(spFileData, pszChannel); - } -} - -#define LOG(log, level) for(logger::TLogRecord rec = (log)->OpenLogRecord(level); rec.IsEnabled(); rec.Disable()) rec - -#define LOG_TRACE(log) if(logger::trace >= (log)->GetMinSeverity()) LOG(log, logger::trace) -#define LOG_DEBUG(log) if(logger::debug >= (log)->GetMinSeverity()) LOG(log, logger::debug) -#define LOG_INFO(log) if(logger::info >= (log)->GetMinSeverity()) LOG(log, logger::info) -#define LOG_WARNING(log) if(logger::warning >= (log)->GetMinSeverity()) LOG(log, logger::warning) -#define LOG_ERROR(log) if(logger::error >= (log)->GetMinSeverity()) LOG(log, logger::error) -#define LOG_CRITICAL(log) if(logger::critical >= (log)->GetMinSeverity()) LOG(log, logger::critical) - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGGER_H__ +#define __TLOGGER_H__ + +#include "TLoggerLevelConfig.h" +#include +#include "TLogFileData.h" +#include "SeverityLevels.h" +#include "TMultiLoggerConfig.h" +#include "TLogRecord.h" + +namespace logger +{ + class TLogger + { + public: + TLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel); + + TLogFileDataPtr GetLogFileData() const; + ESeverityLevel GetMinSeverity() const; + TLogRecord OpenLogRecord(ESeverityLevel eLevel) const; + + private: + TLoggerLevelConfigPtr m_spLoggerConfig; + TLogFileDataPtr m_spFileData; + std::wstring m_strChannel; + + friend class TLoggerFactory; + }; + + inline TLogger::TLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel) : + m_spFileData(spFileData), + m_spLoggerConfig(spFileData->GetMultiLoggerConfig()->GetLoggerConfig(pszChannel)), + m_strChannel(pszChannel) + { + if(!spFileData) + throw std::invalid_argument("spFileData"); + } + + inline TLogFileDataPtr TLogger::GetLogFileData() const + { + return m_spFileData; + } + + inline ESeverityLevel TLogger::GetMinSeverity() const + { + return m_spLoggerConfig->GetMinSeverityLevel(); + } + + inline TLogRecord TLogger::OpenLogRecord(ESeverityLevel eLevel) const + { + return TLogRecord(m_spFileData, eLevel, m_strChannel); + } + + using TLoggerPtr = std::unique_ptr; + + inline TLoggerPtr MakeLogger(const TLogFileDataPtr& spFileData, PCTSTR pszChannel) + { + return std::make_unique(spFileData, pszChannel); + } +} + +#define LOG(log, level) for(logger::TLogRecord rec = (log)->OpenLogRecord(level); rec.IsEnabled(); rec.Disable()) rec + +#define LOG_TRACE(log) if(logger::trace >= (log)->GetMinSeverity()) LOG(log, logger::trace) +#define LOG_DEBUG(log) if(logger::debug >= (log)->GetMinSeverity()) LOG(log, logger::debug) +#define LOG_INFO(log) if(logger::info >= (log)->GetMinSeverity()) LOG(log, logger::info) +#define LOG_WARNING(log) if(logger::warning >= (log)->GetMinSeverity()) LOG(log, logger::warning) +#define LOG_ERROR(log) if(logger::error >= (log)->GetMinSeverity()) LOG(log, logger::error) +#define LOG_CRITICAL(log) if(logger::critical >= (log)->GetMinSeverity()) LOG(log, logger::critical) + +#endif Index: src/liblogger/TLoggerLevelConfig.cpp =================================================================== diff -u -r8f634460db3f225ca24f2e447b3730d4f0614166 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLoggerLevelConfig.cpp (.../TLoggerLevelConfig.cpp) (revision 8f634460db3f225ca24f2e447b3730d4f0614166) +++ src/liblogger/TLoggerLevelConfig.cpp (.../TLoggerLevelConfig.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,38 +1,38 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLoggerLevelConfig.h" - -namespace logger -{ - TLoggerLevelConfig::TLoggerLevelConfig(ESeverityLevel eMinSeverity) : - m_uiMinSeverity(eMinSeverity) - { - } - - void TLoggerLevelConfig::SetMinSeverityLevel(ESeverityLevel eLevel) - { - InterlockedExchange(&m_uiMinSeverity, eLevel); - } - - ESeverityLevel TLoggerLevelConfig::GetMinSeverityLevel() const - { - return (ESeverityLevel)InterlockedCompareExchange(&m_uiMinSeverity, 0, 0); - } -} +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLoggerLevelConfig.h" + +namespace logger +{ + TLoggerLevelConfig::TLoggerLevelConfig(ESeverityLevel eMinSeverity) : + m_uiMinSeverity(eMinSeverity) + { + } + + void TLoggerLevelConfig::SetMinSeverityLevel(ESeverityLevel eLevel) + { + InterlockedExchange(&m_uiMinSeverity, eLevel); + } + + ESeverityLevel TLoggerLevelConfig::GetMinSeverityLevel() const + { + return (ESeverityLevel)InterlockedCompareExchange(&m_uiMinSeverity, 0, 0); + } +} Index: src/liblogger/TLoggerLevelConfig.h =================================================================== diff -u -r031c4e5f6be6ad9589ce5fea8292c990351f9a82 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLoggerLevelConfig.h (.../TLoggerLevelConfig.h) (revision 031c4e5f6be6ad9589ce5fea8292c990351f9a82) +++ src/liblogger/TLoggerLevelConfig.h (.../TLoggerLevelConfig.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,43 +1,43 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGGERCONFIG_H__ -#define __TLOGGERCONFIG_H__ - -#include "SeverityLevels.h" -#include -#include "liblogger.h" - -namespace logger -{ - class LIBLOGGER_API TLoggerLevelConfig - { - public: - explicit TLoggerLevelConfig(ESeverityLevel eMinSeverity = trace); - - void SetMinSeverityLevel(ESeverityLevel eLevel); - ESeverityLevel GetMinSeverityLevel() const; - - private: - volatile mutable unsigned int m_uiMinSeverity = trace; - }; - - using TLoggerLevelConfigPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGGERCONFIG_H__ +#define __TLOGGERCONFIG_H__ + +#include "SeverityLevels.h" +#include +#include "liblogger.h" + +namespace logger +{ + class LIBLOGGER_API TLoggerLevelConfig + { + public: + explicit TLoggerLevelConfig(ESeverityLevel eMinSeverity = trace); + + void SetMinSeverityLevel(ESeverityLevel eLevel); + ESeverityLevel GetMinSeverityLevel() const; + + private: + volatile mutable unsigned int m_uiMinSeverity = trace; + }; + + using TLoggerLevelConfigPtr = std::shared_ptr; +} + +#endif Index: src/liblogger/TLoggerRotationInfo.cpp =================================================================== diff -u -r8f634460db3f225ca24f2e447b3730d4f0614166 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLoggerRotationInfo.cpp (.../TLoggerRotationInfo.cpp) (revision 8f634460db3f225ca24f2e447b3730d4f0614166) +++ src/liblogger/TLoggerRotationInfo.cpp (.../TLoggerRotationInfo.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,53 +1,53 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#include "stdafx.h" -#include "TLoggerRotationInfo.h" - -namespace logger -{ - TLoggerRotationInfo::TLoggerRotationInfo() - { - } - - TLoggerRotationInfo::TLoggerRotationInfo(unsigned int uiMaxLogSize, unsigned int uiMaxRotatedCount) : - m_uiMaxLogSize(uiMaxLogSize), - m_uiMaxRotatedCount(uiMaxRotatedCount) - { - } - - void TLoggerRotationInfo::SetMaxLogSize(unsigned int uiMaxLogSize) - { - InterlockedExchange(&m_uiMaxLogSize, uiMaxLogSize); - } - - void TLoggerRotationInfo::SetRotatedCount(unsigned int uiMaxRotatedCount) - { - InterlockedExchange(&m_uiMaxRotatedCount, uiMaxRotatedCount); - } - - unsigned int TLoggerRotationInfo::GetMaxLogSize() const - { - return InterlockedCompareExchange(&m_uiMaxLogSize, 0, 0); - } - - unsigned int TLoggerRotationInfo::GetMaxRotatedCount() const - { - return InterlockedCompareExchange(&m_uiMaxRotatedCount, 0, 0); - } -} +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#include "stdafx.h" +#include "TLoggerRotationInfo.h" + +namespace logger +{ + TLoggerRotationInfo::TLoggerRotationInfo() + { + } + + TLoggerRotationInfo::TLoggerRotationInfo(unsigned int uiMaxLogSize, unsigned int uiMaxRotatedCount) : + m_uiMaxLogSize(uiMaxLogSize), + m_uiMaxRotatedCount(uiMaxRotatedCount) + { + } + + void TLoggerRotationInfo::SetMaxLogSize(unsigned int uiMaxLogSize) + { + InterlockedExchange(&m_uiMaxLogSize, uiMaxLogSize); + } + + void TLoggerRotationInfo::SetRotatedCount(unsigned int uiMaxRotatedCount) + { + InterlockedExchange(&m_uiMaxRotatedCount, uiMaxRotatedCount); + } + + unsigned int TLoggerRotationInfo::GetMaxLogSize() const + { + return InterlockedCompareExchange(&m_uiMaxLogSize, 0, 0); + } + + unsigned int TLoggerRotationInfo::GetMaxRotatedCount() const + { + return InterlockedCompareExchange(&m_uiMaxRotatedCount, 0, 0); + } +} Index: src/liblogger/TLoggerRotationInfo.h =================================================================== diff -u -r7de00e54431d78b6c54fad6fb163dbc306381ef5 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/TLoggerRotationInfo.h (.../TLoggerRotationInfo.h) (revision 7de00e54431d78b6c54fad6fb163dbc306381ef5) +++ src/liblogger/TLoggerRotationInfo.h (.../TLoggerRotationInfo.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,51 +1,51 @@ -// ============================================================================ -// Copyright (C) 2001-2016 by Jozef Starosczyk -// ixen@copyhandler.com -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU Library General Public License -// (version 2) as published by the Free Software Foundation; -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU Library General Public -// License along with this program; if not, write to the -// Free Software Foundation, Inc., -// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// ============================================================================ -#ifndef __TLOGGERROTATIONINFO_H__ -#define __TLOGGERROTATIONINFO_H__ - -#include -#include "liblogger.h" - -namespace logger -{ - class LIBLOGGER_API TLoggerRotationInfo - { - public: - static const unsigned int DefaultMaxLogSize = 10 * 1024 * 1024; - static const unsigned int DefaultMaxRotatedFiles = 5; - - public: - TLoggerRotationInfo(); - TLoggerRotationInfo(unsigned int uiMaxLogSize, unsigned int uiMaxRotatedCount); - - void SetMaxLogSize(unsigned int uiMaxLogSize); - void SetRotatedCount(unsigned int uiMaxRotatedCount); - - unsigned int GetMaxLogSize() const; - unsigned int GetMaxRotatedCount() const; - - private: - volatile mutable unsigned int m_uiMaxLogSize = DefaultMaxLogSize; - volatile mutable unsigned int m_uiMaxRotatedCount = DefaultMaxRotatedFiles; - }; - - using TLoggerRotationInfoPtr = std::shared_ptr; -} - -#endif +// ============================================================================ +// Copyright (C) 2001-2016 by Jozef Starosczyk +// ixen@copyhandler.com +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License +// (version 2) as published by the Free Software Foundation; +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Library General Public +// License along with this program; if not, write to the +// Free Software Foundation, Inc., +// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// ============================================================================ +#ifndef __TLOGGERROTATIONINFO_H__ +#define __TLOGGERROTATIONINFO_H__ + +#include +#include "liblogger.h" + +namespace logger +{ + class LIBLOGGER_API TLoggerRotationInfo + { + public: + static const unsigned int DefaultMaxLogSize = 10 * 1024 * 1024; + static const unsigned int DefaultMaxRotatedFiles = 5; + + public: + TLoggerRotationInfo(); + TLoggerRotationInfo(unsigned int uiMaxLogSize, unsigned int uiMaxRotatedCount); + + void SetMaxLogSize(unsigned int uiMaxLogSize); + void SetRotatedCount(unsigned int uiMaxRotatedCount); + + unsigned int GetMaxLogSize() const; + unsigned int GetMaxRotatedCount() const; + + private: + volatile mutable unsigned int m_uiMaxLogSize = DefaultMaxLogSize; + volatile mutable unsigned int m_uiMaxRotatedCount = DefaultMaxRotatedFiles; + }; + + using TLoggerRotationInfoPtr = std::shared_ptr; +} + +#endif Index: src/liblogger/liblogger.vc140.vcxproj =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/liblogger.vc140.vcxproj (.../liblogger.vc140.vcxproj) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/liblogger/liblogger.vc140.vcxproj (.../liblogger.vc140.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,521 +1,521 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - Testing Debug - Win32 - - - Testing Debug - x64 - - - Testing Release - Win32 - - - Testing Release - x64 - - - - liblogger - {DF9957D4-3D95-4AC3-AD3F-DCBEA058F79D} - liblogger - Win32Proj - - - - DynamicLibrary - v120_xp - Unicode - true - - - DynamicLibrary - v120_xp - Unicode - true - - - DynamicLibrary - v120_xp - Unicode - - - DynamicLibrary - v120_xp - Unicode - - - DynamicLibrary - Unicode - true - v120_xp - - - DynamicLibrary - Unicode - true - v120_xp - - - DynamicLibrary - Unicode - v120_xp - - - DynamicLibrary - Unicode - v120_xp - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.51106.1 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)32ud - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - NativeRecommendedRules.ruleset - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64ud - NativeRecommendedRules.ruleset - false - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)32u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64u - - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - MachineX86 - "$(OutDir)" - true - - - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - MachineX86 - gmock32d.lib;%(AdditionalDependencies) - "$(OutDir)" - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - X64 - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - false - ProgramDatabase - 4512;4714 - false - true - ../../ext - true - - - true - Windows - MachineX64 - "$(OutDir)" - false - - - - - X64 - - - Disabled - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - Use - Level4 - false - ProgramDatabase - 4512;4714 - false - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - true - - - true - Windows - MachineX64 - gmock64d.lib;%(AdditionalDependencies) - "$(OutDir)" - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - true - true - MachineX86 - "$(OutDir)" - true - - - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - NoExtensions - 4512;4714 - true - - - true - Windows - true - true - MachineX86 - gmock32.lib;%(AdditionalDependencies) - "$(OutDir)" - true - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - X64 - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ../../ext - 4512;4714 - true - - - true - Windows - true - true - MachineX64 - "$(OutDir)" - false - - - - - X64 - - - MaxSpeed - true - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level4 - true - ProgramDatabase - true - ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext - 4512;4714 - true - - - true - Windows - true - true - MachineX64 - gmock64.lib;%(AdditionalDependencies) - "$(OutDir)" - false - - - cd "$(TargetDir)" - -if "$(PlatformName)" EQU "x64" goto x64 - -:x32 -"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:x64 -"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" -goto end - -:end - - - - - - - - - - - - - - - - - - - - - true - true - true - true - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - NotUsing - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + Testing Debug + Win32 + + + Testing Debug + x64 + + + Testing Release + Win32 + + + Testing Release + x64 + + + + liblogger + {DF9957D4-3D95-4AC3-AD3F-DCBEA058F79D} + liblogger + Win32Proj + + + + DynamicLibrary + v120_xp + Unicode + true + + + DynamicLibrary + v120_xp + Unicode + true + + + DynamicLibrary + v120_xp + Unicode + + + DynamicLibrary + v120_xp + Unicode + + + DynamicLibrary + Unicode + true + v120_xp + + + DynamicLibrary + Unicode + true + v120_xp + + + DynamicLibrary + Unicode + v120_xp + + + DynamicLibrary + Unicode + v120_xp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>11.0.51106.1 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)32ud + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + NativeRecommendedRules.ruleset + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64ud + NativeRecommendedRules.ruleset + false + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)32u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64u + + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + MachineX86 + "$(OutDir)" + true + + + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + MachineX86 + gmock32d.lib;%(AdditionalDependencies) + "$(OutDir)" + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + X64 + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + false + ProgramDatabase + 4512;4714 + false + true + ../../ext + true + + + true + Windows + MachineX64 + "$(OutDir)" + false + + + + + X64 + + + Disabled + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + Use + Level4 + false + ProgramDatabase + 4512;4714 + false + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + true + + + true + Windows + MachineX64 + gmock64d.lib;%(AdditionalDependencies) + "$(OutDir)" + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + true + true + MachineX86 + "$(OutDir)" + true + + + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + NoExtensions + 4512;4714 + true + + + true + Windows + true + true + MachineX86 + gmock32.lib;%(AdditionalDependencies) + "$(OutDir)" + true + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + X64 + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ../../ext + 4512;4714 + true + + + true + Windows + true + true + MachineX64 + "$(OutDir)" + false + + + + + X64 + + + MaxSpeed + true + _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBLOGGER_EXPORTS;_BIND_TO_CURRENT_VCLIBS_VERSION=1;NOMINMAX;TESTING;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level4 + true + ProgramDatabase + true + ..\..\ext\googletest\googletest\include;..\..\ext\googletest\googlemock\include;../../ext + 4512;4714 + true + + + true + Windows + true + true + MachineX64 + gmock64.lib;%(AdditionalDependencies) + "$(OutDir)" + false + + + cd "$(TargetDir)" + +if "$(PlatformName)" EQU "x64" goto x64 + +:x32 +"$(SolutionDir)tools\test_runner32.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:x64 +"$(SolutionDir)tools\test_runner64.exe" "$(TargetPath)" --gtest_shuffle --gtest_output="xml:$(TargetPath).UnitTests.xml" +goto end + +:end + + + + + + + + + + + + + + + + + + + + + true + true + true + true + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + NotUsing + + + + + Create + Create + Create + Create + Create + Create + Create + Create + + + + + + + + + + + + + + + \ No newline at end of file Index: src/liblogger/liblogger.vc140.vcxproj.filters =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/liblogger.vc140.vcxproj.filters (.../liblogger.vc140.vcxproj.filters) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/liblogger/liblogger.vc140.vcxproj.filters (.../liblogger.vc140.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,101 +1,101 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {e160d2cd-2a88-40ef-97b4-6b7d3b7ed6b1} - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - {30839f8d-ff2c-45d2-86fe-a7a494f42c8b} - - - {d67e75ea-a3ac-4115-b546-93a6914ee712} - - - - - Source Files\Library files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files\Library files - - - Source Files\internal - - - Source Files - - - Source Files - - - - - - Source Files\Library files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files\Library files - - - Source Files\Library files - - - Tests - - - Source Files\internal - - - Source Files - - - - - Resource Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {e160d2cd-2a88-40ef-97b4-6b7d3b7ed6b1} + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + {30839f8d-ff2c-45d2-86fe-a7a494f42c8b} + + + {d67e75ea-a3ac-4115-b546-93a6914ee712} + + + + + Source Files\Library files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\Library files + + + Source Files\internal + + + Source Files + + + Source Files + + + + + + Source Files\Library files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\Library files + + + Source Files\Library files + + + Tests + + + Source Files\internal + + + Source Files + + + + + Resource Files + + \ No newline at end of file Index: src/liblogger/res/liblogger.rc2 =================================================================== diff -u -r8163be49a92698ada689f27b2dbe0caae69a7d5c -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/liblogger/res/liblogger.rc2 (.../liblogger.rc2) (revision 8163be49a92698ada689f27b2dbe0caae69a7d5c) +++ src/liblogger/res/liblogger.rc2 (.../liblogger.rc2) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,52 +1,52 @@ -// -// liblogger.rc2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - -#include "../common/version.h" - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x29L -#else - FILEFLAGS 0x28L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Multi-file, multithreaded, async logger library" - VALUE "CompanyName", " " - VALUE "FileDescription", "Async Logger Library" - VALUE "FileVersion", PRODUCT_VERSION - VALUE "LegalCopyright", COPYRIGHT_INFO - VALUE "LegalTrademarks", " " - VALUE "OriginalFilename", "liblogger.dll" - VALUE "ProductName", "Copy Handler" - VALUE "ProductVersion", PRODUCT_VERSION - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -///////////////////////////////////////////////////////////////////////////// +// +// liblogger.rc2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + +#include "../common/version.h" + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + PRODUCTVERSION PRODUCT_VERSION1, PRODUCT_VERSION2, PRODUCT_VERSION3, PRODUCT_VERSION4 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x29L +#else + FILEFLAGS 0x28L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Multi-file, multithreaded, async logger library" + VALUE "CompanyName", " " + VALUE "FileDescription", "Async Logger Library" + VALUE "FileVersion", PRODUCT_VERSION + VALUE "LegalCopyright", COPYRIGHT_INFO + VALUE "LegalTrademarks", " " + VALUE "OriginalFilename", "liblogger.dll" + VALUE "ProductName", "Copy Handler" + VALUE "ProductVersion", PRODUCT_VERSION + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +///////////////////////////////////////////////////////////////////////////// Index: src/rc2lng/rc2lng.rc =================================================================== diff -u -ref66618c03735e362f78ddd3822a3f5c40efa366 -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/rc2lng/rc2lng.rc (.../rc2lng.rc) (revision ef66618c03735e362f78ddd3822a3f5c40efa366) +++ src/rc2lng/rc2lng.rc (.../rc2lng.rc) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,99 +1,99 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000904b0" - BEGIN - VALUE "CompanyName", "J�zef Starosczyk" - VALUE "FileDescription", "Rc2Lng" - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "InternalName", "Rc2Lng" - VALUE "LegalCopyright", "Copyright � 2003-2016" - VALUE "OriginalFilename", "Rc2Lng.exe" - VALUE "ProductName", "Rc2Lng" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x9, 1200 - END -END - - -#ifdef APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "000904b0" + BEGIN + VALUE "CompanyName", "J�zef Starosczyk" + VALUE "FileDescription", "Rc2Lng" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "Rc2Lng" + VALUE "LegalCopyright", "Copyright � 2003-2016" + VALUE "OriginalFilename", "Rc2Lng.exe" + VALUE "ProductName", "Rc2Lng" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x9, 1200 + END +END + + +#ifdef APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + Index: src/rc2lng/rc2lng.vc140.vcxproj =================================================================== diff -u -ra27d1acf1bda3c25b6dcce0d0eb0278009ce63ae -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/rc2lng/rc2lng.vc140.vcxproj (.../rc2lng.vc140.vcxproj) (revision a27d1acf1bda3c25b6dcce0d0eb0278009ce63ae) +++ src/rc2lng/rc2lng.vc140.vcxproj (.../rc2lng.vc140.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,260 +1,260 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - rc2lng - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A} - rc2lng - MFCProj - 8.1 - - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - - - Application - v120_xp - Dynamic - Unicode - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.51106.1 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - C:\dev\boost_1_56_0;$(IncludePath) - C:\dev\boost_1_56_0\lib-12.0\x32\lib;$(LibraryPath) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)64 - C:\dev\boost_1_56_0;$(IncludePath) - C:\dev\boost_1_56_0\lib-12.0\x64\lib;$(LibraryPath) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - C:\dev\boost_1_56_0;$(IncludePath) - C:\dev\boost_1_56_0\lib-12.0\x32\lib;$(LibraryPath) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)64 - C:\dev\boost_1_56_0;$(IncludePath) - C:\dev\boost_1_56_0\lib-12.0\x64\lib;$(LibraryPath) - - - - .\Release/rc2lng.tlb - - - - MaxSpeed - OnlyExplicitInline - WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - MultiThreadedDLL - true - Use - - $(IntDir)$(TargetName)_vs90.pdb - Level4 - true - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - Console - MachineX86 - - - - - X64 - .\Release/rc2lng.tlb - - - - MaxSpeed - OnlyExplicitInline - WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - MultiThreadedDLL - true - Use - - $(IntDir)$(TargetName)_vs90.pdb - Level4 - true - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - Console - MachineX64 - - - - - .\Debug/rc2lng.tlb - - - - Disabled - WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - Use - - $(IntDir)$(TargetName)_vs90.pdb - Level4 - true - EditAndContinue - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - Console - MachineX86 - - - - - X64 - .\Debug/rc2lng.tlb - - - - Disabled - WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - Use - - $(IntDir)$(TargetName)_vs90.pdb - Level4 - true - ProgramDatabase - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - Console - MachineX64 - - - - - - - Disabled - EnableFastChecks - Disabled - EnableFastChecks - MaxSpeed - MaxSpeed - - - Disabled - EnableFastChecks - Create - Disabled - EnableFastChecks - Create - MaxSpeed - Create - MaxSpeed - Create - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + rc2lng + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A} + rc2lng + MFCProj + 8.1 + + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + + + Application + v120_xp + Dynamic + Unicode + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>11.0.51106.1 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + C:\dev\boost_1_56_0;$(IncludePath) + C:\dev\boost_1_56_0\lib-12.0\x32\lib;$(LibraryPath) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)64 + C:\dev\boost_1_56_0;$(IncludePath) + C:\dev\boost_1_56_0\lib-12.0\x64\lib;$(LibraryPath) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + C:\dev\boost_1_56_0;$(IncludePath) + C:\dev\boost_1_56_0\lib-12.0\x32\lib;$(LibraryPath) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)64 + C:\dev\boost_1_56_0;$(IncludePath) + C:\dev\boost_1_56_0\lib-12.0\x64\lib;$(LibraryPath) + + + + .\Release/rc2lng.tlb + + + + MaxSpeed + OnlyExplicitInline + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Use + + $(IntDir)$(TargetName)_vs90.pdb + Level4 + true + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + Console + MachineX86 + + + + + X64 + .\Release/rc2lng.tlb + + + + MaxSpeed + OnlyExplicitInline + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Use + + $(IntDir)$(TargetName)_vs90.pdb + Level4 + true + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + Console + MachineX64 + + + + + .\Debug/rc2lng.tlb + + + + Disabled + WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + + $(IntDir)$(TargetName)_vs90.pdb + Level4 + true + EditAndContinue + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + Console + MachineX86 + + + + + X64 + .\Debug/rc2lng.tlb + + + + Disabled + WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + + $(IntDir)$(TargetName)_vs90.pdb + Level4 + true + ProgramDatabase + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + Console + MachineX64 + + + + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + MaxSpeed + MaxSpeed + + + Disabled + EnableFastChecks + Create + Disabled + EnableFastChecks + Create + MaxSpeed + Create + MaxSpeed + Create + + + + + + + + + + + + + + + + \ No newline at end of file Index: src/rc2lng/rc2lng.vc140.vcxproj.filters =================================================================== diff -u -ra27d1acf1bda3c25b6dcce0d0eb0278009ce63ae -ra4635addad389b9e117679437a3e1b64a739ea96 --- src/rc2lng/rc2lng.vc140.vcxproj.filters (.../rc2lng.vc140.vcxproj.filters) (revision a27d1acf1bda3c25b6dcce0d0eb0278009ce63ae) +++ src/rc2lng/rc2lng.vc140.vcxproj.filters (.../rc2lng.vc140.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,56 +1,56 @@ - - - - - {591a2fd9-0a77-49c8-a02b-338deff508f3} - cpp;c;cxx;rc;def;r;odl;idl;hpj;bat - - - {e0790ec6-1103-487e-a22b-3d7c844264fa} - h;hpp;hxx;hm;inl - - - {d43bbdbe-f343-46f5-beea-b5d0fb9b1c29} - ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Source Files - - + + + + + {591a2fd9-0a77-49c8-a02b-338deff508f3} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {e0790ec6-1103-487e-a22b-3d7c844264fa} + h;hpp;hxx;hm;inl + + + {d43bbdbe-f343-46f5-beea-b5d0fb9b1c29} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Source Files + + \ No newline at end of file Index: tests/test_runner/src/stdafx.cpp =================================================================== diff -u -r2e23b5892ef4d4bb1ee2c6cde893004a71a11510 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/src/stdafx.cpp (.../stdafx.cpp) (revision 2e23b5892ef4d4bb1ee2c6cde893004a71a11510) +++ tests/test_runner/src/stdafx.cpp (.../stdafx.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,8 +1,8 @@ -// stdafx.cpp : source file that includes just the standard includes -// libchcore_test.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file +// stdafx.cpp : source file that includes just the standard includes +// libchcore_test.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file Index: tests/test_runner/src/stdafx.h =================================================================== diff -u -r2e23b5892ef4d4bb1ee2c6cde893004a71a11510 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/src/stdafx.h (.../stdafx.h) (revision 2e23b5892ef4d4bb1ee2c6cde893004a71a11510) +++ tests/test_runner/src/stdafx.h (.../stdafx.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,18 +1,18 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#include "targetver.h" - -#include -#include -#include -#include -#include -#include -#include -#include "gmock/gmock.h" -#include "gtest/gtest.h" +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include +#include +#include +#include +#include +#include +#include "gmock/gmock.h" +#include "gtest/gtest.h" Index: tests/test_runner/src/targetver.h =================================================================== diff -u -r2e23b5892ef4d4bb1ee2c6cde893004a71a11510 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/src/targetver.h (.../targetver.h) (revision 2e23b5892ef4d4bb1ee2c6cde893004a71a11510) +++ tests/test_runner/src/targetver.h (.../targetver.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,13 +1,13 @@ -#pragma once - -// The following macros define the minimum required platform. The minimum required platform -// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run -// your application. The macros work by enabling all features available on platform versions up to and -// including the version specified. - -// Modify the following defines if you have to target a platform prior to the ones specified below. -// Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. -#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. -#endif - +#pragma once + +// The following macros define the minimum required platform. The minimum required platform +// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run +// your application. The macros work by enabling all features available on platform versions up to and +// including the version specified. + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. +#endif + Index: tests/test_runner/src/test_runner.cpp =================================================================== diff -u -rb712554e2b3602ce7242c7ff1cd7745b03378440 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/src/test_runner.cpp (.../test_runner.cpp) (revision b712554e2b3602ce7242c7ff1cd7745b03378440) +++ tests/test_runner/src/test_runner.cpp (.../test_runner.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,39 +1,39 @@ -// libchcore_test.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" - -int _tmain(int argc, _TCHAR* argv[]) -{ - using std::wcout; - using std::endl; - - if(argc < 2) - { - wcout << _T("Usage: TestRunner.exe ") << endl; - return 1; - } - - PCTSTR pszLibName = argv[1]; - - wcout << _T("Executing tests in: ") << pszLibName << endl; - - HMODULE module = LoadLibrary(pszLibName); - if(module) - { - typedef int(__stdcall *pfnRunTests)(int argc, TCHAR* argv[]); - - pfnRunTests pfnFunc = (pfnRunTests)::GetProcAddress(module, "_RunTests@8"); - if(!pfnFunc) - pfnFunc = (pfnRunTests)::GetProcAddress(module, "RunTests"); - if(pfnFunc) - return pfnFunc(argc, argv); - else - { - DWORD dwErr = GetLastError(); - wcout << _T("Library ") << pszLibName << _T(" does not have tests embedded. Error: ") << dwErr << endl; - } - } - else - wcout << _T("Cannot load library ") << pszLibName << endl; -} +// libchcore_test.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" + +int _tmain(int argc, _TCHAR* argv[]) +{ + using std::wcout; + using std::endl; + + if(argc < 2) + { + wcout << _T("Usage: TestRunner.exe ") << endl; + return 1; + } + + PCTSTR pszLibName = argv[1]; + + wcout << _T("Executing tests in: ") << pszLibName << endl; + + HMODULE module = LoadLibrary(pszLibName); + if(module) + { + typedef int(__stdcall *pfnRunTests)(int argc, TCHAR* argv[]); + + pfnRunTests pfnFunc = (pfnRunTests)::GetProcAddress(module, "_RunTests@8"); + if(!pfnFunc) + pfnFunc = (pfnRunTests)::GetProcAddress(module, "RunTests"); + if(pfnFunc) + return pfnFunc(argc, argv); + else + { + DWORD dwErr = GetLastError(); + wcout << _T("Library ") << pszLibName << _T(" does not have tests embedded. Error: ") << dwErr << endl; + } + } + else + wcout << _T("Cannot load library ") << pszLibName << endl; +} Index: tests/test_runner/test_runner.vcproj =================================================================== diff -u -r2e23b5892ef4d4bb1ee2c6cde893004a71a11510 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/test_runner.vcproj (.../test_runner.vcproj) (revision 2e23b5892ef4d4bb1ee2c6cde893004a71a11510) +++ tests/test_runner/test_runner.vcproj (.../test_runner.vcproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,723 +1,723 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: tests/test_runner/test_runner.vcxproj =================================================================== diff -u -r3ce97595f1867bfb53e7609d8a10e2c1d94a89a0 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/test_runner.vcxproj (.../test_runner.vcxproj) (revision 3ce97595f1867bfb53e7609d8a10e2c1d94a89a0) +++ tests/test_runner/test_runner.vcxproj (.../test_runner.vcxproj) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,359 +1,359 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - Testing Debug - Win32 - - - Testing Debug - x64 - - - Testing Release - Win32 - - - Testing Release - x64 - - - - {2AF37846-09E7-46EB-83AE-1E4C67742EE7} - test_runner - Win32Proj - 8.1 - - - - Application - v140_xp - Unicode - true - - - Application - v140_xp - Unicode - - - Application - v140_xp - Unicode - true - - - Application - v140_xp - Unicode - - - Application - v140_xp - Unicode - true - - - Application - v140_xp - Unicode - - - Application - v140_xp - Unicode - true - - - Application - v140_xp - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>14.0.24720.0 - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)$(PlatformArchitecture)d - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)$(PlatformArchitecture)d - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)$(PlatformArchitecture) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)$(PlatformArchitecture) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)$(PlatformArchitecture)d - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - true - $(ProjectName)$(PlatformArchitecture)d - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)$(PlatformArchitecture) - - - $(SolutionDir)bin\$(Configuration)\ - $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ - false - $(ProjectName)$(PlatformArchitecture) - - - - Disabled - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - EditAndContinue - - - true - Console - MachineX86 - - - - - X64 - - - Disabled - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - ProgramDatabase - - - true - Console - MachineX64 - - - - - MaxSpeed - true - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - true - Console - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - true - Console - true - true - MachineX64 - - - - - Disabled - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - EditAndContinue - - - true - Console - MachineX86 - - - - - X64 - - - Disabled - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - ProgramDatabase - - - true - Console - MachineX64 - - - - - MaxSpeed - true - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - true - Console - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - true - Console - true - true - MachineX64 - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + Testing Debug + Win32 + + + Testing Debug + x64 + + + Testing Release + Win32 + + + Testing Release + x64 + + + + {2AF37846-09E7-46EB-83AE-1E4C67742EE7} + test_runner + Win32Proj + 8.1 + + + + Application + v140_xp + Unicode + true + + + Application + v140_xp + Unicode + + + Application + v140_xp + Unicode + true + + + Application + v140_xp + Unicode + + + Application + v140_xp + Unicode + true + + + Application + v140_xp + Unicode + + + Application + v140_xp + Unicode + true + + + Application + v140_xp + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>14.0.24720.0 + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)$(PlatformArchitecture)d + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)$(PlatformArchitecture)d + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)$(PlatformArchitecture) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)$(PlatformArchitecture) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)$(PlatformArchitecture)d + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + true + $(ProjectName)$(PlatformArchitecture)d + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)$(PlatformArchitecture) + + + $(SolutionDir)bin\$(Configuration)\ + $(SolutionDir)intermediate\$(PlatformToolset)\$(Platform)\$(ProjectName)_$(Configuration)\ + false + $(ProjectName)$(PlatformArchitecture) + + + + Disabled + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + EditAndContinue + + + true + Console + MachineX86 + + + + + X64 + + + Disabled + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + ProgramDatabase + + + true + Console + MachineX64 + + + + + MaxSpeed + true + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + true + Console + true + true + MachineX86 + + + + + X64 + + + MaxSpeed + true + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + true + Console + true + true + MachineX64 + + + + + Disabled + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + EditAndContinue + + + true + Console + MachineX86 + + + + + X64 + + + Disabled + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + ProgramDatabase + + + true + Console + MachineX64 + + + + + MaxSpeed + true + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + true + Console + true + true + MachineX86 + + + + + X64 + + + MaxSpeed + true + ..\..\ext\gmock\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_BIND_TO_CURRENT_VCLIBS_VERSION=1;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + true + Console + true + true + MachineX64 + + + + + Create + Create + Create + Create + Create + Create + Create + Create + + + + + + + + + + \ No newline at end of file Index: tests/test_runner/test_runner.vcxproj.filters =================================================================== diff -u -r3ce97595f1867bfb53e7609d8a10e2c1d94a89a0 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/test_runner/test_runner.vcxproj.filters (.../test_runner.vcxproj.filters) (revision 3ce97595f1867bfb53e7609d8a10e2c1d94a89a0) +++ tests/test_runner/test_runner.vcxproj.filters (.../test_runner.vcxproj.filters) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,31 +1,31 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;h;hpp;hxx;hm;inl;inc;xsd - - - {ce1a86bb-9ec1-468c-a355-70067f9fa6c4} - - - {61ea4548-fbba-4b3a-b89b-b3f613d85220} - - - - - Source Files\Main - - - Source Files\Main - - - - - Source Files\Main - - - Source Files\Main - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;h;hpp;hxx;hm;inl;inc;xsd + + + {ce1a86bb-9ec1-468c-a355-70067f9fa6c4} + + + {61ea4548-fbba-4b3a-b89b-b3f613d85220} + + + + + Source Files\Main + + + Source Files\Main + + + + + Source Files\Main + + + Source Files\Main + + \ No newline at end of file Index: tests/tests_shared/TestsExports.cpp =================================================================== diff -u -r2f310b20f03fedcda10a7bf0df639c5c2b21db65 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tests/tests_shared/TestsExports.cpp (.../TestsExports.cpp) (revision 2f310b20f03fedcda10a7bf0df639c5c2b21db65) +++ tests/tests_shared/TestsExports.cpp (.../TestsExports.cpp) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,91 +1,91 @@ -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include -#include -#include - -#ifdef TESTING - -class TFailedOutputPrinter : public ::testing::EmptyTestEventListener -{ - virtual void OnTestStart(const ::testing::TestInfo& test_info) - { - m_strTestName = str(boost::format("%1%.%2%") % test_info.test_case_name() % test_info.name()); - } - - virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) - { - if(test_part_result.failed()) - { - char* pszFailureText = NULL; - if(test_part_result.fatally_failed()) - pszFailureText = "FATAL"; - else - pszFailureText = "NON-FATAL"; - - std::string strMsg = test_part_result.message() ? test_part_result.message() : ""; - boost::replace_all(strMsg, "\n", "\n "); - - printf("**[%s FAILURE]** Unit test %s failed\n %s(%ld) : %s\n", - pszFailureText, - m_strTestName.c_str(), - test_part_result.file_name() ? test_part_result.file_name() : "Unknown location", - test_part_result.line_number() < 0 ? 0 : test_part_result.line_number(), - strMsg.c_str()); - } - } - - virtual void OnTestProgramEnd(const ::testing::UnitTest& unit_test) - { - if(unit_test.Failed()) - { - printf("Unit tests execution FAILED (successful: %ld, failed: %ld, elapsed time: %I64d ms)\n>\n", - unit_test.successful_test_count(), - unit_test.failed_test_count(), - unit_test.elapsed_time()); - } - else - { - printf("Unit tests execution succeeded (successful: %ld, failed: %ld, elapsed time: %I64d ms)\n>\n", - unit_test.successful_test_count(), - unit_test.failed_test_count(), - unit_test.elapsed_time()); - } - } - -private: - std::string m_strTestName; -}; - -#ifdef _CONSOLE -int _tmain(int argc, _TCHAR* argv[]) -#else -extern "C" -__declspec(dllexport) int __stdcall RunTests(int argc, TCHAR* argv[]) -#endif -{ - testing::InitGoogleMock(&argc, argv); - ::testing::FLAGS_gtest_death_test_style = "fast"; - ::testing::FLAGS_gtest_print_time = 1; - - bool bUseStdFormat = false; - for(int iIndex = 1; iIndex < argc; ++iIndex) - { - if(_tcscmp(argv[ iIndex ], _T("--stdformat")) == 0) - { - bUseStdFormat = true; - break; - } - } - - if(!bUseStdFormat) - { - ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); - delete listeners.Release(listeners.default_result_printer()); - listeners.Append(new TFailedOutputPrinter); - } - - return RUN_ALL_TESTS(); -} - -#endif +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include +#include +#include + +#ifdef TESTING + +class TFailedOutputPrinter : public ::testing::EmptyTestEventListener +{ + virtual void OnTestStart(const ::testing::TestInfo& test_info) + { + m_strTestName = str(boost::format("%1%.%2%") % test_info.test_case_name() % test_info.name()); + } + + virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) + { + if(test_part_result.failed()) + { + char* pszFailureText = NULL; + if(test_part_result.fatally_failed()) + pszFailureText = "FATAL"; + else + pszFailureText = "NON-FATAL"; + + std::string strMsg = test_part_result.message() ? test_part_result.message() : ""; + boost::replace_all(strMsg, "\n", "\n "); + + printf("**[%s FAILURE]** Unit test %s failed\n %s(%ld) : %s\n", + pszFailureText, + m_strTestName.c_str(), + test_part_result.file_name() ? test_part_result.file_name() : "Unknown location", + test_part_result.line_number() < 0 ? 0 : test_part_result.line_number(), + strMsg.c_str()); + } + } + + virtual void OnTestProgramEnd(const ::testing::UnitTest& unit_test) + { + if(unit_test.Failed()) + { + printf("Unit tests execution FAILED (successful: %ld, failed: %ld, elapsed time: %I64d ms)\n>\n", + unit_test.successful_test_count(), + unit_test.failed_test_count(), + unit_test.elapsed_time()); + } + else + { + printf("Unit tests execution succeeded (successful: %ld, failed: %ld, elapsed time: %I64d ms)\n>\n", + unit_test.successful_test_count(), + unit_test.failed_test_count(), + unit_test.elapsed_time()); + } + } + +private: + std::string m_strTestName; +}; + +#ifdef _CONSOLE +int _tmain(int argc, _TCHAR* argv[]) +#else +extern "C" +__declspec(dllexport) int __stdcall RunTests(int argc, TCHAR* argv[]) +#endif +{ + testing::InitGoogleMock(&argc, argv); + ::testing::FLAGS_gtest_death_test_style = "fast"; + ::testing::FLAGS_gtest_print_time = 1; + + bool bUseStdFormat = false; + for(int iIndex = 1; iIndex < argc; ++iIndex) + { + if(_tcscmp(argv[ iIndex ], _T("--stdformat")) == 0) + { + bUseStdFormat = true; + break; + } + } + + if(!bUseStdFormat) + { + ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new TFailedOutputPrinter); + } + + return RUN_ALL_TESTS(); +} + +#endif Index: tools.sln =================================================================== diff -u -ra27d1acf1bda3c25b6dcce0d0eb0278009ce63ae -ra4635addad389b9e117679437a3e1b64a739ea96 --- tools.sln (.../tools.sln) (revision a27d1acf1bda3c25b6dcce0d0eb0278009ce63ae) +++ tools.sln (.../tools.sln) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,58 +1,58 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rc2lng", "src\rc2lng\rc2lng.vc140.vcxproj", "{10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_runner", "tests\test_runner\test_runner.vcxproj", "{2AF37846-09E7-46EB-83AE-1E4C67742EE7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - Testing Debug|Win32 = Testing Debug|Win32 - Testing Debug|x64 = Testing Debug|x64 - Testing Release|Win32 = Testing Release|Win32 - Testing Release|x64 = Testing Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|Win32.ActiveCfg = Debug|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|Win32.Build.0 = Debug|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|x64.ActiveCfg = Debug|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|x64.Build.0 = Debug|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|Win32.ActiveCfg = Release|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|Win32.Build.0 = Release|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|x64.ActiveCfg = Release|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|x64.Build.0 = Release|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|Win32.ActiveCfg = Debug|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|Win32.Build.0 = Debug|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|x64.ActiveCfg = Debug|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|x64.Build.0 = Debug|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|Win32.ActiveCfg = Release|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|Win32.Build.0 = Release|Win32 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|x64.ActiveCfg = Release|x64 - {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|x64.Build.0 = Release|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|Win32.ActiveCfg = Debug|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|Win32.Build.0 = Debug|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|x64.ActiveCfg = Debug|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|x64.Build.0 = Debug|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|Win32.ActiveCfg = Release|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|Win32.Build.0 = Release|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|x64.ActiveCfg = Release|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|x64.Build.0 = Release|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|Win32.ActiveCfg = Testing Debug|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|Win32.Build.0 = Testing Debug|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|x64.ActiveCfg = Testing Debug|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|x64.Build.0 = Testing Debug|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|Win32.ActiveCfg = Testing Release|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|Win32.Build.0 = Testing Release|Win32 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|x64.ActiveCfg = Testing Release|x64 - {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|x64.Build.0 = Testing Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.24720.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rc2lng", "src\rc2lng\rc2lng.vc140.vcxproj", "{10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_runner", "tests\test_runner\test_runner.vcxproj", "{2AF37846-09E7-46EB-83AE-1E4C67742EE7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + Testing Debug|Win32 = Testing Debug|Win32 + Testing Debug|x64 = Testing Debug|x64 + Testing Release|Win32 = Testing Release|Win32 + Testing Release|x64 = Testing Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|Win32.ActiveCfg = Debug|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|Win32.Build.0 = Debug|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|x64.ActiveCfg = Debug|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Debug|x64.Build.0 = Debug|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|Win32.ActiveCfg = Release|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|Win32.Build.0 = Release|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|x64.ActiveCfg = Release|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Release|x64.Build.0 = Release|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|Win32.ActiveCfg = Debug|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|Win32.Build.0 = Debug|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|x64.ActiveCfg = Debug|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Debug|x64.Build.0 = Debug|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|Win32.ActiveCfg = Release|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|Win32.Build.0 = Release|Win32 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|x64.ActiveCfg = Release|x64 + {10FB6B7E-81A1-47F9-BC6F-7017E5695D3A}.Testing Release|x64.Build.0 = Release|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|Win32.ActiveCfg = Debug|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|Win32.Build.0 = Debug|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|x64.ActiveCfg = Debug|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Debug|x64.Build.0 = Debug|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|Win32.ActiveCfg = Release|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|Win32.Build.0 = Release|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|x64.ActiveCfg = Release|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Release|x64.Build.0 = Release|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|Win32.ActiveCfg = Testing Debug|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|Win32.Build.0 = Testing Debug|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|x64.ActiveCfg = Testing Debug|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Debug|x64.Build.0 = Testing Debug|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|Win32.ActiveCfg = Testing Release|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|Win32.Build.0 = Testing Release|Win32 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|x64.ActiveCfg = Testing Release|x64 + {2AF37846-09E7-46EB-83AE-1E4C67742EE7}.Testing Release|x64.Build.0 = Testing Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal Index: tools/boost-build32.bat =================================================================== diff -u -rc62bdde7e4f25ca4051da3a8b71397bdf7f2b354 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tools/boost-build32.bat (.../boost-build32.bat) (revision c62bdde7e4f25ca4051da3a8b71397bdf7f2b354) +++ tools/boost-build32.bat (.../boost-build32.bat) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,11 +1,11 @@ -rem This scripts updates the environment (that needs to be previously set up for building with vcvarsall) -rem so that the boost will build with xp compatibility in VS2013. -rem Execute this script in the boost directory. - -set INCLUDE=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Include;%INCLUDE% -set PATH=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Bin;%PATH% -set CL=/D_USING_V110_SDK71_;%CL% -set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib;%LIB% -set LINK=/SUBSYSTEM:CONSOLE,5.01 %LINK% - -b2 -j 4 --toolset=msvc-12.0 --link=static --threading=multi --runtime-link=shared address-model=32 define=_BIND_TO_CURRENT_VCLIBS_VERSION define=BOOST_USE_WINAPI_VERSION=0x0501 define=BOOST_UUID_NO_SIMD cxxflags=/arch:IA32 --build-type=complete --stagedir=lib-12.0\x32 stage +rem This scripts updates the environment (that needs to be previously set up for building with vcvarsall) +rem so that the boost will build with xp compatibility in VS2013. +rem Execute this script in the boost directory. + +set INCLUDE=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Include;%INCLUDE% +set PATH=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Bin;%PATH% +set CL=/D_USING_V110_SDK71_;%CL% +set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib;%LIB% +set LINK=/SUBSYSTEM:CONSOLE,5.01 %LINK% + +b2 -j 4 --toolset=msvc-12.0 --link=static --threading=multi --runtime-link=shared address-model=32 define=_BIND_TO_CURRENT_VCLIBS_VERSION define=BOOST_USE_WINAPI_VERSION=0x0501 define=BOOST_UUID_NO_SIMD cxxflags=/arch:IA32 --build-type=complete --stagedir=lib-12.0\x32 stage Index: tools/boost-build64.bat =================================================================== diff -u -r146b40c45c5406090ee3979f12422e04f1f36ce2 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tools/boost-build64.bat (.../boost-build64.bat) (revision 146b40c45c5406090ee3979f12422e04f1f36ce2) +++ tools/boost-build64.bat (.../boost-build64.bat) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,11 +1,11 @@ -rem This scripts updates the environment (that needs to be previously set up for building with vcvarsall) -rem so that the boost will build with xp compatibility in VS2013. -rem Execute this script in the boost directory. - -set INCLUDE=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Include;%INCLUDE% -set PATH=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Bin;%PATH% -set CL=/D_USING_V110_SDK71_;%CL% -set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib\x64;%LIB% -set LINK=/SUBSYSTEM:CONSOLE,5.02 %LINK% - -b2 -j 4 --toolset=msvc-12.0 --link=static --threading=multi --runtime-link=shared address-model=64 define=_BIND_TO_CURRENT_VCLIBS_VERSION define=BOOST_USE_WINAPI_VERSION=0x0501 --build-type=complete --stagedir=lib-12.0\x64 stage +rem This scripts updates the environment (that needs to be previously set up for building with vcvarsall) +rem so that the boost will build with xp compatibility in VS2013. +rem Execute this script in the boost directory. + +set INCLUDE=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Include;%INCLUDE% +set PATH=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Bin;%PATH% +set CL=/D_USING_V110_SDK71_;%CL% +set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib\x64;%LIB% +set LINK=/SUBSYSTEM:CONSOLE,5.02 %LINK% + +b2 -j 4 --toolset=msvc-12.0 --link=static --threading=multi --runtime-link=shared address-model=64 define=_BIND_TO_CURRENT_VCLIBS_VERSION define=BOOST_USE_WINAPI_VERSION=0x0501 --build-type=complete --stagedir=lib-12.0\x64 stage Index: tools/restart_explorer.bat =================================================================== diff -u -r3ff19634b446dd3fbaab6575e162b1cd65c4c029 -ra4635addad389b9e117679437a3e1b64a739ea96 --- tools/restart_explorer.bat (.../restart_explorer.bat) (revision 3ff19634b446dd3fbaab6575e162b1cd65c4c029) +++ tools/restart_explorer.bat (.../restart_explorer.bat) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,3 +1,3 @@ -@ECHO OFF -taskkill /F /IM explorer.exe -start explorer.exe +@ECHO OFF +taskkill /F /IM explorer.exe +start explorer.exe Index: va_stdafx.h =================================================================== diff -u -rbef894e38e5c1486824787cf8c47a87a0828b228 -ra4635addad389b9e117679437a3e1b64a739ea96 --- va_stdafx.h (.../va_stdafx.h) (revision bef894e38e5c1486824787cf8c47a87a0828b228) +++ va_stdafx.h (.../va_stdafx.h) (revision a4635addad389b9e117679437a3e1b64a739ea96) @@ -1,30 +1,30 @@ -/////////////////////////////////////////////////////////////////////////// -// googletest macros replacement for visual assist - -#define TEST_F(fixture, test_name)\ -struct Test_##fixture##_##test_name## : public fixture\ -{\ - void Exec();\ -};\ -void Test_##fixture##_##test_name##::Exec() - - -#define TEST(test_case_name, test_name)\ -struct Test_##test_case_name##_##test_name##\ -{\ - void Exec();\ -};\ -void Test_##test_case_name##_##test_name##::Exec() - -#define EXPECT_EQ(a, b) (a) == (b) -#define EXPECT_THROW(operation, exc)\ -do\ -{\ - try\ - {\ - operation;\ - }\ - catch(const exc&)\ - {\ - }\ -} while(false) +/////////////////////////////////////////////////////////////////////////// +// googletest macros replacement for visual assist + +#define TEST_F(fixture, test_name)\ +struct Test_##fixture##_##test_name## : public fixture\ +{\ + void Exec();\ +};\ +void Test_##fixture##_##test_name##::Exec() + + +#define TEST(test_case_name, test_name)\ +struct Test_##test_case_name##_##test_name##\ +{\ + void Exec();\ +};\ +void Test_##test_case_name##_##test_name##::Exec() + +#define EXPECT_EQ(a, b) (a) == (b) +#define EXPECT_THROW(operation, exc)\ +do\ +{\ + try\ + {\ + operation;\ + }\ + catch(const exc&)\ + {\ + }\ +} while(false)