diff --git a/Src/Common/Types/int.h b/Src/Common/Types/int.h deleted file mode 100644 index 82fa00930..000000000 --- a/Src/Common/Types/int.h +++ /dev/null @@ -1,33 +0,0 @@ -// int.h -// -///////////////////////////////////////////////////////////////////////////// -// -// Copyright (c) 2001-2004 David Ward -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef __int_h__ -#define __int_h__ - -#ifdef _WIN32 - -typedef __int64 int64; -typedef unsigned __int64 uint64; -typedef int int32; -typedef unsigned int uint32; - -#else - -typedef long long int int64; -typedef unsigned long long int uint64; -typedef int int32; -typedef unsigned int uint32; - -#endif - -#include - -const int64 int64_max = std::numeric_limits::max(); -const int64 int64_min = std::numeric_limits::min(); - -#endif diff --git a/Src/DasherCore/Alphabet/AlphabetMap.cpp b/Src/DasherCore/Alphabet/AlphabetMap.cpp index bca600ae9..4e85d12f7 100644 --- a/Src/DasherCore/Alphabet/AlphabetMap.cpp +++ b/Src/DasherCore/Alphabet/AlphabetMap.cpp @@ -97,24 +97,12 @@ inline int CAlphabetMap::SymbolStream::findNext() { if (int numChars = m_utf8_count_array[buf[pos]]) { if (pos+numChars > len) { //no more bytes in file (would have tried to read earlier), but not enough for char - if (m_pMsgs) { - const char *msg(_("File ends with incomplete UTF-8 character beginning 0x%x (expecting %i bytes but only %i)")); - char *mbuf(new char[strlen(msg) + 4]); - sprintf(mbuf, msg, static_cast(buf[pos] & 0xff), numChars, len-pos); - m_pMsgs->Message(mbuf,false); - delete[] mbuf; - } + if(m_pMsgs) m_pMsgs->FormatMessage("File ends with incomplete UTF-8 character beginning 0x%x (expecting %i bytes but only %i)", static_cast(buf[pos] & 0xff), numChars, len-pos); return 0; } return numChars; } - if (m_pMsgs) { - const char *msg(_("Read invalid UTF-8 character 0x%x")); - char *mbuf(new char[strlen(msg) + 2]); - sprintf(mbuf, msg, static_cast(buf[pos] & 0xff)); - m_pMsgs->Message(mbuf,false); - delete[] mbuf; - } + if (m_pMsgs) m_pMsgs->FormatMessage("Read invalid UTF-8 character 0x%x", static_cast(buf[pos] & 0xff)); ++pos; } } diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index e6939300a..d19161c65 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -33,7 +33,6 @@ #include "FileWordGenerator.h" #include -#include using namespace Dasher; @@ -51,32 +50,30 @@ CAlphabetManager::CAlphabetManager(CSettingsStore *pSettingsStore, CDasherInterf { m_pSettingsStore->OnPreParameterChange.Subscribe(this, [this](Parameter parameter, const std::variant& newValue) { - switch(parameter) { - case SP_ALPHABET_ID: - const std::string value = std::get(newValue); - // Cycle the alphabet history - std::vector newHistory; - newHistory.push_back(m_pSettingsStore->GetStringParameter(SP_ALPHABET_ID)); - std::string v; - if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_1)) != value) - newHistory.push_back(v); - if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_2)) != value) - newHistory.push_back(v); - if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_3)) != value) - newHistory.push_back(v); - if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_4)) != value) - newHistory.push_back(v); - - // Fill empty slots. - while (newHistory.size() < 4) - newHistory.push_back(""); - - m_pSettingsStore->SetStringParameter(SP_ALPHABET_1, newHistory[0]); - m_pSettingsStore->SetStringParameter(SP_ALPHABET_2, newHistory[1]); - m_pSettingsStore->SetStringParameter(SP_ALPHABET_3, newHistory[2]); - m_pSettingsStore->SetStringParameter(SP_ALPHABET_4, newHistory[3]); - break; - } + if(parameter == SP_ALPHABET_ID){ + const std::string value = std::get(newValue); + // Cycle the alphabet history + std::vector newHistory; + newHistory.push_back(m_pSettingsStore->GetStringParameter(SP_ALPHABET_ID)); + std::string v; + if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_1)) != value) + newHistory.push_back(v); + if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_2)) != value) + newHistory.push_back(v); + if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_3)) != value) + newHistory.push_back(v); + if ((v = m_pSettingsStore->GetStringParameter(SP_ALPHABET_4)) != value) + newHistory.push_back(v); + + // Fill empty slots. + while (newHistory.size() < 4) + newHistory.push_back(""); + + m_pSettingsStore->SetStringParameter(SP_ALPHABET_1, newHistory[0]); + m_pSettingsStore->SetStringParameter(SP_ALPHABET_2, newHistory[1]); + m_pSettingsStore->SetStringParameter(SP_ALPHABET_3, newHistory[2]); + m_pSettingsStore->SetStringParameter(SP_ALPHABET_4, newHistory[3]); + } }); } @@ -235,7 +232,7 @@ CWordGeneratorBase *CAlphabetManager::GetGameWords() { ///TRANSLATORS: the string "GameTextFile" is the name of a setting in gsettings /// (or equivalent), and should not be translated. The %s is the value of that /// setting (this message displayed only if the user has provided a value) - m_pInterface->FormatMessageWithString(_("Note: GameTextFile setting specifies game sentences file '%s' but this does not exist"),gtf.c_str()); + m_pInterface->FormatMessage("Note: GameTextFile setting specifies game sentences file '%s' but this does not exist", gtf.c_str()); } pGen->setAcceptUser(false); m_pInterface->ScanFiles(pGen, m_pAlphabet->GetTrainingFile()); @@ -616,12 +613,12 @@ void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, const SGroupInfo * bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; - //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") + //uint64_t is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * - static_cast(CDasherModel::NORMALIZATION)) / + static_cast(CDasherModel::NORMALIZATION)) / iRange; unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * - static_cast(CDasherModel::NORMALIZATION)) / + static_cast(CDasherModel::NORMALIZATION)) / iRange; if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i) : CreateSymbolNode(pParent, i); diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index c704a27fc..00e0ad79a 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -66,7 +66,7 @@ namespace Dasher { CNodeManager* mgr() const override; ///Rebuilds this node's parent by recreating the previous 'root' node, /// then calling RebuildForwardsFromAncestor - CDasherNode *RebuildParent(); + CDasherNode *RebuildParent() override; ///Called to build a symbol (leaf) node which is a descendant of the symbol or root node preceding this. /// Default implementation just calls the manager's CreateSymbolNode method to create a new node, /// but subclasses can override to graft themselves into the appropriate point beneath the previous node. @@ -164,11 +164,11 @@ namespace Dasher { /// Uniquely, a paragraph symbol can enter two distinct unicode characters /// (i.e. '\r' and '\n'); every other symbol enters only a single /// unicode char, even if that might take >1 octet. - int numChars(); + int numChars() override; void TrainSymbol(); void UntrainSymbol(); ///Override: true iff pGroup encloses this symbol (according to its start/end symbol#) - bool isInGroup(const SGroupInfo *pGroup); + bool isInGroup(const SGroupInfo *pGroup) override; public: double SpeedMul() override; @@ -182,20 +182,20 @@ namespace Dasher { CGroupNode(int iOffset, CDasherScreen::Label* pLabel, CAlphabetManager* pMgr, const SGroupInfo* pGroup); ///Override: if m_pGroup==NULL, i.e. whole/root-of alphabet, cannot rebuild. - virtual CDasherNode *RebuildParent(); + virtual CDasherNode *RebuildParent() override; ///Create children of this group node, by traversing the section of the alphabet /// indicated by m_pGroup. - virtual void PopulateChildren(); - virtual int ExpectedNumChildren(); + virtual void PopulateChildren() override; + virtual int ExpectedNumChildren() override; - virtual bool GameSearchNode(symbol sym); - std::vector *GetProbInfo(); + virtual bool GameSearchNode(symbol sym) override; + std::vector *GetProbInfo() override; ///Override: if the group to create is the same as this node's group, return this node instead of creating a new one - virtual CDasherNode *RebuildGroup(CAlphNode* pParent, const SGroupInfo* pInfo); + virtual CDasherNode *RebuildGroup(CAlphNode* pParent, const SGroupInfo* pInfo) override; protected: ///Override: true if pGroup encloses this one (by start/end symbol#) - bool isInGroup(const SGroupInfo *pGroup); + bool isInGroup(const SGroupInfo *pGroup) override; public: const ColorPalette::Color& getLabelColor(const ColorPalette* colorPalette) override; diff --git a/Src/DasherCore/ColorIO.cpp b/Src/DasherCore/ColorIO.cpp index 545735712..2169cf87e 100644 --- a/Src/DasherCore/ColorIO.cpp +++ b/Src/DasherCore/ColorIO.cpp @@ -129,7 +129,7 @@ void CColorIO::RelinkParents() std::string allVisited; for(std::string& s : visited) allVisited += s + "->"; allVisited += current->ParentPalette->PaletteName; - m_pMsgs->FormatMessageWithString("Found cycle while parsing color-scheme parenting: %s", allVisited.c_str()); + m_pMsgs->FormatMessage("Found cycle while parsing color-scheme parenting: %s", allVisited.c_str()); KnownPalettes.erase(current->ParentPalette->PaletteName); RelinkParents(); //relink as now a palette was removed return; diff --git a/Src/DasherCore/ConversionManager.h b/Src/DasherCore/ConversionManager.h index 921aadeb4..36ef32882 100644 --- a/Src/DasherCore/ConversionManager.h +++ b/Src/DasherCore/ConversionManager.h @@ -81,33 +81,33 @@ namespace Dasher { class CConvNode : public CDasherNode { public: - CConversionManager *mgr() const {return m_pMgr;} + CConversionManager *mgr() const override {return m_pMgr;} CConvNode(int iOffset, CDasherScreen::Label *pLabel, CConversionManager *pMgr); /// /// Provide children for the supplied node /// - virtual void PopulateChildren(); - virtual int ExpectedNumChildren(); - virtual void SetFlag(int iFlag, bool bValue); + virtual void PopulateChildren() override; + virtual int ExpectedNumChildren() override; + virtual void SetFlag(int iFlag, bool bValue) override; virtual ~CConvNode(); ///Attempts to fill vContextSymbols with the context that would exist _after_ this node has been entered - void GetContext(CDasherInterfaceBase *pInterface, const CAlphabetMap *pAlphabetMap, std::vector &vContextSymbols, int iOffset, int iLength); + void GetContext(CDasherInterfaceBase *pInterface, const CAlphabetMap *pAlphabetMap, std::vector &vContextSymbols, int iOffset, int iLength) override; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// - virtual void Do(); + virtual void Do() override; /// /// Called when a node is left backwards /// - virtual void Undo(); + virtual void Undo() override; const ColorPalette::Color& getLabelColor(const ColorPalette* colorPalette) override; const ColorPalette::Color& getOutlineColor(const ColorPalette* colorPalette) override; const ColorPalette::Color& getNodeColor(const ColorPalette* colorPalette) override; diff --git a/Src/DasherCore/DasherButtons.cpp b/Src/DasherCore/DasherButtons.cpp index 1324c2d24..0ae5e8a1e 100644 --- a/Src/DasherCore/DasherButtons.cpp +++ b/Src/DasherCore/DasherButtons.cpp @@ -6,7 +6,6 @@ #include "DasherButtons.h" #include "DasherScreen.h" #include "DasherInterfaceBase.h" -#include using namespace Dasher; @@ -31,21 +30,22 @@ void CDasherButtons::KeyDown(unsigned long iTime, Keys::VirtualKey Key, CDasherV if(m_bMenu) { switch(Key) { - case Keys::Button_1: - case Keys::Button_4: - m_bDecorationChanged = true; - ++iActiveBox; - if(iActiveBox == m_iNumBoxes) - iActiveBox = 0; - break; - case Keys::Button_2: - case Keys::Button_3: - case Keys::Primary_Input: - m_bDecorationChanged = true; - ScheduleZoom(pModel, m_pBoxes[iActiveBox].iTop, m_pBoxes[iActiveBox].iBottom); - if(iActiveBox != m_iNumBoxes-1) - iActiveBox = 0; - break; + case Keys::Button_1: + case Keys::Button_4: + m_bDecorationChanged = true; + ++iActiveBox; + if(iActiveBox == m_iNumBoxes) + iActiveBox = 0; + break; + case Keys::Button_2: + case Keys::Button_3: + case Keys::Primary_Input: + m_bDecorationChanged = true; + ScheduleZoom(pModel, m_pBoxes[iActiveBox].iTop, m_pBoxes[iActiveBox].iBottom); + if(iActiveBox != m_iNumBoxes-1) + iActiveBox = 0; + break; + default: break; } } else { @@ -55,14 +55,15 @@ void CDasherButtons::KeyDown(unsigned long iTime, Keys::VirtualKey Key, CDasherV } void CDasherButtons::DirectKeyDown(unsigned long iTime, Keys::VirtualKey Key, CDasherView *pView, CDasherModel *pModel) { - if(Key == Keys::Primary_Input) // Ignore mouse events - return; - if(Key == Keys::Button_1) - iActiveBox = m_iNumBoxes - 1; - else if(Key <= m_iNumBoxes) - iActiveBox = Key-2; - else - iActiveBox = m_iNumBoxes-2; + if(Key == Keys::Primary_Input) return; // Ignore mouse events + + if(Key == Keys::Button_1) { + iActiveBox = m_iNumBoxes - 1; + } else if(Key <= m_iNumBoxes) { + iActiveBox = Key-2; + } else { + iActiveBox = m_iNumBoxes-2; + } ScheduleZoom(pModel, m_pBoxes[iActiveBox].iTop,m_pBoxes[iActiveBox].iBottom); } diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index a997994e2..471e4aee5 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -54,11 +54,11 @@ #include "FileUtils.h" #include "SmoothingFilter.h" #include "../DasherCore/FileLogger.h" -#ifdef _DEBUG -const eLogLevel g_iLogLevel = logDEBUG; +#ifndef NDEBUG +const eLogLevel g_iLogLevel = eLogLevel::logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else -const eLogLevel g_iLogLevel = logNORMAL; +const eLogLevel g_iLogLevel = eLogLevel::logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif @@ -334,7 +334,7 @@ void CDasherInterfaceBase::EnterGameMode(CGameModule *pGameModule) { } else { ///TRANSLATORS: %s is the name of the alphabet; the string "GameTextFile" /// refers to a setting name in gsettings or equivalent, and should not be translated. - FormatMessageWithString(_("Could not find game sentences file for %s - check alphabet definition, or override with GameTextFile setting"), + FormatMessage("Could not find game sentences file for %s - check alphabet definition, or override with GameTextFile setting", m_pNCManager->GetAlphabet()->GetID().c_str()); delete pGameModule; //does nothing if null. } @@ -775,20 +775,21 @@ void CDasherInterfaceBase::CreateModules() { void CDasherInterfaceBase::GetPermittedValues(Parameter parameter, std::vector &vList) { // TODO: Deprecate direct calls to these functions switch (parameter) { - case SP_ALPHABET_ID: - DASHER_ASSERT(m_AlphIO != NULL); - m_AlphIO->GetAlphabets(&vList); - break; - case SP_COLOUR_ID: - DASHER_ASSERT(m_ColourIO != NULL); - m_ColorIO->GetKnownPalettes(&vList); - break; - case SP_INPUT_FILTER: - m_pModuleManager->ListInputMethodModules(vList); - break; - case SP_INPUT_DEVICE: - m_pModuleManager->ListInputDeviceModules(vList); - break; + case SP_ALPHABET_ID: + DASHER_ASSERT(m_AlphIO != NULL); + m_AlphIO->GetAlphabets(&vList); + break; + case SP_COLOUR_ID: + DASHER_ASSERT(m_ColourIO != NULL); + m_ColorIO->GetKnownPalettes(&vList); + break; + case SP_INPUT_FILTER: + m_pModuleManager->ListInputMethodModules(vList); + break; + case SP_INPUT_DEVICE: + m_pModuleManager->ListInputDeviceModules(vList); + break; + default: break; } } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 9aee2c957..9a74b9190 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -20,10 +20,10 @@ #include "DasherModel.h" #include "DasherView.h" -#include "Parameters.h" #include "NodeCreationManager.h" #include +#include using namespace Dasher; @@ -50,9 +50,8 @@ CDasherModel::CDasherModel() { m_dAddProb = 0.003; - m_Rootmin_min = int64_min / NORMALIZATION / 2; - m_Rootmax_max = int64_max / NORMALIZATION / 2; - + m_Rootmin_min = std::numeric_limits::min() / NORMALIZATION / 2; + m_Rootmax_max = std::numeric_limits::max() / NORMALIZATION / 2; } CDasherModel::~CDasherModel() { @@ -106,7 +105,7 @@ void CDasherModel::Make_root(CDasherNode *pNewRoot) { for(std::deque >::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { //Some of these co-ordinate pairs can be bigger than m_Rootmin_min - m_Rootmax_max, // hence using unsigned type... - const uint64 r = it->second - it->first; + const uint64_t r = it->second - it->first; it->second = it->first + (r * m_Root->Hbnd()) / NORMALIZATION; it->first += (r * m_Root->Lbnd()) / NORMALIZATION; } diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 472eeb678..66290e0d3 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -22,14 +22,12 @@ #define __DasherModel_h__ #include -#include #include "../Common/NoClones.h" #include "DasherNode.h" #include "DasherTypes.h" #include "Event.h" #include "ExpansionPolicy.h" -#include "SettingsStore.h" namespace Dasher { class CDasherModel; diff --git a/Src/DasherCore/DasherTypes.h b/Src/DasherCore/DasherTypes.h index d6558399f..a351ae8bb 100644 --- a/Src/DasherCore/DasherTypes.h +++ b/Src/DasherCore/DasherTypes.h @@ -33,18 +33,19 @@ // new word and don't use underscores (except as above). // -#include "../Common/Types/int.h" #include #include +#include +//Some typedefs to not having to change this in all of the DasherCore namespace Dasher { // DasherModel co-ordinates are of type myint - typedef int64 myint; - typedef int64 dasherint; + typedef int64_t myint; + typedef int64_t dasherint; // All screen co-ordinates are of type screenint - typedef int32 screenint; + typedef int32_t screenint; // Using a signed symbol type allows "Out of band" ie negative {{{ // values to be used to flag non-symbol data. For example commands diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index 0c739390e..16f840542 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -726,7 +726,7 @@ void CDasherViewSquare::DisjointRender(CDasherNode* pRender, myint y1, myint y2, // Lastly, draw the outline if (m_pSettingsStore->GetLongParameter(LP_OUTLINE_WIDTH) && !pRender->getOutlineColor(m_pColorPalette).isFullyTransparent()) { - DasherDrawRectangle(std::min(Range, visibleRegion.maxX), std::max(y1, visibleRegion.minY), 0, std::min(y2, visibleRegion.maxY), ColorPalette::noColor, pRender->getOutlineColor(m_pColorPalette), abs(m_pSettingsStore->GetLongParameter(LP_OUTLINE_WIDTH))); + DasherDrawRectangle(std::min(Range, visibleRegion.maxX), std::max(y1, visibleRegion.minY), 0, std::min(y2, visibleRegion.maxY), ColorPalette::noColor, pRender->getOutlineColor(m_pColorPalette), labs(m_pSettingsStore->GetLongParameter(LP_OUTLINE_WIDTH))); } } @@ -835,8 +835,7 @@ void CDasherViewSquare::NewRender(CDasherNode* pCurrentNode, myint y1, myint y2, { nodeDepth.extrusionLevel = parentDepth.extrusionLevel; //Use same level as node before nodeDepth.groupRecursionDepth++; - } - else + } else { nodeDepth.groupRecursionDepth = 0; } @@ -879,7 +878,7 @@ void CDasherViewSquare::NewRender(CDasherNode* pCurrentNode, myint y1, myint y2, if (!pCurrentNode->getNodeColor(m_pColorPalette).isFullyTransparent()) { //outline width 0 = fill only; >0 = fill + outline; <0 = outline only - const int line_width = abs(m_pSettingsStore->GetLongParameter(LP_OUTLINE_WIDTH)); + const int line_width = labs(m_pSettingsStore->GetLongParameter(LP_OUTLINE_WIDTH)); const ColorPalette::Color& fill_color = line_width < 0 ? ColorPalette::noColor : (m_pSettingsStore->GetBoolParameter(BP_SIMULATE_TRANSPARENCY) ? SimulateTransparency(pCurrentNode) : pCurrentNode->getNodeColor(m_pColorPalette)); const ColorPalette::Color& outline_color = line_width == 0 ? ColorPalette::noColor : pCurrentNode->getOutlineColor(m_pColorPalette); diff --git a/Src/DasherCore/DemoFilter.cpp b/Src/DasherCore/DemoFilter.cpp index ca07e38de..b50e8af71 100644 --- a/Src/DasherCore/DemoFilter.cpp +++ b/Src/DasherCore/DemoFilter.cpp @@ -4,7 +4,6 @@ #include "DasherInterfaceBase.h" -#include "CircleStartHandler.h" #include "GameModule.h" using namespace Dasher; @@ -116,7 +115,7 @@ void CDemoFilter::HandleEvent(Parameter parameter) { case LP_DEMO_SPRING: case LP_DEMO_NOISE_MEM: case LP_MAX_BITRATE: - case LP_FRAMERATE: + case LP_FRAMERATE: { // Recalculates the parameters used in the demo following a change in framerate or speed. double spring = m_pSettingsStore->GetLongParameter(LP_DEMO_SPRING)/100.0; double noisemem = m_pSettingsStore->GetLongParameter(LP_DEMO_NOISE_MEM)/100.0; @@ -125,5 +124,8 @@ void CDemoFilter::HandleEvent(Parameter parameter) { m_dSpring = (1-exp(-spring*lambda)); m_dNoiseNew = noisemem*(1-exp(-lambda)); m_dNoiseOld = sqrt(1.0-m_dNoiseNew*m_dNoiseNew); + break; + } + default: break; } } diff --git a/Src/DasherCore/ExpansionPolicy.cpp b/Src/DasherCore/ExpansionPolicy.cpp index 5b539f8cb..e2c8b7671 100644 --- a/Src/DasherCore/ExpansionPolicy.cpp +++ b/Src/DasherCore/ExpansionPolicy.cpp @@ -10,6 +10,7 @@ #include "ExpansionPolicy.h" #include "DasherModel.h" #include +#include using namespace Dasher; diff --git a/Src/DasherCore/ExpansionPolicy.h b/Src/DasherCore/ExpansionPolicy.h index abbdbb2fa..70e3647f4 100644 --- a/Src/DasherCore/ExpansionPolicy.h +++ b/Src/DasherCore/ExpansionPolicy.h @@ -7,8 +7,7 @@ * */ -#ifndef __ExpansionPolicy_h__ -#define __ExpansionPolicy_h__ +#pragma once #include #include "DasherNode.h" @@ -20,7 +19,8 @@ namespace Dasher { class CExpansionPolicy { public: - virtual ~CExpansionPolicy() { }; + CExpansionPolicy() = default; + virtual ~CExpansionPolicy() = default; ///dMaxCost should be the value returned by pushNode from the call for the node most closely enclosing pNode (that was pushed!) ///for the first (outermost) node, i.e. when no enclosing node has been passed, (+ive) INFINITY should be passed in. virtual double pushNode(CDasherNode *pNode, int iDasherMinY, int iDasherMaxY, bool bExpand, double dMaxCost)=0; @@ -40,6 +40,7 @@ class NoExpansions : public CExpansionPolicy { public: NoExpansions() = default; + virtual ~NoExpansions() = default; double pushNode(CDasherNode *pNode, int iMin, int iMax, bool bExpand, double dMaxCost) override {return dMaxCost;} bool apply() override {return false;} }; @@ -50,6 +51,7 @@ class BudgettingPolicy : public CExpansionPolicy { public: BudgettingPolicy(CDasherModel *pModel, unsigned int iNodeBudget); + virtual ~BudgettingPolicy() = default; ///sets cost according to getCost(pNode,iMin,iMax); ///then assures node is cheaper (less important) than its parent; ///then adds to relevant queue @@ -68,9 +70,10 @@ class BudgettingPolicy : public CExpansionPolicy class AmortizedPolicy : public BudgettingPolicy { public: + AmortizedPolicy() = delete; AmortizedPolicy(CDasherModel *pModel, unsigned int iNodeBudget); AmortizedPolicy(CDasherModel *pModel, unsigned int iNodeBudget, unsigned int iMaxExpands); - ~AmortizedPolicy() override = default; + ~AmortizedPolicy() = default; bool apply() override; double pushNode(CDasherNode *pNode, int iMin, int iMax, bool bExpand, double dParentCost) override; private: @@ -78,4 +81,3 @@ class AmortizedPolicy : public BudgettingPolicy void trim(); }; } -#endif /*defined __ExpansionPolicy_h__*/ diff --git a/Src/DasherCore/FileLogger.cpp b/Src/DasherCore/FileLogger.cpp index c93268101..9b7e99999 100644 --- a/Src/DasherCore/FileLogger.cpp +++ b/Src/DasherCore/FileLogger.cpp @@ -1,7 +1,6 @@ #include "FileUtils.h" #include -#include #include #include "FileLogger.h" @@ -43,8 +42,8 @@ CFileLogger::~CFileLogger() if (!m_bFunctionTiming) return; // Dump the results of our function timing logging - Log("%-60s%20s%10s", logNORMAL, "Function","Ticks", "Percent"); - Log("%-60s%20s%10s", logNORMAL, "--------","-----", "-------"); + Log("%-60s%20s%10s", eLogLevel::logNORMAL, "Function","Ticks", "Percent"); + Log("%-60s%20s%10s", eLogLevel::logNORMAL, "--------","-----", "-------"); // First pass to count the max ticks // We assume that there was a function logger on the outer most (main) program. @@ -58,7 +57,7 @@ CFileLogger::~CFileLogger() for(const auto &[function_name, duration] : m_mapFunctionDuration) { - Log("%-60s%20I64Ld%10.2f", logNORMAL, function_name.c_str(), duration, static_cast(duration) / max_duration * 100.0); + Log("%-60s%20I64Ld%10.2f", eLogLevel::logNORMAL, function_name.c_str(), duration, static_cast(duration) / max_duration * 100.0); } } @@ -127,7 +126,7 @@ void CFileLogger::Log(const std::string strText, eLogLevel iLogLevel, ...) // Version that assume log level is logDEBUG void CFileLogger::LogDebug(const char* szText, ...) { - if(m_iLogLevel > logDEBUG) return; + if(m_iLogLevel > eLogLevel::logDEBUG) return; va_list args; @@ -139,7 +138,7 @@ void CFileLogger::LogDebug(const char* szText, ...) // Version that assume log level is logNormal void CFileLogger::LogNormal(const char* szText, ...) { - if(m_iLogLevel > logNORMAL) return; + if(m_iLogLevel > eLogLevel::logNORMAL) return; va_list args; @@ -235,7 +234,7 @@ std::string CFileLogger::GetTimeDateStamp() std::time_t now = std::chrono::system_clock::to_time_t(timepoint); int milliseconds = static_cast(std::chrono::time_point_cast(timepoint).time_since_epoch().count() % 1000); std::string strMillis(3,'0'); - sprintf(&strMillis[0], "%03d", milliseconds); + snprintf(&strMillis[0], strMillis.size(), "%03d", milliseconds); std::string Buffer(30, '\0'); //never longer than 30 chars size_t length = std::strftime(&Buffer[0], Buffer.size(), format.c_str(), std::localtime(&now)); //Not thread safe! diff --git a/Src/DasherCore/FileLogger.h b/Src/DasherCore/FileLogger.h index 952b634cc..f0e1d26a5 100644 --- a/Src/DasherCore/FileLogger.h +++ b/Src/DasherCore/FileLogger.h @@ -55,7 +55,7 @@ g_pLogger->LogCritical s ; -enum eLogLevel +enum class eLogLevel { logDEBUG = 0, logNORMAL = 1, @@ -81,13 +81,13 @@ class CFileLogger ~CFileLogger(); - void Log(const char* szText, eLogLevel iLogLevel = logNORMAL, ...); // Logs a string to our file if it meets or exceeds our logging level + void Log(const char* szText, eLogLevel iLogLevel = eLogLevel::logNORMAL, ...); // Logs a string to our file if it meets or exceeds our logging level void LogDebug(const char* szText, ...); // Logs debug level messages void LogNormal(const char* szText, ...); // Logs normal level messages void LogCritical(const char* szText, ...); // Logs critical level messages // Versions that exists so we can pass in STD strings - void Log(const std::string strText, eLogLevel iLogLevel = logNORMAL, ...); // Logs a string to our file if it meets or exceeds our logging level + void Log(const std::string strText, eLogLevel iLogLevel = eLogLevel::logNORMAL, ...); // Logs a string to our file if it meets or exceeds our logging level void SetFilename(const std::string& strFilename); void SetLogLevel(const eLogLevel newLevel); diff --git a/Src/DasherCore/FrameRate.cpp b/Src/DasherCore/FrameRate.cpp index cf5fd7b07..b7c1b1e90 100644 --- a/Src/DasherCore/FrameRate.cpp +++ b/Src/DasherCore/FrameRate.cpp @@ -66,9 +66,11 @@ void CFrameRate::HandleParameterChange(Parameter parameter) { //fallthrough case LP_MAX_BITRATE: case LP_FRAMERATE: - //Calculate m_iSteps from the decaying-average framerate, as the number - // of steps that, at the X limit, will cause LP_MAX_BITRATE bits to be - // entered per second - m_iSteps = std::max(1,(int)(m_pSettingsStore->GetLongParameter(LP_FRAMERATE)*m_dBitsAtLimX/m_pSettingsStore->GetLongParameter(LP_MAX_BITRATE))); + //Calculate m_iSteps from the decaying-average framerate, as the number + // of steps that, at the X limit, will cause LP_MAX_BITRATE bits to be + // entered per second + m_iSteps = std::max(1,(int)(m_pSettingsStore->GetLongParameter(LP_FRAMERATE)*m_dBitsAtLimX/m_pSettingsStore->GetLongParameter(LP_MAX_BITRATE))); + break; + default: break; } } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 859b9b07d..202b731a4 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -151,9 +151,9 @@ void CGameModule::DecorateView(unsigned long lTime, CDasherView *pView, CDasherM m_vTargetY.push_back(iNewTarget); bool bDrawHelper; - if (abs(iNewTarget - CDasherModel::ORIGIN_Y) >= m_pSettingsStore->GetLongParameter(LP_GAME_HELP_DIST)) { + if (llabs(iNewTarget - CDasherModel::ORIGIN_Y) >= m_pSettingsStore->GetLongParameter(LP_GAME_HELP_DIST)) { //offscreen - if (abs(iNewTarget - CDasherModel::ORIGIN_Y) >= abs(m_iTargetY - CDasherModel::ORIGIN_Y)) { + if (llabs(iNewTarget - CDasherModel::ORIGIN_Y) >= llabs(m_iTargetY - CDasherModel::ORIGIN_Y)) { //not decreasing if (m_uHelpStart == std::numeric_limits::max()) m_uHelpStart = lTime + m_pSettingsStore->GetLongParameter(LP_GAME_HELP_TIME); @@ -228,7 +228,7 @@ void CGameModule::DrawBrachistochrone(CDasherView *pView) { // Plot a brachistochrone - the optimal path from the crosshair to the target // this is a circle, passing through both crosshair and target, centered on the y-axis const myint CenterY = ComputeBrachCenter(); - pView->DasherSpaceArc(CenterY, abs(CenterY - m_iTargetY), CDasherModel::ORIGIN_X, CDasherModel::ORIGIN_Y, 0, m_iTargetY, pView->GetNamedColor(NamedColor::gameGuide), 2*(int)m_pSettingsStore->GetLongParameter(LP_LINE_WIDTH)); + pView->DasherSpaceArc(CenterY, llabs(CenterY - m_iTargetY), CDasherModel::ORIGIN_X, CDasherModel::ORIGIN_Y, 0, m_iTargetY, pView->GetNamedColor(NamedColor::gameGuide), 2*(int)m_pSettingsStore->GetLongParameter(LP_LINE_WIDTH)); } void CGameModule::DrawHelperArrow(Dasher::CDasherView* pView) diff --git a/Src/DasherCore/LanguageModelling/CTWLanguageModel.cpp b/Src/DasherCore/LanguageModelling/CTWLanguageModel.cpp index 0ee024622..620e1da44 100644 --- a/Src/DasherCore/LanguageModelling/CTWLanguageModel.cpp +++ b/Src/DasherCore/LanguageModelling/CTWLanguageModel.cpp @@ -24,8 +24,11 @@ //#include "stdafx.h" #include "CTWLanguageModel.h" +#include #include // not in use anymore? needed it for log #include +#include +#include "HashTable.h" using namespace Dasher; @@ -73,7 +76,7 @@ inline int CCTWLanguageModel::MapIndex(int b, int f){ return ((1<>(NrPhases-f))); //(2^phase -1) + dec. value of most significant bits } -inline void CCTWLanguageModel::Scale(uint64 &a, uint64 &b) +inline void CCTWLanguageModel::Scale(uint64_t &a, uint64_t &b) { // Instead of using the full 16 bits for the probabilities, use only 9, // that's the only relevant information the other bits are noise <- depends on the value of MaxCount, @@ -105,18 +108,18 @@ void CCTWLanguageModel::UpdatePath(int bit, int Update, int ValidDepth, int* & i // Update specifies yes (1) or no (0) (GetProbs). In the case 'no', the new Pws are calculated but the tree is not // altered in any way - uint64 GammaZero; // (GammaZero / (GammaZero + GammaOne)) = Pw(0|x) - uint64 GammaOne; // (GammaOne / (GammaZero + GammaOne)) = Pw(1|x) + uint64_t GammaZero; // (GammaZero / (GammaZero + GammaOne)) = Pw(0|x) + uint64_t GammaOne; // (GammaOne / (GammaZero + GammaOne)) = Pw(1|x) unsigned short int CountZero; // Number of zeros seen so far in this node unsigned short int CountOne; // Number of ones seen so far in this node - uint64 PeBlockZero; // Local block probability of sequence (0,x) - uint64 PeBlockOne; // Local block probability of sequence (1,x) - uint64 PwCBlockZero; // Product of the weighted block probabilities of the childnodes of sequence (0,x) - uint64 PwCBlockOne; // Product of the weighted block probabilities of the childnodes of sequence (1,x) - uint64 PeCondZero; // Conditional local probability (0|x) - uint64 PeCondOne; // Conditional local probability (1|x) - uint64 PwCBlock; // Product of the weighted block probabilities of the childnodes of sequence (x) - uint64 PeBlock; // Local block probability of sequence (x) + uint64_t PeBlockZero; // Local block probability of sequence (0,x) + uint64_t PeBlockOne; // Local block probability of sequence (1,x) + uint64_t PwCBlockZero; // Product of the weighted block probabilities of the childnodes of sequence (0,x) + uint64_t PwCBlockOne; // Product of the weighted block probabilities of the childnodes of sequence (1,x) + uint64_t PeCondZero; // Conditional local probability (0|x) + uint64_t PeCondOne; // Conditional local probability (1|x) + uint64_t PwCBlock; // Product of the weighted block probabilities of the childnodes of sequence (x) + uint64_t PeBlock; // Local block probability of sequence (x) // The deepest index can be a leaf, a failed node, or a not-placed node const int DeepestIndex = index[ValidDepth]; @@ -268,8 +271,7 @@ int CCTWLanguageModel::FindPath(CCTWContext & context, char NewChar, int phase, found = true; // to avoid 'failed' index[i+1] = curindex; // tell calling function where to find the node, i+1 because index[0] = rootnode break; // to escape loop and continue with next character - } - else // can't create a new node + } else // can't create a new node { found = false; index[i+1] = MaxNrNodes+1; // to indicate node could not be placed @@ -357,9 +359,9 @@ void CCTWLanguageModel::GetProbs(Context context, std::vector &Pro Interval[0] = Norm; int ValidDepth = 0; - uint64 IntervalB = 0; // 'base' interval - uint64 IntervalZ = 0; // divided interval for the 0-branch - uint64 IntervalO = 0; // divided interval for the 1-branch + uint64_t IntervalB = 0; // 'base' interval + uint64_t IntervalZ = 0; // divided interval for the 0-branch + uint64_t IntervalO = 0; // divided interval for the 1-branch unsigned int MinInterval = 0; unsigned short int Pw0 = 0; unsigned short int Pw1 = 0; @@ -375,7 +377,7 @@ void CCTWLanguageModel::GetProbs(Context context, std::vector &Pro IntervalB = Interval[(1<UpdatePath(0,0, ValidDepth, Index, Pw0, Pw1); - IntervalZ = (IntervalB * Pw0)/(uint64)(Pw0+Pw1); // flooring, influence of flooring P0 instead of P1 is negligible + IntervalZ = (IntervalB * Pw0)/(uint64_t)(Pw0+Pw1); // flooring, influence of flooring P0 instead of P1 is negligible IntervalO = IntervalB - IntervalZ; MinInterval = MinProb*1<<(NrPhases-1-phase); // leafs for each rootnode at the current phase, assuming a full alphabet!! @@ -423,12 +425,6 @@ void CCTWLanguageModel::GetProbs(Context context, std::vector &Pro bool CCTWLanguageModel::WriteToFile(std::string strFilename, std::string AlphabetName){ SLMFileHeader GenericHeader; - // Magic number ("%DLF" in ASCII) - GenericHeader.szMagic[0] = '%'; - GenericHeader.szMagic[1] = 'D'; - GenericHeader.szMagic[2] = 'L'; - GenericHeader.szMagic[3] = 'F'; - GenericHeader.iAlphabetSize = GetSize(); // Number of characters in the alphabet GenericHeader.iHeaderVersion = 1; // Version of the header GenericHeader.iLMID = 5; // ID of the language model, 5 for CTW @@ -440,38 +436,32 @@ bool CCTWLanguageModel::WriteToFile(std::string strFilename, std::string Alphabe OutputFile = fopen(strFilename.c_str(), "wb"); if(OutputFile) { - char * buffer; - buffer = new char[AlphabetName.length()+1]; - strcpy(buffer, AlphabetName.c_str()); - // write header - fwrite(GenericHeader.szMagic , sizeof(GenericHeader.szMagic[0]), sizeof(GenericHeader.szMagic), OutputFile ); - fwrite(&GenericHeader.iHeaderVersion, 2,1, OutputFile); - fwrite(&GenericHeader.iHeaderSize, 2,1, OutputFile); - fwrite(&GenericHeader.iLMID, 2,1, OutputFile); - fwrite(&GenericHeader.iLMVersion, 2,1, OutputFile); - fwrite(&GenericHeader.iLMMinVersion, 2,1, OutputFile); - fwrite(&GenericHeader.iAlphabetSize, 2,1, OutputFile); - fwrite(buffer, 1, AlphabetName.length(), OutputFile ); // UTF-8 encoded alphabet name (variable length struct) - delete[] buffer; + fwrite(GenericHeader.szMagic , sizeof(GenericHeader.szMagic[0]), sizeof(GenericHeader.szMagic) - 1, OutputFile); //Do not print Null-Char + fwrite(&GenericHeader.iHeaderVersion, sizeof(GenericHeader.iHeaderVersion), 1, OutputFile); + fwrite(&GenericHeader.iHeaderSize, sizeof(GenericHeader.iHeaderSize), 1, OutputFile); + fwrite(&GenericHeader.iLMID, sizeof(GenericHeader.iLMID), 1, OutputFile); + fwrite(&GenericHeader.iLMVersion, sizeof(GenericHeader.iLMVersion), 1, OutputFile); + fwrite(&GenericHeader.iLMMinVersion, sizeof(GenericHeader.iLMMinVersion), 1, OutputFile); + fwrite(&GenericHeader.iAlphabetSize, sizeof(GenericHeader.iAlphabetSize), 1, OutputFile); + fwrite(AlphabetName.c_str(), sizeof(AlphabetName[0]), AlphabetName.length(), OutputFile); // UTF-8 encoded alphabet name (variable length struct) // CTW specific, not in SLMFileHeader - fwrite(&MaxNrNodes, 4,1, OutputFile); + fwrite(&MaxNrNodes, sizeof(MaxNrNodes), 1, OutputFile); for(int i=0;i 1) + + bytesRead = fread(&GenericHeader.iLMVersion,sizeof(GenericHeader.iLMVersion),1, InputFile); + if(bytesRead < sizeof(GenericHeader.iLMVersion)) return false; //Not enough bytes read + + bytesRead = fread(&GenericHeader.iLMMinVersion,sizeof(GenericHeader.iLMMinVersion),1, InputFile); + if(bytesRead < sizeof(GenericHeader.iLMMinVersion) || GenericHeader.iLMMinVersion > 1) { // header indicates stored model newer than we can handle return false; } - fread(&GenericHeader.iAlphabetSize,2,1, InputFile); - if(GenericHeader.iAlphabetSize != GetSize()) + + bytesRead = fread(&GenericHeader.iAlphabetSize,sizeof(GenericHeader.iAlphabetSize),1, InputFile); + if(bytesRead < sizeof(GenericHeader.iAlphabetSize) || GenericHeader.iAlphabetSize != GetSize()) { // header indicates stored model uses an alphabet of different size return false; } - ReadAlphabetName = new char[GenericHeader.iHeaderSize - sizeof(SLMFileHeader)+1]; - fread(ReadAlphabetName,1,GenericHeader.iHeaderSize - sizeof(SLMFileHeader), InputFile); + ReadAlphabetName = new char[GenericHeader.iHeaderSize - sizeof(SLMFileHeader) + 1]; + bytesRead = fread(ReadAlphabetName,sizeof(ReadAlphabetName[0]), GenericHeader.iHeaderSize - sizeof(SLMFileHeader), InputFile); + if(bytesRead < GenericHeader.iHeaderSize - sizeof(SLMFileHeader)) return false; //Not enough bytes read ReadAlphabetName[GenericHeader.iHeaderSize - sizeof(SLMFileHeader)] = '\0'; // write the terminating 0 and read it in as well if(strcmp(ReadAlphabetName,AlphabetName.c_str())) @@ -525,21 +526,22 @@ bool CCTWLanguageModel::ReadFromFile(std::string strFilename, std::string Alphab return false; } delete[] ReadAlphabetName; + int ReadNrNodes; - fread(&ReadNrNodes,4,1, InputFile); - if(ReadNrNodes != MaxNrNodes) + bytesRead = fread(&ReadNrNodes,sizeof(ReadNrNodes), 1, InputFile); + if(bytesRead < sizeof(ReadNrNodes) || ReadNrNodes != MaxNrNodes) { // header indicates different number of nodes in the hashtable return false; } for(int i=0;i -#include -#include "LanguageModel.h" -#include "HashTable.h" -#include +#include "LanguageModel.h" +#include +#include using namespace Dasher; using namespace std; @@ -120,7 +119,7 @@ namespace Dasher { // Returns depth of found path. ``Create'' specifies whether non-existing nodes need to be // created (LearnSymbol) or not (GetProbs). - void Scale(uint64 & a, uint64 & b); + void Scale(uint64_t & a, uint64_t & b); // Scales both inputs to fit in NrBits }; // end class CCTWLanguageModel diff --git a/Src/DasherCore/LanguageModelling/LanguageModel.h b/Src/DasherCore/LanguageModelling/LanguageModel.h index 816f9f827..825e7bc69 100644 --- a/Src/DasherCore/LanguageModelling/LanguageModel.h +++ b/Src/DasherCore/LanguageModelling/LanguageModel.h @@ -9,10 +9,9 @@ #ifndef __LanguageModelling_LanguageModel_h__ #define __LanguageModelling_LanguageModel_h__ -#include "../DasherTypes.h" - #include +#include ///////////////////////////////////////////////////////////////////////////// @@ -126,7 +125,7 @@ class Dasher::CLanguageModel protected: struct SLMFileHeader { // Magic number ("%DLF" in ASCII) - char szMagic[4]; + char szMagic[5] = "%DLF"; // Version of the header unsigned short int iHeaderVersion; // Total size of header (including variable length alphabet name) diff --git a/Src/DasherCore/MandarinAlphMgr.cpp b/Src/DasherCore/MandarinAlphMgr.cpp index 008ee5930..614d42c10 100644 --- a/Src/DasherCore/MandarinAlphMgr.cpp +++ b/Src/DasherCore/MandarinAlphMgr.cpp @@ -32,6 +32,7 @@ #include #include +#include using namespace Dasher; @@ -156,7 +157,7 @@ CMandarinAlphMgr::CMandarinTrainer::CMandarinTrainer(CMessageDisplay *pMsgs, CMa if (trainStartSyms.size()==1) m_iStartSym = trainStartSyms[0]; else - m_pMsgs->FormatMessageWithString(_("Warning: faulty alphabet definition: training-start delimiter %s must be a single unicode character. May be unable to process training file."), + m_pMsgs->FormatMessage("Warning: faulty alphabet definition: training-start delimiter %s must be a single unicode character. May be unable to process training file.", m_pInfo->m_strConversionTrainStart.c_str()); } @@ -166,7 +167,7 @@ symbol CMandarinAlphMgr::CMandarinTrainer::getPYsym(bool bHavePy, const std::str //only one possibility; so we'll use it, but maybe flag. symbol pySym = *(posPY.begin()); if (bHavePy && m_pMgr->m_vGroupNames[pySym] != strPy) - m_pMsgs->FormatMessageWith2Strings(_("Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character; ignoring group specifier"), + m_pMsgs->FormatMessage("Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character; ignoring group specifier", m_pInfo->GetDisplayText(symCh).c_str(), strPy.c_str()); return pySym; @@ -178,9 +179,9 @@ symbol CMandarinAlphMgr::CMandarinTrainer::getPYsym(bool bHavePy, const std::str withName.insert(*it); if (withName.size()==1) return *(withName.begin()); else - m_pMsgs->FormatMessageWith2Strings((withName.empty()) - ? _("Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character. Dasher will not be able to learn how you want to write this character.") - : _("Warning: training file contains character '%s' as member of group '%s', but alphabet contains several such groups. Dasher will not be able to learn how you want to write this character."), + m_pMsgs->FormatMessage((withName.empty()) + ? "Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character. Dasher will not be able to learn how you want to write this character." + : "Warning: training file contains character '%s' as member of group '%s', but alphabet contains several such groups. Dasher will not be able to learn how you want to write this character.", m_pInfo->GetDisplayText(symCh).c_str(), strPy.c_str()); } @@ -200,7 +201,7 @@ void CMandarinAlphMgr::CMandarinTrainer::Train(CAlphabetMap::SymbolStream &syms) if (sym == m_iStartSym) { if (sym!=0 || syms.peekBack()==m_pInfo->m_strConversionTrainStart) { if (bHavePy) - m_pMsgs->FormatMessageWithString(_("Warning: in training file, annotation '<%s>' is followed by another annotation and will be ignored"), + m_pMsgs->FormatMessage("Warning: in training file, annotation '<%s>' is followed by another annotation and will be ignored", strPy.c_str()); strPy.clear(); bHavePy=true; for (std::string s; (s=syms.peekAhead()).length(); strPy+=s) { @@ -233,8 +234,9 @@ void CMandarinAlphMgr::CMandarinTrainer::Train(CAlphabetMap::SymbolStream &syms) #else const char* msg = _("In file %s, the following %i symbols appeared without annotations saying how they should be entered, but each can be entered in several ways. Dasher will not be able to learn how you want to enter these symbols:"); #endif - char *buf(new char[strlen(msg) + GetDesc().length() + 10]); - sprintf(buf, msg, GetDesc().c_str(), unannotated.size()); + const size_t buflen = strlen(msg) + GetDesc().length() + 10; + char* buf(new char[buflen]); + snprintf(buf, buflen, msg, GetDesc().c_str(), unannotated.size()); std::ostringstream withChars; withChars << msg; for (std::set::iterator it = unannotated.begin(); it!=unannotated.end(); it++) @@ -380,10 +382,10 @@ void CMandarinAlphMgr::GetConversions(std::vector //Two degenerate cases: PROB_SORT_THRES=0 => all (legal) ch symbols predicted uniformly // PROB_SORT_THRES=100 => all symbols put into probability order std::set haveProbs; - uint64 iRemaining(CDasherModel::NORMALIZATION); + uint64_t iRemaining(CDasherModel::NORMALIZATION); if (long percent=m_pSettingsStore->GetLongParameter(LP_PY_PROB_SORT_THRES)) { - const uint64 iNorm(iRemaining); + const uint64_t iNorm(iRemaining); const unsigned int uniform(static_cast((m_pSettingsStore->GetLongParameter(LP_UNIFORM)*iNorm)/1000)); //Set up list of symbols with blank probability entries... @@ -397,7 +399,7 @@ void CMandarinAlphMgr::GetConversions(std::vector //std::cout<<"after get probs "< >::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { sumProb += it->second; } diff --git a/Src/DasherCore/MandarinAlphMgr.h b/Src/DasherCore/MandarinAlphMgr.h index bdd5dd860..09833a1cb 100644 --- a/Src/DasherCore/MandarinAlphMgr.h +++ b/Src/DasherCore/MandarinAlphMgr.h @@ -160,18 +160,18 @@ namespace Dasher { public: /// \param pySym symbol in pinyin alphabet; must have >1 possible chinese conversion. CConvRoot(int iOffset, CMandarinAlphMgr *pMgr, symbol pySym); - CMandarinAlphMgr *mgr() const {return static_cast(CAlphBase::mgr());} - void PopulateChildren(); + CMandarinAlphMgr *mgr() const override {return static_cast(CAlphBase::mgr());} + void PopulateChildren() override; void PopulateChildrenWithExisting(CMandSym *existing); - int ExpectedNumChildren(); + int ExpectedNumChildren() override; CLanguageModel::Context iContext; - void SetFlag(int iFlag, bool bValue); + void SetFlag(int iFlag, bool bValue) override; const symbol m_pySym; ///A "symbol" to be rebuilt, is a PY sound, i.e. potentially this - CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol); + CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol) override; protected: - bool isInGroup(const SGroupInfo *pGroup); + bool isInGroup(const SGroupInfo *pGroup) override; public: const ColorPalette::Color& getLabelColor(const ColorPalette* colorPalette) override; diff --git a/Src/DasherCore/Messages.cpp b/Src/DasherCore/Messages.cpp index f7d33193f..6de201065 100644 --- a/Src/DasherCore/Messages.cpp +++ b/Src/DasherCore/Messages.cpp @@ -1,57 +1,25 @@ #include "Messages.h" -#include -#include #include #include -using std::vector; +void CMessageDisplay::FormatMessage(const char* format, va_list args) +{ + if (format == nullptr) return; -void CMessageDisplay::FormatMessageWithString(const char *fmt, const char *str) { - char *buf(new char[strlen(fmt)+strlen(str)]); - sprintf(buf, fmt, str); - Message(buf, true); - delete[] buf; -} + std::string lineToPrint; -void CMessageDisplay::FormatMessageWith2Strings(const char *fmt, const char *str1, const char *str2) { - char *buf(new char[strlen(fmt)+strlen(str1)+strlen(str2)]); - sprintf(buf, fmt, str1, str2); - Message(buf,true); - delete[] buf; + int length = vsnprintf(nullptr, 0, format, args); + lineToPrint.resize(length); + vsnprintf(&lineToPrint[0], length + 1, format, args); + + Message(lineToPrint, true); } - //The following implements a varargs version of the above, - // dynamically allocating enough storage for the formatted string - // using snprintf. However, this doesn't work on Solaris, - // hence commenting out. +void CMessageDisplay::FormatMessage(const char* format, ...) +{ + va_list args; - //Note: vector is guaranteed to store elements contiguously. - // C++98 did not guarantee this, but this was corrected in a 2003 - // technical corrigendum. As Bjarne Stroustrup says, - // "this was always the intent and all implementations always did it that way" - /*vector buf; - for (int len = strlen(fmt)+1024; ;) { - buf.resize(len); - va_list args; - va_start(args,fmt); - int res = vsnprintf(&buf[0], len, fmt, args); - va_end(args); - if (res>=0 && res double size & retry. - // However, on linux, -1 indicates "some other error". - // So make sure we don't infinite loop but instead break out somehow... - if (len*=2 > 1<<16) { - printf("Could not allocate big enough buffer, or other error, when trying to print:\n"); - va_list args2; - va_start(args2,fmt); - vprintf(fmt,args2); - va_end(args2); - return; //exit loop + function, no call to Message() - } - } else len = res+1; //that identifies necessary size of buffer - }*/ + va_start(args, format); + FormatMessage(format, args); + va_end(args); +} \ No newline at end of file diff --git a/Src/DasherCore/Messages.h b/Src/DasherCore/Messages.h index b8cfdc2d3..3c1561d64 100644 --- a/Src/DasherCore/Messages.h +++ b/Src/DasherCore/Messages.h @@ -19,8 +19,7 @@ // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -#ifndef __MESSAGES_H__ -#define __MESSAGES_H__ +#pragma once ///Abstract superclass = interface for displaying messages to the user. ///Each platform must implement: see CDasherInterfaceBase, CDashIntfScreenMsgs @@ -44,16 +43,9 @@ class CMessageDisplay { /// be able to continue writing uninterrupted. virtual void Message(const std::string &strText, bool bInterrupt)=0; - ///Utility method for common case of displaying a modal message with a format - /// string containing a single %s. - void FormatMessageWithString(const char* fmt, const char* str); - - ///Utility method for less-but-still-quite-common case of displaying a modal - /// message with a format string containing two %s - void FormatMessageWith2Strings(const char* fmt, const char* str1, const char* str2); - + /// Utility method for common case of displaying a modal message with a format + void FormatMessage(const char* format, va_list args); + void FormatMessage(const char* format, ...); }; -/// @} - -#endif +/// @} \ No newline at end of file diff --git a/Src/DasherCore/NodeCreationManager.cpp b/Src/DasherCore/NodeCreationManager.cpp index 9a4787f69..509c4239d 100644 --- a/Src/DasherCore/NodeCreationManager.cpp +++ b/Src/DasherCore/NodeCreationManager.cpp @@ -118,17 +118,17 @@ CNodeCreationManager::CNodeCreationManager( ///TRANSLATORS: These 3 messages will be displayed when the user has just chosen a new alphabet. The %s parameter will be the name of the alphabet. if(pn.has_parsed_from_system_dir()) { - pInterface->FormatMessageWithString(_("No user training text found - if you have written in \"%s\" before, this means Dasher may not be learning from previous sessions"), pAlphInfo->GetID().c_str()); + pInterface->FormatMessage("No user training text found - if you have written in \"%s\" before, this means Dasher may not be learning from previous sessions", pAlphInfo->GetID().c_str()); } else { - pInterface->FormatMessageWithString(_("No training text (user or system) found for \"%s\". Dasher will still work but entry will be slower. We suggest downloading a training text file from the Dasher website, or constructing your own."), pAlphInfo->GetID().c_str()); + pInterface->FormatMessage("No training text (user or system) found for \"%s\". Dasher will still work but entry will be slower. We suggest downloading a training text file from the Dasher website, or constructing your own.", pAlphInfo->GetID().c_str()); } } } else { - pInterface->FormatMessageWithString(_("\"%s\" does not specify training file. Dasher will work but entry will be slower. Check you have the latest version of the alphabet definition."), pAlphInfo->GetID().c_str()); + pInterface->FormatMessage("\"%s\" does not specify training file. Dasher will work but entry will be slower. Check you have the latest version of the alphabet definition.", pAlphInfo->GetID().c_str()); } HandleParameterChange(LP_ORIENTATION); diff --git a/Src/DasherCore/OneDimensionalFilter.h b/Src/DasherCore/OneDimensionalFilter.h index fd7ee4f7b..65ac14d46 100644 --- a/Src/DasherCore/OneDimensionalFilter.h +++ b/Src/DasherCore/OneDimensionalFilter.h @@ -31,7 +31,7 @@ class C1DCircleStartHandler : public CCircleStartHandler { C1DCircleStartHandler(COneDimensionalFilter *f, CSettingsStore* pSettingsStore); CDasherScreen::point CircleCenter(CDasherView *pView) override; - void onPause(); + void onPause() override; private: CDasherScreen::point m_fwdCenter; diff --git a/Src/DasherCore/RoutingAlphMgr.cpp b/Src/DasherCore/RoutingAlphMgr.cpp index 7bc0a239b..5be0c8456 100644 --- a/Src/DasherCore/RoutingAlphMgr.cpp +++ b/Src/DasherCore/RoutingAlphMgr.cpp @@ -99,7 +99,7 @@ CRoutingAlphMgr::CRoutingTrainer::CRoutingTrainer(CMessageDisplay *pMsgs, CRouti if (trainStartSyms.size()==1) m_iStartSym = trainStartSyms[0]; else - m_pMsgs->FormatMessageWithString(_("Warning: faulty alphabet definition: training-start delimiter %s must be a single unicode character. May be unable to process training file."), + m_pMsgs->FormatMessage("Warning: faulty alphabet definition: training-start delimiter %s must be a single unicode character. May be unable to process training file.", m_pInfo->m_strConversionTrainStart.c_str()); } @@ -116,9 +116,9 @@ symbol CRoutingAlphMgr::CRoutingTrainer::getRoute(bool bHaveRoute, const std::st // that later more-or-less independently if (bHaveRoute) { - m_pMsgs->FormatMessageWith2Strings((named.size()==0) - ? _("Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character. Ignoring group specifier.") - : _("Warning: training file contains character '%s' as member of group '%s', but alphabet contains several such groups. Dasher will not be able to learn how you want to write this character."), + m_pMsgs->FormatMessage((named.size()==0) + ? "Warning: training file contains character '%s' as member of group '%s', but no group of that name contains the character. Ignoring group specifier." + : "Warning: training file contains character '%s' as member of group '%s', but alphabet contains several such groups. Dasher will not be able to learn how you want to write this character.", m_pInfo->GetDisplayText(baseSym).c_str(), strRoute.c_str()); } @@ -135,7 +135,7 @@ void CRoutingAlphMgr::CRoutingTrainer::Train(CAlphabetMap::SymbolStream &syms) { if (sym == m_iStartSym) { if (sym!=0 || syms.peekBack()==m_pInfo->m_strConversionTrainStart) { if (bHaveRoute) - m_pMsgs->FormatMessageWithString(_("Warning: in training file, annotation '<%s>' is followed by another annotation and will be ignored"), + m_pMsgs->FormatMessage("Warning: in training file, annotation '<%s>' is followed by another annotation and will be ignored", strRoute.c_str()); strRoute.clear(); bHaveRoute=true; for (std::string s; (s=syms.peekAhead()).length(); strRoute+=s) { diff --git a/Src/DasherCore/ScreenGameModule.h b/Src/DasherCore/ScreenGameModule.h index 1e9913a6f..6f66cedcc 100644 --- a/Src/DasherCore/ScreenGameModule.h +++ b/Src/DasherCore/ScreenGameModule.h @@ -30,8 +30,8 @@ namespace Dasher { CScreenGameModule(CSettingsStore* pSettingsStore, CDasherInterfaceBase *pInterface,CDasherView *pView, CDasherModel *pModel); void HandleEditEvent(CEditEvent::EditEventType type, const std::string& strText, CDasherNode* node) override; protected: - virtual void ChunkGenerated(); - virtual void DrawText(CDasherView *pView); + virtual void ChunkGenerated() override; + virtual void DrawText(CDasherView *pView) override; private: std::string m_strEntered, m_strTarget; CDasherScreen::Label *m_pLabEntered, *m_pLabTarget, *m_pLabWrong; diff --git a/Src/DasherCore/TimeSpan.cpp b/Src/DasherCore/TimeSpan.cpp index 0ea64e8bf..1c126d3cb 100644 --- a/Src/DasherCore/TimeSpan.cpp +++ b/Src/DasherCore/TimeSpan.cpp @@ -52,7 +52,7 @@ std::string CTimeSpan::GetXML(const std::string& strPrefix, bool bSinglePointInT strResult += strPrefix; strResult += "\t"; char strNum[256]; - sprintf(strNum, "%0.3f", m_dElapsed); + snprintf(strNum, sizeof(strNum), "%0.3f", m_dElapsed); strResult += strNum; strResult += "\n"; } diff --git a/Src/DasherCore/Trainer.cpp b/Src/DasherCore/Trainer.cpp index 8a23f6922..f3e370d43 100644 --- a/Src/DasherCore/Trainer.cpp +++ b/Src/DasherCore/Trainer.cpp @@ -3,9 +3,7 @@ #include -#include "LanguageModelling/PPMPYLanguageModel.h" #include -#include #include using namespace Dasher; @@ -19,7 +17,7 @@ CTrainer::CTrainer(CMessageDisplay *pMsgs, CLanguageModel *pLanguageModel, const m_iCtxEsc = syms[0]; else { //no context switch commands will be executed! - pMsgs->FormatMessageWithString(_("Warning: faulty alphabet definition, escape sequence %s must be a single unicode character. This may worsen Dasher's text prediction."), + pMsgs->FormatMessage("Warning: faulty alphabet definition, escape sequence %s must be a single unicode character. This may worsen Dasher's text prediction.", pInfo->GetContextEscapeChar().c_str()); m_iCtxEsc = -1; } @@ -85,7 +83,7 @@ class ProgressStream : public CAlphabetMap::SymbolStream { bool Dasher::CTrainer::Parse(const std::string &strDesc, std::istream &in, bool bUser) { if (in.fail()) { - m_pMsgs->FormatMessageWithString(_("Unable to open file \"%s\" for reading"),strDesc.c_str()); + m_pMsgs->FormatMessage("Unable to open file \"%s\" for reading",strDesc.c_str()); return false; } ///easy enough to be re-entrant, so might as well diff --git a/Src/DasherCore/TwoPushDynamicFilter.cpp b/Src/DasherCore/TwoPushDynamicFilter.cpp index e8f10164d..14f0e46ca 100644 --- a/Src/DasherCore/TwoPushDynamicFilter.cpp +++ b/Src/DasherCore/TwoPushDynamicFilter.cpp @@ -116,19 +116,21 @@ bool CTwoPushDynamicFilter::DecorateView(CDasherView *pView, CDasherInput *pInpu void CTwoPushDynamicFilter::HandleParameterChange(Parameter parameter) { switch (parameter) { - case LP_TWO_PUSH_OUTER: //fallthrough - case LP_TWO_PUSH_LONG: //fallthrough - case LP_TWO_PUSH_SHORT: { - //TODO, short gap always at the top - allow other way around also? - double dOuter = m_pSettingsStore->GetLongParameter(LP_TWO_PUSH_OUTER); - m_dLogUpMul = log(dOuter / upDist()); - m_dLogDownMul = log(dOuter / downDist()); -//cout << "bitsUp " << m_dLogUpMul << " bitsDown " << m_dLogDownMul << std::endl; - } //and fallthrough - case LP_TWO_PUSH_TOLERANCE: //fallthrough - case LP_DYNAMIC_BUTTON_LAG: - //recompute rest in Timer - m_dLastBitRate=-std::numeric_limits::infinity(); + case LP_TWO_PUSH_OUTER: //fallthrough + case LP_TWO_PUSH_LONG: //fallthrough + case LP_TWO_PUSH_SHORT: { + //TODO, short gap always at the top - allow other way around also? + double dOuter = m_pSettingsStore->GetLongParameter(LP_TWO_PUSH_OUTER); + m_dLogUpMul = log(dOuter / upDist()); + m_dLogDownMul = log(dOuter / downDist()); + //cout << "bitsUp " << m_dLogUpMul << " bitsDown " << m_dLogDownMul << std::endl; + } //and fallthrough + case LP_TWO_PUSH_TOLERANCE: //fallthrough + case LP_DYNAMIC_BUTTON_LAG: + //recompute rest in Timer + m_dLastBitRate=-std::numeric_limits::infinity(); + break; + default: break; } } diff --git a/Src/DasherCore/UserLocation.cpp b/Src/DasherCore/UserLocation.cpp index b42310429..1be64453a 100644 --- a/Src/DasherCore/UserLocation.cpp +++ b/Src/DasherCore/UserLocation.cpp @@ -4,6 +4,7 @@ #include #include "TimeSpan.h" +#include "XMLUtil.h" // Construct a new location at the current point in time and at the specified coordinates. @@ -107,13 +108,13 @@ std::string CUserLocation::GetXML(const std::string& strPrefix) { strResult += strPrefix; strResult += "\t"; - sprintf(strNum, "%d", m_iLocationX); + snprintf(strNum, sizeof(strNum), "%d", m_iLocationX); strResult += strNum; strResult += "\n"; strResult += strPrefix; strResult += "\t"; - sprintf(strNum, "%d", m_iLocationY); + snprintf(strNum, sizeof(strNum), "%d", m_iLocationY); strResult += strNum; strResult += "\n"; } @@ -121,20 +122,20 @@ std::string CUserLocation::GetXML(const std::string& strPrefix) { strResult += strPrefix; strResult += "\t"; - sprintf(strNum, "%0.4f", m_dNormalizedLocationX); + snprintf(strNum, sizeof(strNum), "%0.4f", m_dNormalizedLocationX); strResult += strNum; strResult += "\n"; strResult += strPrefix; strResult += "\t"; - sprintf(strNum, "%0.4f", m_dNormalizedLocationY); + snprintf(strNum, sizeof(strNum), "%0.4f", m_dNormalizedLocationY); strResult += strNum; strResult += "\n"; } strResult += strPrefix; strResult += "\t"; - sprintf(strNum, "%0.3f", m_dNats / log(2.0)); + snprintf(strNum, sizeof(strNum), "%0.3f", m_dNats / log(2.0)); strResult += strNum; strResult += "\n"; @@ -235,9 +236,9 @@ std::string CUserLocation::GetTabMouseXY(bool bReturnNormalized) char szNum[256]; if (bReturnNormalized) - sprintf(szNum, "%0.4f\t%0.4f\n", m_dNormalizedLocationX, m_dNormalizedLocationY); + snprintf(szNum, sizeof(szNum), "%0.4f\t%0.4f\n", m_dNormalizedLocationX, m_dNormalizedLocationY); else - sprintf(szNum, "%0.4f\t%0.4f\n", (double)m_iLocationX, (double)m_iLocationY); + snprintf(szNum, sizeof(szNum),"%0.4f\t%0.4f\n", (double)m_iLocationX, (double)m_iLocationY); strResult += szNum; diff --git a/Src/DasherCore/UserLocation.h b/Src/DasherCore/UserLocation.h index db9a9a557..2b3365b5f 100644 --- a/Src/DasherCore/UserLocation.h +++ b/Src/DasherCore/UserLocation.h @@ -12,7 +12,7 @@ #include "FileLogger.h" #include -#include "XMLUtil.h" +#include extern CFileLogger* g_pLogger; diff --git a/Src/DasherCore/UserLog.cpp b/Src/DasherCore/UserLog.cpp index 77c37034f..510a3e7d1 100644 --- a/Src/DasherCore/UserLog.cpp +++ b/Src/DasherCore/UserLog.cpp @@ -4,6 +4,7 @@ #include #include +#include "FileLogger.h" #include "FileUtils.h" @@ -56,14 +57,13 @@ CUserLog::CUserLog(CSettingsStore* pSettingsStore, InitUsingMask(iLogTypeMask); - if ((m_bSimple) && (m_pSimpleLogger != NULL)) - m_pSimpleLogger->Log("start, %s", logDEBUG, GetVersionInfo().c_str()); + if ((m_bSimple) && (m_pSimpleLogger != NULL)) m_pSimpleLogger->LogDebug("start, %s", GetVersionInfo().c_str()); SetOuputFilename(); m_pApplicationSpan = new CTimeSpan("Application", true); if (m_pApplicationSpan == NULL) - g_pLogger->Log("CUserLog::CUserLog, failed to create m_pApplicationSpan!", logNORMAL); + g_pLogger->LogNormal("CUserLog::CUserLog, failed to create m_pApplicationSpan!"); // TODO: for the load test harness, we apparently need to create the object directly // without a settings store (which will break CSettingsObserver, etc.); and then, @@ -76,7 +76,7 @@ CUserLog::~CUserLog() //CFunctionLogger f1("CUserLog::~CUserLog", g_pLogger); if ((m_bSimple) && (m_pSimpleLogger != NULL)) - m_pSimpleLogger->Log("stop", logDEBUG); + m_pSimpleLogger->LogDebug("stop"); if (m_pApplicationSpan != NULL) { @@ -147,7 +147,7 @@ void CUserLog::InitUsingMask(int iLogLevelMask) m_bSimple = true; if (m_pSimpleLogger == NULL) - m_pSimpleLogger = new CFileLogger(USER_LOG_SIMPLE_FILENAME, logDEBUG, logTimeStamp | logDateStamp); + m_pSimpleLogger = new CFileLogger(USER_LOG_SIMPLE_FILENAME, eLogLevel::logDEBUG, logTimeStamp | logDateStamp); } if (iLogLevelMask & userLogDetailed) @@ -187,8 +187,7 @@ void CUserLog::StartWriting() // one short log entry for the final position the next time they start writing. if ((m_bNeedToWriteCanvas) && (m_pSimpleLogger != NULL)) { - m_pSimpleLogger->Log("canvas:\t%d\t%d\t%d\t%d", - logDEBUG, + m_pSimpleLogger->LogDebug("canvas:\t%d\t%d\t%d\t%d", m_sCanvasCoordinates.top, m_sCanvasCoordinates.left, m_sCanvasCoordinates.bottom, @@ -212,7 +211,7 @@ void CUserLog::StartWriting() if (pTrial != NULL) pTrial->StartWriting(); else - g_pLogger->Log("CUserLog::StartWriting, failed to create new pTrial!", logNORMAL); + g_pLogger->LogNormal("CUserLog::StartWriting, failed to create new pTrial!"); } m_bIsWriting = true; @@ -243,7 +242,7 @@ void CUserLog::StopWriting() // In simple logging mode, we'll output the stats for this navigation cycle if ((m_bSimple) && (m_pSimpleLogger != NULL)) - m_pSimpleLogger->Log("%s", logDEBUG, GetStartStopCycleStats().c_str()); + m_pSimpleLogger->LogDebug("%s", GetStartStopCycleStats().c_str()); if (m_bDetailed) { @@ -251,7 +250,7 @@ void CUserLog::StopWriting() if (pTrial == NULL) { - g_pLogger->Log("CUserLog::StopWriting, pTrial was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLog::StopWriting, pTrial was NULL!"); return; } @@ -267,13 +266,13 @@ void CUserLog::AddSymbols(Dasher::VECTOR_SYMBOL_PROB* vpNewSymbols, eUserLogEven if (!m_bIsWriting) { // StartWriting() wasn't called, so we'll do it implicitly now - g_pLogger->Log("CUserLog::AddSymbols, StartWriting() not called?", logDEBUG); + g_pLogger->LogDebug("CUserLog::AddSymbols, StartWriting() not called?"); StartWriting(); } if (vpNewSymbols == NULL) { - g_pLogger->Log("CUserLog::AddSymbols, vpNewSymbols was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLog::AddSymbols, vpNewSymbols was NULL!"); return; } @@ -291,7 +290,7 @@ void CUserLog::AddSymbols(Dasher::VECTOR_SYMBOL_PROB* vpNewSymbols, eUserLogEven // We should have a pTrial object since StartWriting() should have been called before us if (pTrial == NULL) { - g_pLogger->Log("CUserLog::AddSymbols, pTrial was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLog::AddSymbols, pTrial was NULL!"); return; } @@ -309,7 +308,7 @@ void CUserLog::DeleteSymbols(int iNumToDelete, eUserLogEventType iEvent) if (!m_bIsWriting) { // StartWriting() wasn't called, so we'll do it implicitly now - g_pLogger->Log("CUserLog::DeleteSymbols, StartWriting() not called?", logDEBUG); + g_pLogger->LogDebug("CUserLog::DeleteSymbols, StartWriting() not called?"); StartWriting(); } @@ -331,7 +330,7 @@ void CUserLog::DeleteSymbols(int iNumToDelete, eUserLogEventType iEvent) // We should have a pTrial object since StartWriting() should have been called before us if (pTrial == NULL) { - g_pLogger->Log("CUserLog::DeleteSymbols, pTrial was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLog::DeleteSymbols, pTrial was NULL!"); return; } @@ -346,7 +345,7 @@ void CUserLog::NewTrial() if (m_bIsWriting) { // We should have called StopWriting(), but we'll do it here implicitly - g_pLogger->Log("CUserLog::NewTrial, StopWriting() not called?", logDEBUG); + g_pLogger->LogDebug("CUserLog::NewTrial, StopWriting() not called?"); StopWriting(); } @@ -377,14 +376,14 @@ void CUserLog::NewTrial() // Overloaded version that converts a double to a string void CUserLog::AddParam(const std::string& strName, double dValue, int iOptionMask) { - sprintf(m_szTempBuffer, "%0.4f", dValue); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "%0.4f", dValue); AddParam(strName, m_szTempBuffer, iOptionMask); } // Overloaded version that converts a int to a string void CUserLog::AddParam(const std::string& strName, int iValue, int iOptionMask) { - sprintf(m_szTempBuffer, "%d", iValue); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "%d", iValue); AddParam(strName, m_szTempBuffer, iOptionMask); } @@ -422,7 +421,7 @@ void CUserLog::AddParam(const std::string& strName, const std::string& strValue, (m_bInitIsDone) && (!bShortInCycle)) { - m_pSimpleLogger->Log("%s = %s", logDEBUG, strName.c_str(), strValue.c_str()); + m_pSimpleLogger->LogNormal("%s = %s", strName.c_str(), strValue.c_str()); } // See if this matches an existing parameter value that we may want to @@ -449,7 +448,7 @@ void CUserLog::AddParam(const std::string& strName, const std::string& strValue, if (pNewParam == NULL) { - g_pLogger->Log("CUserLog::AddParam, failed to create CUserLogParam object!", logNORMAL); + g_pLogger->LogNormal("CUserLog::AddParam, failed to create CUserLogParam object!"); return; } @@ -579,7 +578,7 @@ void CUserLog::AddMouseLocationNormalized(int iX, int iY, bool bStoreIntegerRep, (m_sCanvasCoordinates.right == 0) && (m_sCanvasCoordinates.top == 0)) { - g_pLogger->Log("CUserLog::AddMouseLocationNormalized, called before AddCanvasSize()?", logNORMAL); + g_pLogger->LogNormal("CUserLog::AddMouseLocationNormalized, called before AddCanvasSize()?"); return; } @@ -790,7 +789,7 @@ CUserLogTrial* CUserLog::AddTrial() PrepareNewTrial(); } else - g_pLogger->Log("CUserLog::AddTrial, failed to create CUserLogTrialSpeech!", logNORMAL); + g_pLogger->LogNormal("CUserLog::AddTrial, failed to create CUserLogTrialSpeech!"); return pTrial; } @@ -835,7 +834,7 @@ std::string CUserLog::GetStartStopCycleStats() if (m_pCycleTimer == NULL) { - g_pLogger->Log("CUserLog::GetStartStopCycleStats, cycle timer was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLog::GetStartStopCycleStats, cycle timer was NULL!"); return ""; } @@ -845,7 +844,7 @@ std::string CUserLog::GetStartStopCycleStats() // coordinate, (any parameters marked to be put in cycle stats) // // tsbdxym stands for: time symbols bits deletes x y maxbitrate - sprintf(m_szTempBuffer, + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "tsbdxym:\t%0.3f\t%zu\t%0.6f\t%d\t%0.3f\t%0.3f%s", m_pCycleTimer->GetElapsed(), m_vCycleHistory.size(), @@ -968,7 +967,7 @@ void CUserLog::PrepareNewTrial() } else - g_pLogger->Log("CUserLog::PrepareNewTrial, failed to create CUserLogTrial", logNORMAL); + g_pLogger->LogNormal("CUserLog::PrepareNewTrial, failed to create CUserLogTrial"); } // Parameters can be marked to always end them at the cycle stats in short logging. @@ -1073,7 +1072,7 @@ void CUserLog::UpdateParam(Parameter parameter, int iOptionMask) } default: { - g_pLogger->Log("CUserLog::UpdateParam, matched parameter %d but unknown type %d", logNORMAL, parameter, GetParameterType(parameter)); + g_pLogger->LogNormal("CUserLog::UpdateParam, matched parameter %d but unknown type %d", parameter, GetParameterType(parameter)); break; } }; diff --git a/Src/DasherCore/UserLogTrial.cpp b/Src/DasherCore/UserLogTrial.cpp index 9ca88898b..674c9b789 100644 --- a/Src/DasherCore/UserLogTrial.cpp +++ b/Src/DasherCore/UserLogTrial.cpp @@ -159,7 +159,7 @@ void CUserLogTrial::StartWriting() if (m_bWritingStart) { - g_pLogger->Log("CUserLogTrial::StartWriting, nav already marked as started!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StartWriting, nav already marked as started!"); return; } @@ -173,7 +173,7 @@ void CUserLogTrial::StartWriting() if (m_pSpan == NULL) { - g_pLogger->Log("CUserLogTrial::StartWriting, m_pSpan was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StartWriting, m_pSpan was NULL!"); return; } @@ -199,27 +199,27 @@ void CUserLogTrial::StopWriting(double dBits) if (!m_bWritingStart) { - g_pLogger->Log("CUserLogTrial::StopWriting, nav already marked as stopped!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StopWriting, nav already marked as stopped!"); return; } if (m_vpNavCycles.size() <= 0) { - g_pLogger->Log("CUserLogTrial::StopWriting, vector was empty!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StopWriting, vector was empty!"); return; } NavCycle* pCycle = GetCurrentNavCycle(); if (pCycle == NULL) { - g_pLogger->Log("CUserLogTrial::StopWriting, current cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StopWriting, current cycle was NULL!"); return; } CTimeSpan* pSpan = (CTimeSpan*) pCycle->pSpan; if (pSpan == NULL) { - g_pLogger->Log("CUserLogTrial::StopWriting, span was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::StopWriting, span was NULL!"); return; } @@ -267,7 +267,7 @@ void CUserLogTrial::AddSymbols(Dasher::VECTOR_SYMBOL_PROB* vpNewSymbolProbs, if (pLocation == NULL) { - g_pLogger->Log("CUserLogTrial::AddSymbols, failed to create location!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddSymbols, failed to create location!"); return; } @@ -282,7 +282,7 @@ void CUserLogTrial::AddSymbols(Dasher::VECTOR_SYMBOL_PROB* vpNewSymbolProbs, if (pCycle != NULL) pCycle->vectorNavLocations.push_back(pLocation); else - g_pLogger->Log("CUserLogTrial::AddSymbols, cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddSymbols, cycle was NULL!"); } @@ -312,7 +312,7 @@ void CUserLogTrial::DeleteSymbols(int iNumToDelete, eUserLogEventType iEvent) if (pLocation == NULL) { - g_pLogger->Log("CUserLogTrial::DeleteSymbols, failed to create location!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::DeleteSymbols, failed to create location!"); return; } @@ -327,7 +327,7 @@ void CUserLogTrial::DeleteSymbols(int iNumToDelete, eUserLogEventType iEvent) if (pCycle != NULL) pCycle->vectorNavLocations.push_back(pLocation); else - g_pLogger->Log("CUserLogTrial::DeleteSymbols, cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::DeleteSymbols, cycle was NULL!"); } @@ -364,10 +364,10 @@ void CUserLogTrial::AddMouseLocation(int iX, int iY, float dNats) if (pCycle != NULL) pCycle->vectorMouseLocations.push_back(pLocation); else - g_pLogger->Log("CUserLogTrial::AddLocation, cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddLocation, cycle was NULL!"); } else - g_pLogger->Log("CUserLogTrial::AddLocation, location was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddLocation, location was NULL!"); } @@ -383,7 +383,7 @@ void CUserLogTrial::AddMouseLocationNormalized(int iX, int iY, bool bStoreIntege (m_sCanvasCoordinates.left == 0) && (m_sCanvasCoordinates.right == 0) && (m_sCanvasCoordinates.top == 0)) - g_pLogger->Log("CUserLogTrial::AddMouseLocationNormalized, called before AddCanvasSize()?", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddMouseLocationNormalized, called before AddCanvasSize()?"); pLocation = new CUserLocation(iX, iY, @@ -402,10 +402,10 @@ void CUserLogTrial::AddMouseLocationNormalized(int iX, int iY, bool bStoreIntege if (pCycle != NULL) pCycle->vectorMouseLocations.push_back(pLocation); else - g_pLogger->Log("CUserLogTrial::AddMouseLocationNormalized, cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddMouseLocationNormalized, cycle was NULL!"); } else - g_pLogger->Log("CUserLogTrial::AddLocation, location was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddLocation, location was NULL!"); } void CUserLogTrial::AddKeyDown(Dasher::Keys::VirtualKey Key, int iType, int iEffect) { @@ -417,10 +417,10 @@ void CUserLogTrial::AddKeyDown(Dasher::Keys::VirtualKey Key, int iType, int iEff if(pCycle) pCycle->vectorButtons.push_back(pButton); else - g_pLogger->Log("CUserLogTrial::AddLocation, cycle was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddLocation, cycle was NULL!"); } else - g_pLogger->Log("CUserLogTrial::AddLocation, location was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddLocation, location was NULL!"); } // Sets the current window size, this includes area for the menu bar, @@ -566,7 +566,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str std::string strResult = ""; if (pLocation == NULL) { - g_pLogger->Log("CUserLogTrial::GetLocationXML, location was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::GetLocationXML, location was NULL!"); return strResult; } @@ -580,7 +580,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str strResult += strPrefix; strResult += "\t"; - sprintf(m_szTempBuffer, "%0.6f", pLocation->avgBits); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "%0.6f", pLocation->avgBits); strResult += m_szTempBuffer; strResult += "\n"; @@ -589,7 +589,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str { strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%d", (int) pLocation->event); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "%d", (int) pLocation->event); strResult += m_szTempBuffer; strResult += "\n"; } @@ -598,7 +598,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str { strResult += strPrefix; strResult += "\t"; - sprintf(m_szTempBuffer, "%zu", pLocation->pVectorAdded->size()); + snprintf(m_szTempBuffer,TEMP_BUFFER_SIZE, "%zu", pLocation->pVectorAdded->size()); strResult += m_szTempBuffer; strResult += "\n"; @@ -621,7 +621,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%0.6f", sItem.prob); + snprintf(m_szTempBuffer,TEMP_BUFFER_SIZE, "%0.6f", sItem.prob); strResult += m_szTempBuffer; strResult += "\n"; @@ -635,7 +635,7 @@ std::string CUserLogTrial::GetLocationXML(NavLocation* pLocation, const std::str { strResult += strPrefix; strResult += "\t"; - sprintf(m_szTempBuffer, "%d", pLocation->numDeleted); + snprintf(m_szTempBuffer,TEMP_BUFFER_SIZE, "%d", pLocation->numDeleted); strResult += m_szTempBuffer; strResult += "\n"; } @@ -695,7 +695,7 @@ std::string CUserLogTrial::GetStatsXML(const std::string& strPrefix, const std:: if (pSpan == NULL) { - g_pLogger->Log("CUserLogTrial::GetStatsXML, pSpan = NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::GetStatsXML, pSpan = NULL!"); return strResult; } @@ -707,20 +707,20 @@ std::string CUserLogTrial::GetStatsXML(const std::string& strPrefix, const std:: // Average number of bits along the path to the final string strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%0.6f", dAvgBits); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "%0.6f", dAvgBits); strResult += m_szTempBuffer; strResult += "\n"; strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%0.6f", dTotalBits); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%0.6f", dTotalBits); strResult += m_szTempBuffer; strResult += "\n"; strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%d", iButtonCount); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%d", iButtonCount); strResult += m_szTempBuffer; strResult += "\n"; @@ -731,14 +731,14 @@ std::string CUserLogTrial::GetStatsXML(const std::string& strPrefix, const std:: // We want the number of symbols which might differ // from the actual length of the text history. int iNumChars = static_cast(m_vHistory.size()); - sprintf(m_szTempBuffer, "%d", iNumChars); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%d", iNumChars); strResult += m_szTempBuffer; strResult += "\n"; strResult += strPrefix; strResult += "\t\t"; double dNumWords = (double) iNumChars / (double) 5; - sprintf(m_szTempBuffer, "%0.2f", dNumWords); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%0.2f", dNumWords); strResult += m_szTempBuffer; strResult += "\n"; @@ -753,13 +753,13 @@ std::string CUserLogTrial::GetStatsXML(const std::string& strPrefix, const std:: strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%0.3f", dWPM); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%0.3f", dWPM); strResult += m_szTempBuffer; strResult += "\n"; strResult += strPrefix; strResult += "\t\t"; - sprintf(m_szTempBuffer, "%0.3f", dCPM); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE,"%0.3f", dCPM); strResult += m_szTempBuffer; strResult += "\n"; @@ -783,19 +783,19 @@ std::string CUserLogTrial::GetWindowCanvasXML(const std::string& strPrefix) strResult += "\t\n"; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sWindowCoordinates.top); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sWindowCoordinates.top); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sWindowCoordinates.bottom); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sWindowCoordinates.bottom); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sWindowCoordinates.left); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sWindowCoordinates.left); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sWindowCoordinates.right); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sWindowCoordinates.right); strResult += m_szTempBuffer; strResult += strPrefix; @@ -806,19 +806,19 @@ std::string CUserLogTrial::GetWindowCanvasXML(const std::string& strPrefix) strResult += "\t\n"; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sCanvasCoordinates.top); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sCanvasCoordinates.top); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sCanvasCoordinates.bottom); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sCanvasCoordinates.bottom); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sCanvasCoordinates.left); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sCanvasCoordinates.left); strResult += m_szTempBuffer; strResult += strPrefix; - sprintf(m_szTempBuffer, "\t\t%d\n", m_sCanvasCoordinates.right); + snprintf(m_szTempBuffer, TEMP_BUFFER_SIZE, "\t\t%d\n", m_sCanvasCoordinates.right); strResult += m_szTempBuffer; strResult += strPrefix; @@ -912,7 +912,7 @@ void CUserLogTrial::AddParam(const std::string& strName, const std::string& strV CUserLogParam* pNewParam = new CUserLogParam; if (pNewParam == NULL) { - g_pLogger->Log("CUserLogTrial::AddParam, newParam was NULL!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddParam, newParam was NULL!"); return; } @@ -1015,7 +1015,7 @@ NavCycle* CUserLogTrial::AddNavCycle() NavCycle* pNewCycle = new NavCycle; if (pNewCycle == NULL) { - g_pLogger->Log("CUserLogTrial::AddNavCycle, failed to create NavCycle!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::AddNavCycle, failed to create NavCycle!"); return NULL; } @@ -1181,7 +1181,7 @@ CUserLogTrial::CUserLogTrial(const std::string& strXML, int iIgnored) NavCycle* pCycle = new NavCycle(); if (pCycle == NULL) { - g_pLogger->Log("CUserLogTrial::CUserLogTrial, failed to create NavCycle!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::CUserLogTrial, failed to create NavCycle!"); return; } @@ -1202,7 +1202,7 @@ CUserLogTrial::CUserLogTrial(const std::string& strXML, int iIgnored) NavLocation* pLocation = new NavLocation(); if (pLocation == NULL) { - g_pLogger->Log("CUserLogTrial::CUserLogTrial, failed to create NavLocation!", logNORMAL); + g_pLogger->LogNormal("CUserLogTrial::CUserLogTrial, failed to create NavLocation!"); return; }