- Format all files.

This commit is contained in:
Daniel Belcher 2019-05-02 12:30:54 -07:00
commit 0df371f5a3
234 changed files with 12650 additions and 11851 deletions

View file

@ -33,9 +33,7 @@ bool IsDigitOpCode(OpCode opCode)
// was never inout, we need to revert the state changes made as a result of this test // was never inout, we need to revert the state changes made as a result of this test
bool IsGuiSettingOpCode(OpCode opCode) bool IsGuiSettingOpCode(OpCode opCode)
{ {
if (IsOpInRange(opCode, IDM_HEX, IDM_BIN) || if (IsOpInRange(opCode, IDM_HEX, IDM_BIN) || IsOpInRange(opCode, IDM_QWORD, IDM_BYTE) || IsOpInRange(opCode, IDM_DEG, IDM_GRAD))
IsOpInRange(opCode, IDM_QWORD, IDM_BYTE) ||
IsOpInRange(opCode, IDM_DEG, IDM_GRAD))
{ {
return true; return true;
} }

View file

@ -11,7 +11,8 @@ constexpr int ASCII_0 = 48;
using namespace std; using namespace std;
using namespace CalcEngine; using namespace CalcEngine;
namespace { namespace
{
void IFT(ResultCode hr) void IFT(ResultCode hr)
{ {
if (FAILED(hr)) if (FAILED(hr))
@ -38,11 +39,8 @@ void CHistoryCollector::ReinitHistory()
// Constructor // Constructor
// Can throw Out of memory error // Can throw Out of memory error
CHistoryCollector::CHistoryCollector(ICalcDisplay *pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol) : CHistoryCollector::CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol)
m_pHistoryDisplay(pHistoryDisplay), : m_pHistoryDisplay(pHistoryDisplay), m_pCalcDisplay(pCalcDisplay), m_iCurLineHistStart(-1), m_decimalSymbol(decimalSymbol)
m_pCalcDisplay(pCalcDisplay),
m_iCurLineHistStart(-1),
m_decimalSymbol(decimalSymbol)
{ {
ReinitHistory(); ReinitHistory();
} }
@ -302,7 +300,8 @@ void CHistoryCollector::CompleteHistoryLine(wstring_view numStr)
{ {
if (nullptr != m_pCalcDisplay) if (nullptr != m_pCalcDisplay)
{ {
m_pCalcDisplay->SetExpressionDisplay(std::make_shared<CalculatorVector<std::pair<std::wstring, int>>>(), std::make_shared<CalculatorVector<std::shared_ptr<IExpressionCommand>>>()); m_pCalcDisplay->SetExpressionDisplay(std::make_shared<CalculatorVector<std::pair<std::wstring, int>>>(),
std::make_shared<CalculatorVector<std::shared_ptr<IExpressionCommand>>>());
} }
if (nullptr != m_pHistoryDisplay) if (nullptr != m_pHistoryDisplay)
@ -323,14 +322,14 @@ void CHistoryCollector::ClearHistoryLine(wstring_view errStr)
{ {
if (nullptr != m_pCalcDisplay) if (nullptr != m_pCalcDisplay)
{ {
m_pCalcDisplay->SetExpressionDisplay(std::make_shared<CalculatorVector<std::pair<std::wstring, int>>>(), std::make_shared<CalculatorVector<std::shared_ptr<IExpressionCommand>>>()); m_pCalcDisplay->SetExpressionDisplay(std::make_shared<CalculatorVector<std::pair<std::wstring, int>>>(),
std::make_shared<CalculatorVector<std::shared_ptr<IExpressionCommand>>>());
} }
m_iCurLineHistStart = -1; // It will get recomputed at the first Opnd m_iCurLineHistStart = -1; // It will get recomputed at the first Opnd
ReinitHistory(); ReinitHistory();
} }
} }
// Adds the given string psz to the globally maintained current equation string at the end. // Adds the given string psz to the globally maintained current equation string at the end.
// Also returns the 0 based index in the string just added. Can throw out of memory error // Also returns the 0 based index in the string just added. Can throw out of memory error
int CHistoryCollector::IchAddSzToEquationSz(wstring_view str, int icommandIndex) int CHistoryCollector::IchAddSzToEquationSz(wstring_view str, int icommandIndex)
@ -392,7 +391,6 @@ void CHistoryCollector::SetExpressionDisplay()
{ {
m_pCalcDisplay->SetExpressionDisplay(m_spTokens, m_spCommands); m_pCalcDisplay->SetExpressionDisplay(m_spTokens, m_spCommands);
} }
} }
int CHistoryCollector::AddCommand(_In_ const std::shared_ptr<IExpressionCommand>& spCommand) int CHistoryCollector::AddCommand(_In_ const std::shared_ptr<IExpressionCommand>& spCommand)

View file

@ -7,20 +7,15 @@ using namespace std;
namespace CalcEngine namespace CalcEngine
{ {
Number::Number() noexcept : Number::Number() noexcept : Number(1, 0, { 0 })
Number(1, 0, { 0 }) {
{} }
Number::Number(int32_t sign, int32_t exp, vector<uint32_t> const& mantissa) noexcept : Number::Number(int32_t sign, int32_t exp, vector<uint32_t> const& mantissa) noexcept : m_sign{ sign }, m_exp{ exp }, m_mantissa{ mantissa }
m_sign{ sign }, {
m_exp{ exp }, }
m_mantissa{ mantissa }
{}
Number::Number(PNUMBER p) noexcept : Number::Number(PNUMBER p) noexcept : m_sign{ p->sign }, m_exp{ p->exp }, m_mantissa{}
m_sign{ p->sign },
m_exp{ p->exp },
m_mantissa{}
{ {
m_mantissa.reserve(p->cdigit); m_mantissa.reserve(p->cdigit);
copy(p->mant, p->mant + p->cdigit, back_inserter(m_mantissa)); copy(p->mant, p->mant + p->cdigit, back_inserter(m_mantissa));

View file

@ -7,10 +7,9 @@ using namespace std;
namespace CalcEngine namespace CalcEngine
{ {
Rational::Rational() noexcept : Rational::Rational() noexcept : m_p{}, m_q{ 1, 0, { 1 } }
m_p{}, {
m_q{ 1, 0, { 1 } } }
{}
Rational::Rational(Number const& n) noexcept Rational::Rational(Number const& n) noexcept
{ {
@ -24,10 +23,9 @@ namespace CalcEngine
m_q = Number(1, qExp, { 1 }); m_q = Number(1, qExp, { 1 });
} }
Rational::Rational(Number const& p, Number const& q) noexcept : Rational::Rational(Number const& p, Number const& q) noexcept : m_p{ p }, m_q{ q }
m_p{ p }, {
m_q{ q } }
{}
Rational::Rational(int32_t i) Rational::Rational(int32_t i)
{ {
@ -60,10 +58,9 @@ namespace CalcEngine
m_q = Number{ temp.Q() }; m_q = Number{ temp.Q() };
} }
Rational::Rational(PRAT prat) noexcept : Rational::Rational(PRAT prat) noexcept : m_p{ Number{ prat->pp } }, m_q{ Number{ prat->pq } }
m_p{ Number{prat->pp} }, {
m_q{ Number{prat->pq} } }
{}
PRAT Rational::ToPRAT() const PRAT Rational::ToPRAT() const
{ {
@ -353,7 +350,8 @@ namespace CalcEngine
/// Calculate the remainder after division, the sign of a result will match the sign of lhs. /// Calculate the remainder after division, the sign of a result will match the sign of lhs.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This function has the same behavior as the standard C/C++ operator '%', to calculate the modulus after division instead, use <see cref="Rational::operator%"/> instead. /// This function has the same behavior as the standard C/C++ operator '%', to calculate the modulus after division instead, use <see
/// cref="Rational::operator%"/> instead.
/// </remarks> /// </remarks>
Rational operator%(Rational lhs, Rational const& rhs) Rational operator%(Rational lhs, Rational const& rhs)
{ {

View file

@ -58,42 +58,43 @@ void CCalcEngine::InitialOneTimeOnlySetup(CalculationManager::IResourceProvider&
// CCalcEngine::CCalcEngine // CCalcEngine::CCalcEngine
// //
////////////////////////////////////////////////// //////////////////////////////////////////////////
CCalcEngine::CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider, __in_opt ICalcDisplay *pCalcDisplay, __in_opt shared_ptr<IHistoryDisplay> pHistoryDisplay) : CCalcEngine::CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider,
m_fPrecedence(fPrecedence), __in_opt ICalcDisplay* pCalcDisplay, __in_opt shared_ptr<IHistoryDisplay> pHistoryDisplay)
m_fIntegerMode(fIntegerMode), : m_fPrecedence(fPrecedence)
m_pCalcDisplay(pCalcDisplay), , m_fIntegerMode(fIntegerMode)
m_resourceProvider(pResourceProvider), , m_pCalcDisplay(pCalcDisplay)
m_nOpCode(0), , m_resourceProvider(pResourceProvider)
m_nPrevOpCode(0), , m_nOpCode(0)
m_bChangeOp(false), , m_nPrevOpCode(0)
m_bRecord(false), , m_bChangeOp(false)
m_bSetCalcState(false), , m_bRecord(false)
m_input(DEFAULT_DEC_SEPARATOR), , m_bSetCalcState(false)
m_nFE(FMT_FLOAT), , m_input(DEFAULT_DEC_SEPARATOR)
m_memoryValue{ make_unique<Rational>() }, , m_nFE(FMT_FLOAT)
m_holdVal{}, , m_memoryValue{ make_unique<Rational>() }
m_currentVal{}, , m_holdVal{}
m_lastVal{}, , m_currentVal{}
m_parenVals{}, , m_lastVal{}
m_precedenceVals{}, , m_parenVals{}
m_bError(false), , m_precedenceVals{}
m_bInv(false), , m_bError(false)
m_bNoPrevEqu(true), , m_bInv(false)
m_radix(DEFAULT_RADIX), , m_bNoPrevEqu(true)
m_precision(DEFAULT_PRECISION), , m_radix(DEFAULT_RADIX)
m_cIntDigitsSav(DEFAULT_MAX_DIGITS), , m_precision(DEFAULT_PRECISION)
m_decGrouping(), , m_cIntDigitsSav(DEFAULT_MAX_DIGITS)
m_numberString(DEFAULT_NUMBER_STR), , m_decGrouping()
m_nTempCom(0), , m_numberString(DEFAULT_NUMBER_STR)
m_openParenCount(0), , m_nTempCom(0)
m_nOp(), , m_openParenCount(0)
m_nPrecOp(), , m_nOp()
m_precedenceOpCount(0), , m_nPrecOp()
m_nLastCom(0), , m_precedenceOpCount(0)
m_angletype(ANGLE_DEG), , m_nLastCom(0)
m_numwidth(QWORD_WIDTH), , m_angletype(ANGLE_DEG)
m_HistoryCollector(pCalcDisplay, pHistoryDisplay, DEFAULT_DEC_SEPARATOR), , m_numwidth(QWORD_WIDTH)
m_groupSeparator(DEFAULT_GRP_SEPARATOR) , m_HistoryCollector(pCalcDisplay, pHistoryDisplay, DEFAULT_DEC_SEPARATOR)
, m_groupSeparator(DEFAULT_GRP_SEPARATOR)
{ {
InitChopNumbers(); InitChopNumbers();

View file

@ -20,16 +20,16 @@
using namespace std; using namespace std;
using namespace CalcEngine; using namespace CalcEngine;
namespace { namespace
{
// NPrecedenceOfOp // NPrecedenceOfOp
// //
// returns a virtual number for precedence for the operator. We expect binary operator only, otherwise the lowest number // returns a virtual number for precedence for the operator. We expect binary operator only, otherwise the lowest number
// 0 is returned. Higher the number, higher the precedence of the operator. // 0 is returned. Higher the number, higher the precedence of the operator.
int NPrecedenceOfOp(int nopCode) int NPrecedenceOfOp(int nopCode)
{ {
static uint8_t rgbPrec[] = { 0,0, IDC_OR,0, IDC_XOR,0, IDC_AND,1, static uint8_t rgbPrec[] = { 0, 0, IDC_OR, 0, IDC_XOR, 0, IDC_AND, 1, IDC_ADD, 2, IDC_SUB, 2, IDC_RSHF,
IDC_ADD,2, IDC_SUB,2, IDC_RSHF,3, IDC_LSHF,3, 3, IDC_LSHF, 3, IDC_MOD, 3, IDC_DIV, 3, IDC_MUL, 3, IDC_PWR, 4, IDC_ROOT, 4 };
IDC_MOD,3, IDC_DIV,3, IDC_MUL,3, IDC_PWR,4, IDC_ROOT, 4 };
unsigned int iPrec; unsigned int iPrec;
iPrec = 0; iPrec = 0;
@ -42,7 +42,6 @@ namespace {
iPrec = 0; iPrec = 0;
} }
return rgbPrec[iPrec + 1]; return rgbPrec[iPrec + 1];
} }
} }
@ -125,14 +124,9 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
// Toggle Record/Display mode if appropriate. // Toggle Record/Display mode if appropriate.
if (m_bRecord) if (m_bRecord)
{ {
if (IsOpInRange(wParam, IDC_AND, IDC_MMINUS) || if (IsOpInRange(wParam, IDC_AND, IDC_MMINUS) || IsOpInRange(wParam, IDC_OPENP, IDC_CLOSEP) || IsOpInRange(wParam, IDM_HEX, IDM_BIN)
IsOpInRange(wParam, IDC_OPENP, IDC_CLOSEP) || || IsOpInRange(wParam, IDM_QWORD, IDM_BYTE) || IsOpInRange(wParam, IDM_DEG, IDM_GRAD)
IsOpInRange(wParam, IDM_HEX, IDM_BIN) || || IsOpInRange(wParam, IDC_BINEDITSTART, IDC_BINEDITSTART + 63) || (IDC_INV == wParam) || (IDC_SIGN == wParam && 10 != m_radix))
IsOpInRange(wParam, IDM_QWORD, IDM_BYTE) ||
IsOpInRange(wParam, IDM_DEG, IDM_GRAD) ||
IsOpInRange(wParam, IDC_BINEDITSTART, IDC_BINEDITSTART + 63) ||
(IDC_INV == wParam) ||
(IDC_SIGN == wParam && 10 != m_radix))
{ {
m_bRecord = false; m_bRecord = false;
m_currentVal = m_input.ToRational(m_radix, m_precision); m_currentVal = m_input.ToRational(m_radix, m_precision);
@ -272,7 +266,6 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
m_HistoryCollector.PopLastOpndStart(); m_HistoryCollector.PopLastOpndStart();
goto DoPrecedenceCheckAgain; goto DoPrecedenceCheckAgain;
} }
} }
} }
@ -337,11 +330,9 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
/* reset the m_bInv flag and indicators if it is set /* reset the m_bInv flag and indicators if it is set
and have been used */ and have been used */
if (m_bInv && if (m_bInv
((wParam == IDC_CHOP) || && ((wParam == IDC_CHOP) || (wParam == IDC_SIN) || (wParam == IDC_COS) || (wParam == IDC_TAN) || (wParam == IDC_LN) || (wParam == IDC_DMS)
(wParam == IDC_SIN) || (wParam == IDC_COS) || (wParam == IDC_TAN) || || (wParam == IDC_DEGREES) || (wParam == IDC_SINH) || (wParam == IDC_COSH) || (wParam == IDC_TANH)))
(wParam == IDC_LN) || (wParam == IDC_DMS) || (wParam == IDC_DEGREES) ||
(wParam == IDC_SINH) || (wParam == IDC_COSH) || (wParam == IDC_TANH)))
{ {
m_bInv = false; m_bInv = false;
} }
@ -386,13 +377,13 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
m_nPrevOpCode = 0; m_nPrevOpCode = 0;
m_bNoPrevEqu = true; m_bNoPrevEqu = true;
/* clear the parenthesis status box indicator, this will not be /* clear the parenthesis status box indicator, this will not be
cleared for CENTR */ cleared for CENTR */
if (nullptr != m_pCalcDisplay) if (nullptr != m_pCalcDisplay)
{ {
m_pCalcDisplay->SetParenthesisNumber(0); m_pCalcDisplay->SetParenthesisNumber(0);
m_pCalcDisplay->SetExpressionDisplay(make_shared<CalculatorVector<pair<wstring, int>>>(), make_shared<CalculatorVector<shared_ptr<IExpressionCommand>>>()); m_pCalcDisplay->SetExpressionDisplay(make_shared<CalculatorVector<pair<wstring, int>>>(),
make_shared<CalculatorVector<shared_ptr<IExpressionCommand>>>());
} }
m_HistoryCollector.ClearHistoryLine(wstring()); m_HistoryCollector.ClearHistoryLine(wstring());
@ -485,7 +476,8 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
m_HistoryCollector.CompleteHistoryLine(groupedString); m_HistoryCollector.CompleteHistoryLine(groupedString);
if (nullptr != m_pCalcDisplay) if (nullptr != m_pCalcDisplay)
{ {
m_pCalcDisplay->SetExpressionDisplay(make_shared<CalculatorVector<pair<wstring, int>>>(), make_shared<CalculatorVector<shared_ptr<IExpressionCommand>>>()); m_pCalcDisplay->SetExpressionDisplay(make_shared<CalculatorVector<pair<wstring, int>>>(),
make_shared<CalculatorVector<shared_ptr<IExpressionCommand>>>());
} }
} }
@ -749,7 +741,6 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam)
m_bInv = !m_bInv; m_bInv = !m_bInv;
break; break;
} }
} }
// Helper function to resolve one item on the precedence stack. // Helper function to resolve one item on the precedence stack.
@ -814,7 +805,6 @@ void CCalcEngine::CheckAndAddLastBinOpToHistory(bool addToHistory)
// So erase the last operand // So erase the last operand
m_HistoryCollector.RemoveLastOpndFromHistory(); m_HistoryCollector.RemoveLastOpndFromHistory();
} }
} }
else if (m_HistoryCollector.FOpndAddedToHistory() && !m_bError) else if (m_HistoryCollector.FOpndAddedToHistory() && !m_bError)
{ {
@ -823,8 +813,7 @@ void CCalcEngine::CheckAndAddLastBinOpToHistory(bool addToHistory)
// Let us make a current value =. So in case of 4 SQRT (or a equation under braces) and then a new equation is started, we can just form // Let us make a current value =. So in case of 4 SQRT (or a equation under braces) and then a new equation is started, we can just form
// a useful equation of sqrt(4) = 2 and continue a new equation from now on. But no point in doing this for things like // a useful equation of sqrt(4) = 2 and continue a new equation from now on. But no point in doing this for things like
// MR, SUM etc. All you will get is 5 = 5 kind of no useful equation. // MR, SUM etc. All you will get is 5 = 5 kind of no useful equation.
if ((IsUnaryOpCode(m_nLastCom) || IDC_SIGN == m_nLastCom || IDC_CLOSEP == m_nLastCom) && if ((IsUnaryOpCode(m_nLastCom) || IDC_SIGN == m_nLastCom || IDC_CLOSEP == m_nLastCom) && 0 == m_openParenCount)
0 == m_openParenCount)
{ {
if (addToHistory) if (addToHistory)
{ {
@ -877,8 +866,7 @@ struct FunctionNameElement
}; };
// Table for each unary operator // Table for each unary operator
static const std::unordered_map<int, FunctionNameElement> unaryOperatorStringTable = static const std::unordered_map<int, FunctionNameElement> unaryOperatorStringTable = {
{
{ IDC_CHOP, { L"", SIDS_FRAC } }, { IDC_CHOP, { L"", SIDS_FRAC } },
{ IDC_SIN, { SIDS_SIND, SIDS_ASIND, SIDS_SINR, SIDS_ASINR, SIDS_SING, SIDS_ASING } }, { IDC_SIN, { SIDS_SIND, SIDS_ASIND, SIDS_SINR, SIDS_ASINR, SIDS_SING, SIDS_ASING } },

View file

@ -25,7 +25,6 @@ constexpr uint32_t MAX_GROUPING_SIZE = 16;
constexpr wstring_view c_decPreSepStr = L"[+-]?(\\d*)["; constexpr wstring_view c_decPreSepStr = L"[+-]?(\\d*)[";
constexpr wstring_view c_decPostSepStr = L"]?(\\d*)(?:e[+-]?(\\d*))?$"; constexpr wstring_view c_decPostSepStr = L"]?(\\d*)(?:e[+-]?(\\d*))?$";
/****************************************************************************\ /****************************************************************************\
* void DisplayNum(void) * void DisplayNum(void)
* *
@ -37,7 +36,8 @@ constexpr wstring_view c_decPostSepStr = L"]?(\\d*)(?:e[+-]?(\\d*))?$";
// //
// State of calc last time DisplayNum was called // State of calc last time DisplayNum was called
// //
typedef struct { typedef struct
{
Rational value; Rational value;
int32_t precision; int32_t precision;
uint32_t radix; uint32_t radix;
@ -84,15 +84,8 @@ void CCalcEngine::DisplayNum(void)
// something important has changed since the last time DisplayNum was // something important has changed since the last time DisplayNum was
// called. // called.
// //
if (m_bRecord || if (m_bRecord || gldPrevious.value != m_currentVal || gldPrevious.precision != m_precision || gldPrevious.radix != m_radix || gldPrevious.nFE != (int)m_nFE
gldPrevious.value != m_currentVal || || gldPrevious.bUseSep != true || gldPrevious.numwidth != m_numwidth || gldPrevious.fIntMath != m_fIntegerMode || gldPrevious.bRecord != m_bRecord)
gldPrevious.precision != m_precision ||
gldPrevious.radix != m_radix ||
gldPrevious.nFE != (int)m_nFE ||
gldPrevious.bUseSep != true ||
gldPrevious.numwidth != m_numwidth ||
gldPrevious.fIntMath != m_fIntegerMode ||
gldPrevious.bRecord != m_bRecord)
{ {
gldPrevious.precision = m_precision; gldPrevious.precision = m_precision;
gldPrevious.radix = m_radix; gldPrevious.radix = m_radix;

View file

@ -226,4 +226,3 @@ void CCalcEngine::DisplayError(uint32_t nError)
m_HistoryCollector.ClearHistoryLine(errorString); m_HistoryCollector.ClearHistoryLine(errorString);
} }

View file

@ -7,11 +7,12 @@
using namespace std; using namespace std;
using namespace CalculationManager; using namespace CalculationManager;
CalculatorHistory::CalculatorHistory(size_t maxSize) : CalculatorHistory::CalculatorHistory(size_t maxSize) : m_maxHistorySize(maxSize)
m_maxHistorySize(maxSize) {
{} }
unsigned int CalculatorHistory::AddToHistory(_In_ shared_ptr<CalculatorVector <pair<wstring, int>>> const &tokens, _In_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const &commands, _In_ wstring_view result) unsigned int CalculatorHistory::AddToHistory(_In_ shared_ptr<CalculatorVector<pair<wstring, int>>> const& tokens,
_In_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const& commands, _In_ wstring_view result)
{ {
unsigned int addedIndex; unsigned int addedIndex;
wstring generatedExpression; wstring generatedExpression;
@ -31,7 +32,6 @@ unsigned int CalculatorHistory::AddToHistory(_In_ shared_ptr<CalculatorVector <p
return addedIndex; return addedIndex;
} }
unsigned int CalculatorHistory::AddItem(_In_ shared_ptr<HISTORYITEM> const& spHistoryItem) unsigned int CalculatorHistory::AddItem(_In_ shared_ptr<HISTORYITEM> const& spHistoryItem)
{ {
if (m_historyItems.size() >= m_maxHistorySize) if (m_historyItems.size() >= m_maxHistorySize)

View file

@ -26,19 +26,21 @@ namespace CalculationManager
HISTORYITEMVECTOR historyItemVector; HISTORYITEMVECTOR historyItemVector;
}; };
class CalculatorHistory : class CalculatorHistory : public IHistoryDisplay
public IHistoryDisplay
{ {
public: public:
CalculatorHistory(const size_t maxSize); CalculatorHistory(const size_t maxSize);
unsigned int AddToHistory(_In_ std::shared_ptr<CalculatorVector <std::pair<std::wstring, int>>> const &spTokens, _In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const &spCommands, std::wstring_view result); unsigned int AddToHistory(_In_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& spTokens,
_In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& spCommands, std::wstring_view result);
std::vector<std::shared_ptr<HISTORYITEM>> const& GetHistory(); std::vector<std::shared_ptr<HISTORYITEM>> const& GetHistory();
std::shared_ptr<HISTORYITEM> const& GetHistoryItem(unsigned int uIdx); std::shared_ptr<HISTORYITEM> const& GetHistoryItem(unsigned int uIdx);
void ClearHistory(); void ClearHistory();
unsigned int AddItem(_In_ std::shared_ptr<HISTORYITEM> const& spHistoryItem); unsigned int AddItem(_In_ std::shared_ptr<HISTORYITEM> const& spHistoryItem);
bool RemoveItem(unsigned int uIdx); bool RemoveItem(unsigned int uIdx);
size_t MaxHistorySize() const { return m_maxHistorySize; } size_t MaxHistorySize() const
{
return m_maxHistorySize;
}
~CalculatorHistory(void); ~CalculatorHistory(void);
private: private:

View file

@ -14,25 +14,21 @@ static constexpr size_t SERIALIZED_NUMBER_MINSIZE = 3;
// Converts Memory Command enum value to unsigned char, // Converts Memory Command enum value to unsigned char,
// while ignoring Warning C4309: 'conversion' : truncation of constant value // while ignoring Warning C4309: 'conversion' : truncation of constant value
#define MEMORY_COMMAND_TO_UNSIGNED_CHAR(c)\ #define MEMORY_COMMAND_TO_UNSIGNED_CHAR(c) __pragma(warning(push)) __pragma(warning(disable : 4309)) static_cast<unsigned char>(c) __pragma(warning(pop))
__pragma(warning(push))\
__pragma(warning(disable: 4309))\
static_cast<unsigned char>(c)\
__pragma(warning(pop))
namespace CalculationManager namespace CalculationManager
{ {
CalculatorManager::CalculatorManager(_In_ ICalcDisplay* displayCallback, _In_ IResourceProvider* resourceProvider) : CalculatorManager::CalculatorManager(_In_ ICalcDisplay* displayCallback, _In_ IResourceProvider* resourceProvider)
m_displayCallback(displayCallback), : m_displayCallback(displayCallback)
m_currentCalculatorEngine(nullptr), , m_currentCalculatorEngine(nullptr)
m_resourceProvider(resourceProvider), , m_resourceProvider(resourceProvider)
m_inHistoryItemLoadMode(false), , m_inHistoryItemLoadMode(false)
m_persistedPrimaryValue(), , m_persistedPrimaryValue()
m_isExponentialFormat(false), , m_isExponentialFormat(false)
m_currentDegreeMode(Command::CommandNULL), , m_currentDegreeMode(Command::CommandNULL)
m_savedDegreeMode(Command::CommandDEG), , m_savedDegreeMode(Command::CommandDEG)
m_pStdHistory(new CalculatorHistory(MAX_HISTORY_ITEMS)), , m_pStdHistory(new CalculatorHistory(MAX_HISTORY_ITEMS))
m_pSciHistory(new CalculatorHistory(MAX_HISTORY_ITEMS)) , m_pSciHistory(new CalculatorHistory(MAX_HISTORY_ITEMS))
{ {
CCalcEngine::InitialOneTimeOnlySetup(*m_resourceProvider); CCalcEngine::InitialOneTimeOnlySetup(*m_resourceProvider);
} }
@ -89,7 +85,8 @@ namespace CalculationManager
/// Used to set the expression display value on ViewModel /// Used to set the expression display value on ViewModel
/// </summary> /// </summary>
/// <param name="expressionString">wstring representing expression to be displayed</param> /// <param name="expressionString">wstring representing expression to be displayed</param>
void CalculatorManager::SetExpressionDisplay(_Inout_ shared_ptr<CalculatorVector<pair<wstring, int>>> const &tokens, _Inout_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const &commands) void CalculatorManager::SetExpressionDisplay(_Inout_ shared_ptr<CalculatorVector<pair<wstring, int>>> const& tokens,
_Inout_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const& commands)
{ {
if (!m_inHistoryItemLoadMode) if (!m_inHistoryItemLoadMode)
{ {
@ -165,7 +162,8 @@ namespace CalculationManager
{ {
if (!m_standardCalculatorEngine) if (!m_standardCalculatorEngine)
{ {
m_standardCalculatorEngine = make_unique<CCalcEngine>(false /* Respect Order of Operations */, false /* Set to Integer Mode */, m_resourceProvider, this, m_pStdHistory); m_standardCalculatorEngine =
make_unique<CCalcEngine>(false /* Respect Order of Operations */, false /* Set to Integer Mode */, m_resourceProvider, this, m_pStdHistory);
} }
m_currentCalculatorEngine = m_standardCalculatorEngine.get(); m_currentCalculatorEngine = m_standardCalculatorEngine.get();
@ -183,7 +181,8 @@ namespace CalculationManager
{ {
if (!m_scientificCalculatorEngine) if (!m_scientificCalculatorEngine)
{ {
m_scientificCalculatorEngine = make_unique<CCalcEngine>(true /* Respect Order of Operations */, false /* Set to Integer Mode */, m_resourceProvider, this, m_pSciHistory); m_scientificCalculatorEngine =
make_unique<CCalcEngine>(true /* Respect Order of Operations */, false /* Set to Integer Mode */, m_resourceProvider, this, m_pSciHistory);
} }
m_currentCalculatorEngine = m_scientificCalculatorEngine.get(); m_currentCalculatorEngine = m_scientificCalculatorEngine.get();
@ -200,7 +199,8 @@ namespace CalculationManager
{ {
if (!m_programmerCalculatorEngine) if (!m_programmerCalculatorEngine)
{ {
m_programmerCalculatorEngine = make_unique<CCalcEngine>(true /* Respect Order of Operations */, true /* Set to Integer Mode */, m_resourceProvider, this, nullptr); m_programmerCalculatorEngine =
make_unique<CCalcEngine>(true /* Respect Order of Operations */, true /* Set to Integer Mode */, m_resourceProvider, this, nullptr);
} }
m_currentCalculatorEngine = m_programmerCalculatorEngine.get(); m_currentCalculatorEngine = m_programmerCalculatorEngine.get();
@ -209,7 +209,6 @@ namespace CalculationManager
m_currentCalculatorEngine->ChangePrecision(static_cast<int>(CalculatorPrecision::ProgrammerModePrecision)); m_currentCalculatorEngine->ChangePrecision(static_cast<int>(CalculatorPrecision::ProgrammerModePrecision));
} }
/// <summary> /// <summary>
/// Send command to the Calc Engine /// Send command to the Calc Engine
/// Cast Command Enum to OpCode. /// Cast Command Enum to OpCode.
@ -220,8 +219,8 @@ namespace CalculationManager
{ {
// When the expression line is cleared, we save the current state, which includes, // When the expression line is cleared, we save the current state, which includes,
// primary display, memory, and degree mode // primary display, memory, and degree mode
if (command == Command::CommandCLEAR || command == Command::CommandEQU if (command == Command::CommandCLEAR || command == Command::CommandEQU || command == Command::ModeBasic || command == Command::ModeScientific
|| command == Command::ModeBasic || command == Command::ModeScientific || command == Command::ModeProgrammer) || command == Command::ModeProgrammer)
{ {
switch (command) switch (command)
{ {
@ -435,8 +434,8 @@ namespace CalculationManager
for (auto commandItr = serializedData.begin(); commandItr != serializedData.end(); ++commandItr) for (auto commandItr = serializedData.begin(); commandItr != serializedData.end(); ++commandItr)
{ {
if (*commandItr >= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizeNumber) && if (*commandItr >= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizeNumber)
*commandItr <= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizedNumberClearAll)) && *commandItr <= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizedNumberClearAll))
{ {
// MemoryCommands(which have values above 255) are pushed on m_savedCommands upon casting to unsigned char. // MemoryCommands(which have values above 255) are pushed on m_savedCommands upon casting to unsigned char.
// SerializeCommands uses m_savedCommands, which is then used in DeSerializeCommands. // SerializeCommands uses m_savedCommands, which is then used in DeSerializeCommands.
@ -673,9 +672,7 @@ namespace CalculationManager
vector<shared_ptr<HISTORYITEM>> const& CalculatorManager::GetHistoryItems(_In_ CALCULATOR_MODE mode) vector<shared_ptr<HISTORYITEM>> const& CalculatorManager::GetHistoryItems(_In_ CALCULATOR_MODE mode)
{ {
return (mode == CM_STD) ? return (mode == CM_STD) ? m_pStdHistory->GetHistory() : m_pSciHistory->GetHistory();
m_pStdHistory->GetHistory() :
m_pSciHistory->GetHistory();
} }
shared_ptr<HISTORYITEM> const& CalculatorManager::GetHistoryItem(_In_ unsigned int uIdx) shared_ptr<HISTORYITEM> const& CalculatorManager::GetHistoryItem(_In_ unsigned int uIdx)

View file

@ -91,7 +91,8 @@ namespace CalculationManager
// ICalcDisplay // ICalcDisplay
void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override; void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override;
void SetIsInError(bool isError) override; void SetIsInError(bool isError) override;
void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const &tokens, _Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const &commands) override; void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& tokens,
_Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& commands) override;
void SetMemorizedNumbers(_In_ const std::vector<std::wstring>& memorizedNumbers) override; void SetMemorizedNumbers(_In_ const std::vector<std::wstring>& memorizedNumbers) override;
void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override; void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override;
void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override; void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override;
@ -101,7 +102,6 @@ namespace CalculationManager
void BinaryOperatorReceived() override; void BinaryOperatorReceived() override;
void MemoryItemChanged(unsigned int indexOfMemory) override; void MemoryItemChanged(unsigned int indexOfMemory) override;
CalculatorManager(ICalcDisplay* displayCallback, IResourceProvider* resourceProvider); CalculatorManager(ICalcDisplay* displayCallback, IResourceProvider* resourceProvider);
~CalculatorManager(); ~CalculatorManager();
@ -128,7 +128,10 @@ namespace CalculationManager
void MemorizedNumberClearAll(); void MemorizedNumberClearAll();
bool IsEngineRecording(); bool IsEngineRecording();
std::vector<unsigned char> GetSavedCommands(){ return m_savedCommands; } std::vector<unsigned char> GetSavedCommands()
{
return m_savedCommands;
}
void SetRadix(RADIX_TYPE iRadixType); void SetRadix(RADIX_TYPE iRadixType);
void SetMemorizedNumbersString(); void SetMemorizedNumbersString();
std::wstring GetResultForRadix(uint32_t radix, int32_t precision); std::wstring GetResultForRadix(uint32_t radix, int32_t precision);
@ -141,7 +144,10 @@ namespace CalculationManager
std::shared_ptr<HISTORYITEM> const& GetHistoryItem(_In_ unsigned int uIdx); std::shared_ptr<HISTORYITEM> const& GetHistoryItem(_In_ unsigned int uIdx);
bool RemoveHistoryItem(_In_ unsigned int uIdx); bool RemoveHistoryItem(_In_ unsigned int uIdx);
void ClearHistory(); void ClearHistory();
size_t MaxHistorySize() const { return m_pHistory->MaxHistorySize(); } size_t MaxHistorySize() const
{
return m_pHistory->MaxHistorySize();
}
CalculationManager::Command GetCurrentDegreeMode(); CalculationManager::Command GetCurrentDegreeMode();
void SetHistory(_In_ CALCULATOR_MODE eMode, _In_ std::vector<std::shared_ptr<HISTORYITEM>> const& history); void SetHistory(_In_ CALCULATOR_MODE eMode, _In_ std::vector<std::shared_ptr<HISTORYITEM>> const& history);
void SetInHistoryItemLoadMode(_In_ bool isHistoryItemLoadMode); void SetInHistoryItemLoadMode(_In_ bool isHistoryItemLoadMode);

View file

@ -8,7 +8,9 @@ namespace CalculationManager
class IResourceProvider class IResourceProvider
{ {
public: public:
virtual ~IResourceProvider() { } virtual ~IResourceProvider()
{
}
// Should return a string from the resource table for strings used // Should return a string from the resource table for strings used
// by the calculation engine. The strings that must be defined // by the calculation engine. The strings that must be defined

View file

@ -7,9 +7,19 @@ namespace UnitConversionManager
{ {
enum class Command enum class Command
{ {
Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Decimal, Decimal,
Negate, Backspace, Negate,
Backspace,
Clear, Clear,
Reset, Reset,
None None
@ -20,9 +30,19 @@ namespace CurrencyConversionManager
{ {
enum class Command enum class Command
{ {
Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Decimal, Decimal,
Negate, Backspace, Negate,
Backspace,
Clear, Clear,
None None
}; };
@ -85,7 +105,6 @@ namespace CalculationManager
CommandCOSH = 106, CommandCOSH = 106,
CommandTANH = 107, CommandTANH = 107,
CommandLN = 108, CommandLN = 108,
CommandLOG = 109, CommandLOG = 109,
CommandSQRT = 110, CommandSQRT = 110,

View file

@ -14,7 +14,8 @@ constexpr wchar_t chExp = L'e';
constexpr wchar_t chPlus = L'+'; constexpr wchar_t chPlus = L'+';
CParentheses::CParentheses(_In_ int command) : m_command(command) CParentheses::CParentheses(_In_ int command) : m_command(command)
{} {
}
int CParentheses::GetCommand() const int CParentheses::GetCommand() const
{ {
@ -73,7 +74,8 @@ void CUnaryCommand::Accept(_In_ ISerializeCommandVisitor &commandVisitor)
} }
CBinaryCommand::CBinaryCommand(int command) : m_command(command) CBinaryCommand::CBinaryCommand(int command) : m_command(command)
{} {
}
void CBinaryCommand::SetCommand(int command) void CBinaryCommand::SetCommand(int command)
{ {
@ -95,14 +97,10 @@ void CBinaryCommand::Accept(_In_ ISerializeCommandVisitor &commandVisitor)
commandVisitor.Visit(*this); commandVisitor.Visit(*this);
} }
COpndCommand::COpndCommand(shared_ptr<CalculatorVector<int>> const &commands, bool fNegative, bool fDecimal, bool fSciFmt) : COpndCommand::COpndCommand(shared_ptr<CalculatorVector<int>> const& commands, bool fNegative, bool fDecimal, bool fSciFmt)
m_commands(commands), : m_commands(commands), m_fNegative(fNegative), m_fSciFmt(fSciFmt), m_fDecimal(fDecimal), m_fInitialized(false), m_value{}
m_fNegative(fNegative), {
m_fSciFmt(fSciFmt), }
m_fDecimal(fDecimal),
m_fInitialized(false),
m_value{}
{}
void COpndCommand::Initialize(Rational const& rat) void COpndCommand::Initialize(Rational const& rat)
{ {

View file

@ -49,11 +49,7 @@ private:
class COpndCommand final : public IOpndCommand class COpndCommand final : public IOpndCommand
{ {
public: public:
COpndCommand( COpndCommand(std::shared_ptr<CalculatorVector<int>> const& commands, bool fNegative, bool fDecimal, bool fSciFmt);
std::shared_ptr<CalculatorVector<int>> const &commands,
bool fNegative,
bool fDecimal,
bool fSciFmt);
void Initialize(CalcEngine::Rational const& rat); void Initialize(CalcEngine::Rational const& rat);
const std::shared_ptr<CalculatorVector<int>>& GetCommands() const override; const std::shared_ptr<CalculatorVector<int>>& GetCommands() const override;

View file

@ -45,7 +45,6 @@
#define IDC_WORD IDM_WORD #define IDC_WORD IDM_WORD
#define IDC_BYTE IDM_BYTE #define IDC_BYTE IDM_BYTE
// Key IDs: // Key IDs:
// These id's must be consecutive from IDC_FIRSTCONTROL to IDC_LASTCONTROL. // These id's must be consecutive from IDC_FIRSTCONTROL to IDC_LASTCONTROL.
// The actual values don't matter but the order and sequence are very important. // The actual values don't matter but the order and sequence are very important.
@ -77,7 +76,6 @@
#define IDC_ROOT 96 #define IDC_ROOT 96
#define IDC_PWR 97 #define IDC_PWR 97
#define IDC_UNARYFIRST IDC_CHOP #define IDC_UNARYFIRST IDC_CHOP
#define IDC_CHOP 98 // Unary operators must be between IDC_CHOP and IDC_EQU #define IDC_CHOP 98 // Unary operators must be between IDC_CHOP and IDC_EQU
#define IDC_ROL 99 #define IDC_ROL 99
@ -116,7 +114,6 @@
#define IDC_EXP 127 #define IDC_EXP 127
#define IDC_OPENP 128 #define IDC_OPENP 128
#define IDC_CLOSEP 129 #define IDC_CLOSEP 129
@ -208,9 +205,7 @@
#define IDC_BINPOS63 763 #define IDC_BINPOS63 763
#define IDC_BINEDITEND 763 #define IDC_BINEDITEND 763
// The strings in the following range IDS_ENGINESTR_FIRST ... IDS_ENGINESTR_MAX are strings allocated in the // The strings in the following range IDS_ENGINESTR_FIRST ... IDS_ENGINESTR_MAX are strings allocated in the
// resource for the purpose internal to Engine and cant be used by the clients // resource for the purpose internal to Engine and cant be used by the clients
#define IDS_ENGINESTR_FIRST 0 #define IDS_ENGINESTR_FIRST 0
#define IDS_ENGINESTR_MAX 200 #define IDS_ENGINESTR_MAX 200

View file

@ -31,7 +31,8 @@
// The real exports follows later // The real exports follows later
// This is expected to be in same order as IDM_QWORD, IDM_DWORD etc. // This is expected to be in same order as IDM_QWORD, IDM_DWORD etc.
enum eNUM_WIDTH { enum eNUM_WIDTH
{
QWORD_WIDTH, // Number width of 64 bits mode (default) QWORD_WIDTH, // Number width of 64 bits mode (default)
DWORD_WIDTH, // Number width of 32 bits mode DWORD_WIDTH, // Number width of 32 bits mode
WORD_WIDTH, // Number width of 16 bits mode WORD_WIDTH, // Number width of 16 bits mode
@ -50,31 +51,53 @@ namespace CalculatorEngineTests
class CalcEngineTests; class CalcEngineTests;
} }
class CCalcEngine { class CCalcEngine
{
public: public:
CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider, __in_opt ICalcDisplay *pCalcDisplay, __in_opt std::shared_ptr<IHistoryDisplay> pHistoryDisplay); CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider, __in_opt ICalcDisplay* pCalcDisplay,
__in_opt std::shared_ptr<IHistoryDisplay> pHistoryDisplay);
void ProcessCommand(OpCode wID); void ProcessCommand(OpCode wID);
void DisplayError(uint32_t nError); void DisplayError(uint32_t nError);
std::unique_ptr<CalcEngine::Rational> PersistedMemObject(); std::unique_ptr<CalcEngine::Rational> PersistedMemObject();
void PersistedMemObject(CalcEngine::Rational const& memObject); void PersistedMemObject(CalcEngine::Rational const& memObject);
bool FInErrorState() { return m_bError; } bool FInErrorState()
bool FInRecordingState() { return m_bRecord; } {
return m_bError;
}
bool FInRecordingState()
{
return m_bRecord;
}
void SettingsChanged(); void SettingsChanged();
bool IsCurrentTooBigForTrig(); bool IsCurrentTooBigForTrig();
int GetCurrentRadix(); int GetCurrentRadix();
std::wstring GetCurrentResultForRadix(uint32_t radix, int32_t precision); std::wstring GetCurrentResultForRadix(uint32_t radix, int32_t precision);
void ChangePrecision(int32_t precision) { m_precision = precision; ChangeConstants(m_radix, precision); } void ChangePrecision(int32_t precision)
{
m_precision = precision;
ChangeConstants(m_radix, precision);
}
std::wstring GroupDigitsPerRadix(std::wstring_view numberString, uint32_t radix); std::wstring GroupDigitsPerRadix(std::wstring_view numberString, uint32_t radix);
std::wstring GetStringForDisplay(CalcEngine::Rational const& rat, uint32_t radix); std::wstring GetStringForDisplay(CalcEngine::Rational const& rat, uint32_t radix);
void UpdateMaxIntDigits(); void UpdateMaxIntDigits();
wchar_t DecimalSeparator() const; wchar_t DecimalSeparator() const;
// Static methods for the instance // Static methods for the instance
static void InitialOneTimeOnlySetup(CalculationManager::IResourceProvider& resourceProvider); // Once per load time to call to initialize all shared global variables static void
InitialOneTimeOnlySetup(CalculationManager::IResourceProvider& resourceProvider); // Once per load time to call to initialize all shared global variables
// returns the ptr to string representing the operator. Mostly same as the button, but few special cases for x^y etc. // returns the ptr to string representing the operator. Mostly same as the button, but few special cases for x^y etc.
static std::wstring_view GetString(int ids) { return s_engineStrings[std::to_wstring(ids)]; } static std::wstring_view GetString(int ids)
static std::wstring_view GetString(std::wstring ids) { return s_engineStrings[ids]; } {
static std::wstring_view OpCodeToString(int nOpCode) { return GetString(IdStrFromCmdId(nOpCode)); } return s_engineStrings[std::to_wstring(ids)];
}
static std::wstring_view GetString(std::wstring ids)
{
return s_engineStrings[ids];
}
static std::wstring_view OpCodeToString(int nOpCode)
{
return GetString(IdStrFromCmdId(nOpCode));
}
static std::wstring_view OpCodeToUnaryString(int nOpCode, bool fInv, ANGLE_TYPE angletype); static std::wstring_view OpCodeToUnaryString(int nOpCode, bool fInv, ANGLE_TYPE angletype);
private: private:
@ -151,7 +174,10 @@ private:
void InitChopNumbers(); void InitChopNumbers();
static void LoadEngineStrings(CalculationManager::IResourceProvider& resourceProvider); static void LoadEngineStrings(CalculationManager::IResourceProvider& resourceProvider);
static int IdStrFromCmdId(int id) { return id - IDC_FIRSTCONTROL + IDS_ENGINESTR_FIRST; } static int IdStrFromCmdId(int id)
{
return id - IDC_FIRSTCONTROL + IDS_ENGINESTR_FIRST;
}
static std::vector<uint32_t> DigitGroupingStringToGroupingVector(std::wstring_view groupingString); static std::vector<uint32_t> DigitGroupingStringToGroupingVector(std::wstring_view groupingString);
std::wstring GroupDigits(std::wstring_view delimiter, std::vector<uint32_t> const& grouping, std::wstring_view displayString, bool isNumNegative = false); std::wstring GroupDigits(std::wstring_view delimiter, std::vector<uint32_t> const& grouping, std::wstring_view displayString, bool isNumNegative = false);

View file

@ -13,16 +13,24 @@ namespace CalcEngine
class CalcNumSec class CalcNumSec
{ {
public: public:
CalcNumSec() : CalcNumSec() : value(), m_isNegative(false)
value(), {
m_isNegative(false) }
{}
void Clear(); void Clear();
bool IsEmpty() { return value.empty(); } bool IsEmpty()
{
return value.empty();
}
bool IsNegative() { return m_isNegative; } bool IsNegative()
void IsNegative(bool isNegative) { m_isNegative = isNegative; } {
return m_isNegative;
}
void IsNegative(bool isNegative)
{
m_isNegative = isNegative;
}
std::wstring value; std::wstring value;
@ -34,16 +42,12 @@ namespace CalcEngine
{ {
public: public:
CalcInput() : CalcInput(L'.') CalcInput() : CalcInput(L'.')
{} {
}
CalcInput(wchar_t decSymbol) : CalcInput(wchar_t decSymbol) : m_hasExponent(false), m_hasDecimal(false), m_decPtIndex(0), m_decSymbol(decSymbol), m_base(), m_exponent()
m_hasExponent(false), {
m_hasDecimal(false), }
m_decPtIndex(0),
m_decSymbol(decSymbol),
m_base(),
m_exponent()
{}
void Clear(); void Clear();
bool TryToggleSign(bool isIntegerMode, std::wstring_view maxNumStr); bool TryToggleSign(bool isIntegerMode, std::wstring_view maxNumStr);

View file

@ -171,9 +171,7 @@ inline constexpr auto SIDS_ERR_INPUT_OVERFLOW = L"119";
inline constexpr auto SIDS_ERR_OUTPUT_OVERFLOW = L"120"; inline constexpr auto SIDS_ERR_OUTPUT_OVERFLOW = L"120";
// Include the resource key ID from above into this vector to load it into memory for the engine to use // Include the resource key ID from above into this vector to load it into memory for the engine to use
inline constexpr std::array<std::wstring_view, 120> g_sids = inline constexpr std::array<std::wstring_view, 120> g_sids = { SIDS_PLUS_MINUS,
{
SIDS_PLUS_MINUS,
SIDS_C, SIDS_C,
SIDS_CE, SIDS_CE,
SIDS_BACKSPACE, SIDS_BACKSPACE,
@ -292,5 +290,4 @@ inline constexpr std::array<std::wstring_view, 120> g_sids =
SIDS_ERR_UNEX_END, SIDS_ERR_UNEX_END,
SIDS_ERR_SG_INV_ERROR, SIDS_ERR_SG_INV_ERROR,
SIDS_ERR_INPUT_OVERFLOW, SIDS_ERR_INPUT_OVERFLOW,
SIDS_ERR_OUTPUT_OVERFLOW SIDS_ERR_OUTPUT_OVERFLOW };
};

View file

@ -14,7 +14,8 @@ static constexpr size_t MAXPRECDEPTH = 25;
// Helper class really a internal class to CCalcEngine, to accumulate each history line of text by collecting the // Helper class really a internal class to CCalcEngine, to accumulate each history line of text by collecting the
// operands, operator, unary operator etc. Since it is a separate entity, it can be unit tested on its own but does // operands, operator, unary operator etc. Since it is a separate entity, it can be unit tested on its own but does
// rely on CCalcEngine calling it in appropriate order. // rely on CCalcEngine calling it in appropriate order.
class CHistoryCollector { class CHistoryCollector
{
public: public:
CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol); // Can throw errors CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol); // Can throw errors
~CHistoryCollector(); ~CHistoryCollector();
@ -44,7 +45,8 @@ private:
// attaching the unary op around the last operand // attaching the unary op around the last operand
int m_lastOpStartIndex; // index of the beginning of the last operand added to the history int m_lastOpStartIndex; // index of the beginning of the last operand added to the history
int m_lastBinOpStartIndex; // index of the beginning of the last binary operator added to the history int m_lastBinOpStartIndex; // index of the beginning of the last binary operator added to the history
std::array<int, MAXPRECDEPTH> m_operandIndices; // Stack of index of opnd's beginning for each '('. A parallel array to m_hnoParNum, but abstracted independently of that std::array<int, MAXPRECDEPTH>
m_operandIndices; // Stack of index of opnd's beginning for each '('. A parallel array to m_hnoParNum, but abstracted independently of that
int m_curOperandIndex; // Stack index for the above stack int m_curOperandIndex; // Stack index for the above stack
bool m_bLastOpndBrace; // iff the last opnd in history is already braced so we can avoid putting another one for unary operator bool m_bLastOpndBrace; // iff the last opnd in history is already braced so we can avoid putting another one for unary operator
wchar_t m_decimalSymbol; wchar_t m_decimalSymbol;

View file

@ -7,11 +7,13 @@
#include "../ExpressionCommandInterface.h" #include "../ExpressionCommandInterface.h"
// Callback interface to be implemented by the clients of CCalcEngine // Callback interface to be implemented by the clients of CCalcEngine
class ICalcDisplay { class ICalcDisplay
{
public: public:
virtual void SetPrimaryDisplay(const std::wstring& pszText, bool isError) = 0; virtual void SetPrimaryDisplay(const std::wstring& pszText, bool isError) = 0;
virtual void SetIsInError(bool isInError) = 0; virtual void SetIsInError(bool isInError) = 0;
virtual void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const &tokens, _Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const &commands) = 0; virtual void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& tokens,
_Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& commands) = 0;
virtual void SetParenthesisNumber(_In_ unsigned int count) = 0; virtual void SetParenthesisNumber(_In_ unsigned int count) = 0;
virtual void OnNoRightParenAdded() = 0; virtual void OnNoRightParenAdded() = 0;
virtual void MaxDigitsReached() = 0; // not an error but still need to inform UI layer. virtual void MaxDigitsReached() = 0; // not an error but still need to inform UI layer.

View file

@ -4,8 +4,11 @@
#pragma once #pragma once
// Callback interface to be implemented by the clients of CCalcEngine if they require equation history // Callback interface to be implemented by the clients of CCalcEngine if they require equation history
class IHistoryDisplay { class IHistoryDisplay
{
public: public:
virtual ~IHistoryDisplay(){}; virtual ~IHistoryDisplay(){};
virtual unsigned int AddToHistory(_In_ std::shared_ptr<CalculatorVector <std::pair<std::wstring, int>>> const &tokens, _In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const &commands, _In_ std::wstring_view result) = 0; virtual unsigned int AddToHistory(_In_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& tokens,
_In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& commands,
_In_ std::wstring_view result) = 0;
}; };

View file

@ -4,7 +4,8 @@
#pragma once #pragma once
// This is expected to be in same order as IDM_HEX, IDM_DEC, IDM_OCT, IDM_BIN // This is expected to be in same order as IDM_HEX, IDM_DEC, IDM_OCT, IDM_BIN
enum eRADIX_TYPE { enum eRADIX_TYPE
{
HEX_RADIX, HEX_RADIX,
DEC_RADIX, DEC_RADIX,
OCT_RADIX, OCT_RADIX,

View file

@ -83,4 +83,3 @@ typedef int32_t ResultCode;
// //
// The result of this operation is undefined // The result of this operation is undefined
#define CALC_E_NORESULT ((uint32_t)0x80000009) #define CALC_E_NORESULT ((uint32_t)0x80000009)

View file

@ -130,7 +130,6 @@ void _mulnumx( PNUMBER *pa, PNUMBER b )
// If result is nonzero, or while result of carry is nonzero... // If result is nonzero, or while result of carry is nonzero...
while (mcy || cy) while (mcy || cy)
{ {
// update carry from addition(s) and multiply. // update carry from addition(s) and multiply.
cy += (TWO_MANTTYPE)ptrc[icdigit] + ((uint32_t)mcy & ((uint32_t)~BASEX)); cy += (TWO_MANTTYPE)ptrc[icdigit] + ((uint32_t)mcy & ((uint32_t)~BASEX));
@ -144,7 +143,6 @@ void _mulnumx( PNUMBER *pa, PNUMBER b )
ptrb++; ptrb++;
ptrc++; ptrc++;
} }
} }
@ -198,7 +196,6 @@ void numpowi32x( _Inout_ PNUMBER *proot, _In_ int32_t power )
} }
destroynum(*proot); destroynum(*proot);
*proot = lret; *proot = lret;
} }
void _divnumx(PNUMBER* pa, PNUMBER b, int32_t precision); void _divnumx(PNUMBER* pa, PNUMBER b, int32_t precision);
@ -363,5 +360,3 @@ void _divnumx( PNUMBER *pa, PNUMBER b, int32_t precision)
destroynum(*pa); destroynum(*pa);
*pa = c; *pa = c;
} }

View file

@ -42,8 +42,7 @@ wchar_t g_decimalSeparator = L'.';
// See also // See also
// * https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros // * https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros
// * https://sourceforge.net/p/predef/wiki/Architectures/ // * https://sourceforge.net/p/predef/wiki/Architectures/
#if defined(MIDL_PASS) || defined(RC_INVOKED) || defined(_M_CEE_PURE) \ #if defined(MIDL_PASS) || defined(RC_INVOKED) || defined(_M_CEE_PURE) || defined(_M_AMD64) || defined(__ARM_ARCH) || defined(__x86_64__) || defined(_M_ARM64)
|| defined(_M_AMD64) || defined(__ARM_ARCH) || defined(__x86_64__) || defined(_M_ARM64)
#ifndef Calc_UInt32x32To64 #ifndef Calc_UInt32x32To64
#define Calc_UInt32x32To64(a, b) ((uint64_t)((uint32_t)(a)) * (uint64_t)((uint32_t)(b))) #define Calc_UInt32x32To64(a, b) ((uint64_t)((uint32_t)(a)) * (uint64_t)((uint32_t)(b)))
@ -63,12 +62,9 @@ wchar_t g_decimalSeparator = L'.';
#define CALC_INTSAFE_E_ARITHMETIC_OVERFLOW ((int32_t)0x80070216L) // 0x216 = 534 = ERROR_ARITHMETIC_OVERFLOW #define CALC_INTSAFE_E_ARITHMETIC_OVERFLOW ((int32_t)0x80070216L) // 0x216 = 534 = ERROR_ARITHMETIC_OVERFLOW
#define CALC_ULONG_ERROR ((uint32_t)0xffffffffU) #define CALC_ULONG_ERROR ((uint32_t)0xffffffffU)
namespace { namespace
int32_t {
Calc_ULongAdd( int32_t Calc_ULongAdd(_In_ uint32_t ulAugend, _In_ uint32_t ulAddend, _Out_ uint32_t* pulResult)
_In_ uint32_t ulAugend,
_In_ uint32_t ulAddend,
_Out_ uint32_t* pulResult)
{ {
int32_t hr = CALC_INTSAFE_E_ARITHMETIC_OVERFLOW; int32_t hr = CALC_INTSAFE_E_ARITHMETIC_OVERFLOW;
*pulResult = CALC_ULONG_ERROR; *pulResult = CALC_ULONG_ERROR;
@ -82,10 +78,7 @@ namespace {
return hr; return hr;
} }
int32_t int32_t Calc_ULongLongToULong(_In_ uint64_t ullOperand, _Out_ uint32_t* pulResult)
Calc_ULongLongToULong(
_In_ uint64_t ullOperand,
_Out_ uint32_t* pulResult)
{ {
int32_t hr = CALC_INTSAFE_E_ARITHMETIC_OVERFLOW; int32_t hr = CALC_INTSAFE_E_ARITHMETIC_OVERFLOW;
*pulResult = CALC_ULONG_ERROR; *pulResult = CALC_ULONG_ERROR;
@ -99,11 +92,7 @@ namespace {
return hr; return hr;
} }
int32_t int32_t Calc_ULongMult(_In_ uint32_t ulMultiplicand, _In_ uint32_t ulMultiplier, _Out_ uint32_t* pulResult)
Calc_ULongMult(
_In_ uint32_t ulMultiplicand,
_In_ uint32_t ulMultiplier,
_Out_ uint32_t* pulResult)
{ {
uint64_t ull64Result = Calc_UInt32x32To64(ulMultiplicand, ulMultiplier); uint64_t ull64Result = Calc_UInt32x32To64(ulMultiplicand, ulMultiplier);
@ -165,7 +154,6 @@ void _destroynum( _In_ PNUMBER pnum )
} }
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: _destroyrat // FUNCTION: _destroyrat
@ -190,7 +178,6 @@ void _destroyrat( _In_ PRAT prat )
} }
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: _createnum // FUNCTION: _createnum
@ -210,9 +197,8 @@ PNUMBER _createnum( _In_ uint32_t size )
uint32_t cbAlloc; uint32_t cbAlloc;
// sizeof( MANTTYPE ) is the size of a 'digit' // sizeof( MANTTYPE ) is the size of a 'digit'
if (SUCCEEDED(Calc_ULongAdd(size, 1, &cbAlloc)) && if (SUCCEEDED(Calc_ULongAdd(size, 1, &cbAlloc)) && SUCCEEDED(Calc_ULongMult(cbAlloc, sizeof(MANTTYPE), &cbAlloc))
SUCCEEDED(Calc_ULongMult(cbAlloc, sizeof(MANTTYPE), &cbAlloc)) && && SUCCEEDED(Calc_ULongAdd(cbAlloc, sizeof(NUMBER), &cbAlloc)))
SUCCEEDED(Calc_ULongAdd(cbAlloc, sizeof(NUMBER), &cbAlloc)))
{ {
pnumret = (PNUMBER)zmalloc(cbAlloc); pnumret = (PNUMBER)zmalloc(cbAlloc);
if (pnumret == nullptr) if (pnumret == nullptr)
@ -241,7 +227,6 @@ PNUMBER _createnum( _In_ uint32_t size )
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
PRAT _createrat(void) PRAT _createrat(void)
{ {
@ -258,8 +243,6 @@ PRAT _createrat( void )
return (prat); return (prat);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: numtorat // FUNCTION: numtorat
@ -297,15 +280,12 @@ PRAT numtorat( _In_ PNUMBER pin, uint32_t radix)
pout->pp = numtonRadixx(pnRadixn, radix); pout->pp = numtonRadixx(pnRadixn, radix);
pout->pq = numtonRadixx(qnRadixn, radix); pout->pq = numtonRadixx(qnRadixn, radix);
destroynum(pnRadixn); destroynum(pnRadixn);
destroynum(qnRadixn); destroynum(qnRadixn);
return (pout); return (pout);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// //
// FUNCTION: nRadixxtonum // FUNCTION: nRadixxtonum
@ -343,8 +323,7 @@ PNUMBER nRadixxtonum( _In_ PNUMBER a, uint32_t radix, int32_t precision)
numpowi32(&powofnRadix, a->exp + (a->cdigit - cdigits), radix, precision); numpowi32(&powofnRadix, a->exp + (a->cdigit - cdigits), radix, precision);
// Loop over all the relative digits from MSD to LSD // Loop over all the relative digits from MSD to LSD
for ( ptr = &(a->mant[a->cdigit-1]); cdigits > 0; for (ptr = &(a->mant[a->cdigit - 1]); cdigits > 0; ptr--, cdigits--)
ptr--, cdigits-- )
{ {
// Loop over all the bits from MSB to LSB // Loop over all the bits from MSB to LSB
for (bitmask = BASEX / 2; bitmask > 0; bitmask /= 2) for (bitmask = BASEX / 2; bitmask > 0; bitmask /= 2)
@ -585,21 +564,7 @@ static constexpr uint8_t ERR = 14;
#if defined(DEBUG) #if defined(DEBUG)
char* statestr[] = { char* statestr[] = {
"START", "START", "MANTS", "LZ", "LZDP", "LD", "DZ", "DD", "DDP", "EXPB", "EXPS", "EXPD", "EXPBZ", "EXPSZ", "EXPDZ", "ERR",
"MANTS",
"LZ",
"LZDP",
"LD",
"DZ",
"DD",
"DDP",
"EXPB",
"EXPS",
"EXPD",
"EXPBZ",
"EXPSZ",
"EXPDZ",
"ERR",
}; };
#endif #endif
@ -862,7 +827,8 @@ PNUMBER i32tonum( int32_t ini32, uint32_t radix)
pnumret->sign = 1; pnumret->sign = 1;
} }
do { do
{
*pmant++ = (MANTTYPE)(ini32 % radix); *pmant++ = (MANTTYPE)(ini32 % radix);
ini32 /= radix; ini32 /= radix;
pnumret->cdigit++; pnumret->cdigit++;
@ -885,7 +851,6 @@ PNUMBER i32tonum( int32_t ini32, uint32_t radix)
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
PNUMBER Ui32tonum(uint32_t ini32, uint32_t radix) PNUMBER Ui32tonum(uint32_t ini32, uint32_t radix)
{ {
MANTTYPE* pmant; MANTTYPE* pmant;
@ -897,7 +862,8 @@ PNUMBER Ui32tonum(uint32_t ini32, uint32_t radix)
pnumret->exp = 0; pnumret->exp = 0;
pnumret->sign = 1; pnumret->sign = 1;
do { do
{
*pmant++ = (MANTTYPE)(ini32 % radix); *pmant++ = (MANTTYPE)(ini32 % radix);
ini32 /= radix; ini32 /= radix;
pnumret->cdigit++; pnumret->cdigit++;
@ -906,7 +872,6 @@ PNUMBER Ui32tonum(uint32_t ini32, uint32_t radix)
return (pnumret); return (pnumret);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: rattoi32 // FUNCTION: rattoi32
@ -978,7 +943,6 @@ uint32_t rattoUi32( _In_ PRAT prat, uint32_t radix, int32_t precision)
return (lret); return (lret);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: rattoUi64 // FUNCTION: rattoUi64
@ -1531,7 +1495,6 @@ void numpowi32( _Inout_ PNUMBER *proot, int32_t power, uint32_t radix, int32_t p
} }
destroynum(*proot); destroynum(*proot);
*proot = lret; *proot = lret;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------

View file

@ -16,7 +16,6 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "ratpak.h" #include "ratpak.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: exprat // FUNCTION: exprat
@ -51,7 +50,8 @@ void _exprat( PRAT *px, int32_t precision)
n2 = i32tonum(0L, BASEX); n2 = i32tonum(0L, BASEX);
do { do
{
NEXTTERM(*px, INC(n2) DIVNUM(n2), precision); NEXTTERM(*px, INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -96,7 +96,6 @@ void exprat( PRAT *px, uint32_t radix, int32_t precision)
destroyrat(pint); destroyrat(pint);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: lograt, _lograt // FUNCTION: lograt, _lograt
@ -142,7 +141,8 @@ void _lograt( PRAT *px, int32_t precision)
n2 = i32tonum(1L, BASEX); n2 = i32tonum(1L, BASEX);
(*px)->pp->sign *= -1; (*px)->pp->sign *= -1;
do { do
{
NEXTTERM(*px, MULNUM(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(*px, MULNUM(n2) INC(n2) DIVNUM(n2), precision);
TRIMTOP(*px, precision); TRIMTOP(*px, precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -150,7 +150,6 @@ void _lograt( PRAT *px, int32_t precision)
DESTROYTAYLOR(); DESTROYTAYLOR();
} }
void lograt(PRAT* px, int32_t precision) void lograt(PRAT* px, int32_t precision)
{ {
@ -158,7 +157,6 @@ void lograt( PRAT *px, int32_t precision)
PRAT pwr = nullptr; // pwr is the large scaling factor. PRAT pwr = nullptr; // pwr is the large scaling factor.
PRAT offset = nullptr; // offset is the incremental scaling factor. PRAT offset = nullptr; // offset is the incremental scaling factor.
// Check for someone taking the log of zero or a negative number. // Check for someone taking the log of zero or a negative number.
if (rat_le(*px, rat_zero, precision)) if (rat_le(*px, rat_zero, precision))
{ {
@ -433,8 +431,7 @@ void powratcomp(PRAT *px, PRAT y, uint32_t radix, int32_t precision)
PRAT pxint = nullptr; PRAT pxint = nullptr;
DUPRAT(pxint, *px); DUPRAT(pxint, *px);
subrat(&pxint, rat_one, precision); subrat(&pxint, rat_one, precision);
if ( rat_gt( pxint, rat_negsmallest, precision) && if (rat_gt(pxint, rat_negsmallest, precision) && rat_lt(pxint, rat_smallest, precision) && (sign == 1))
rat_lt( pxint, rat_smallest, precision) && ( sign == 1 ) )
{ {
// *px is one, special case a 1 return. // *px is one, special case a 1 return.
DUPRAT(*px, rat_one); DUPRAT(*px, rat_one);
@ -443,7 +440,6 @@ void powratcomp(PRAT *px, PRAT y, uint32_t radix, int32_t precision)
} }
else else
{ {
// Only do the exp if the number isn't zero or one // Only do the exp if the number isn't zero or one
PRAT podd = nullptr; PRAT podd = nullptr;
DUPRAT(podd, y); DUPRAT(podd, y);

View file

@ -15,7 +15,6 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "ratpak.h" #include "ratpak.h"
#define ABSRAT(x) (((x)->pp->sign = 1), ((x)->pq->sign = 1)) #define ABSRAT(x) (((x)->pp->sign = 1), ((x)->pq->sign = 1))
#define NEGATE(x) ((x)->pp->sign *= -1) #define NEGATE(x) ((x)->pp->sign *= -1)
@ -55,7 +54,6 @@
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _gamma(PRAT* pn, uint32_t radix, int32_t precision) void _gamma(PRAT* pn, uint32_t radix, int32_t precision)
{ {
@ -214,13 +212,11 @@ void factrat( PRAT *px, uint32_t radix, int32_t precision)
fracrat(&frac, radix, precision); fracrat(&frac, radix, precision);
// Check for negative integers and throw an error. // Check for negative integers and throw an error.
if ( ( zerrat(frac) || ( LOGRATRADIX(frac) <= -precision) ) && if ((zerrat(frac) || (LOGRATRADIX(frac) <= -precision)) && (SIGN(*px) == -1))
( SIGN(*px) == -1 ) )
{ {
throw CALC_E_DOMAIN; throw CALC_E_DOMAIN;
} }
while ( rat_gt( *px, rat_zero, precision) && while (rat_gt(*px, rat_zero, precision) && (LOGRATRADIX(*px) > -precision))
( LOGRATRADIX(*px) > -precision) )
{ {
mulrat(&fact, *px, precision); mulrat(&fact, *px, precision);
subrat(px, rat_one, precision); subrat(px, rat_one, precision);
@ -254,4 +250,3 @@ void factrat( PRAT *px, uint32_t radix, int32_t precision)
destroyrat(frac); destroyrat(frac);
destroyrat(neg_rat_one); destroyrat(neg_rat_one);
} }

View file

@ -17,8 +17,6 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "ratpak.h" #include "ratpak.h"
void ascalerat(_Inout_ PRAT* pa, ANGLE_TYPE angletype, int32_t precision) void ascalerat(_Inout_ PRAT* pa, ANGLE_TYPE angletype, int32_t precision)
{ {
switch (angletype) switch (angletype)
@ -36,7 +34,6 @@ void ascalerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, int32_t precision)
} }
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: asinrat, _asinrat // FUNCTION: asinrat, _asinrat
@ -74,10 +71,8 @@ void _asinrat( PRAT *px, int32_t precision)
do do
{ {
NEXTTERM(xx,MULNUM(n2) MULNUM(n2) NEXTTERM(xx, MULNUM(n2) MULNUM(n2) INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
}
while ( !SMALL_ENOUGH_RAT( thisterm, precision) );
DESTROYTAYLOR(); DESTROYTAYLOR();
} }
@ -143,7 +138,6 @@ void asinrat( PRAT *px, uint32_t radix, int32_t precision)
(*px)->pq->sign = 1; (*px)->pq->sign = 1;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: acosrat, _acosrat // FUNCTION: acosrat, _acosrat
@ -190,10 +184,8 @@ void _acosrat( PRAT *px, int32_t precision)
do do
{ {
NEXTTERM(xx,MULNUM(n2) MULNUM(n2) NEXTTERM(xx, MULNUM(n2) MULNUM(n2) INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
}
while ( !SMALL_ENOUGH_RAT( thisterm, precision) );
DESTROYTAYLOR(); DESTROYTAYLOR();
} }
@ -276,7 +268,8 @@ void _atanrat( PRAT *px, int32_t precision)
xx->pp->sign *= -1; xx->pp->sign *= -1;
do { do
{
NEXTTERM(xx, MULNUM(n2) INC(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(xx, MULNUM(n2) INC(n2) INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -332,4 +325,3 @@ void atanrat( PRAT *px, uint32_t radix, int32_t precision)
subrat(px, pi, precision); subrat(px, pi, precision);
} }
} }

View file

@ -18,8 +18,6 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "ratpak.h" #include "ratpak.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: asinhrat // FUNCTION: asinhrat
@ -79,17 +77,14 @@ void asinhrat( PRAT *px, uint32_t radix, int32_t precision)
do do
{ {
NEXTTERM(xx,MULNUM(n2) MULNUM(n2) NEXTTERM(xx, MULNUM(n2) MULNUM(n2) INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
}
while ( !SMALL_ENOUGH_RAT( thisterm, precision) );
DESTROYTAYLOR(); DESTROYTAYLOR();
} }
destroyrat(neg_pt_eight_five); destroyrat(neg_pt_eight_five);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: acoshrat // FUNCTION: acoshrat
@ -156,4 +151,3 @@ void atanhrat( PRAT *px, int32_t precision)
divrat(px, rat_two, precision); divrat(px, rat_two, precision);
destroyrat(ptmp); destroyrat(ptmp);
} }

View file

@ -66,8 +66,8 @@ void rshrat(PRAT *pa, PRAT b, uint32_t radix, int32_t precision)
void boolrat(PRAT* pa, PRAT b, int func, uint32_t radix, int32_t precision); void boolrat(PRAT* pa, PRAT b, int func, uint32_t radix, int32_t precision);
void boolnum(PNUMBER* pa, PNUMBER b, int func); void boolnum(PNUMBER* pa, PNUMBER b, int func);
enum
enum { {
FUNC_AND, FUNC_AND,
FUNC_OR, FUNC_OR,
FUNC_XOR FUNC_XOR
@ -143,8 +143,7 @@ void boolnum(PNUMBER *pa, PNUMBER b, int func)
MANTTYPE db; MANTTYPE db;
a = *pa; a = *pa;
cdigits = max(a->cdigit + a->exp, b->cdigit + b->exp) - cdigits = max(a->cdigit + a->exp, b->cdigit + b->exp) - min(a->exp, b->exp);
min(a->exp, b->exp);
createnum(c, cdigits); createnum(c, cdigits);
c->exp = min(a->exp, b->exp); c->exp = min(a->exp, b->exp);
mexp = c->exp; mexp = c->exp;
@ -154,12 +153,8 @@ void boolnum(PNUMBER *pa, PNUMBER b, int func)
pchc = c->mant; pchc = c->mant;
for (; cdigits > 0; cdigits--, mexp++) for (; cdigits > 0; cdigits--, mexp++)
{ {
da = (((mexp >= a->exp) && (cdigits + a->exp - c->exp > da = (((mexp >= a->exp) && (cdigits + a->exp - c->exp > (c->cdigit - a->cdigit))) ? *pcha++ : 0);
(c->cdigit - a->cdigit))) ? db = (((mexp >= b->exp) && (cdigits + b->exp - c->exp > (c->cdigit - b->cdigit))) ? *pchb++ : 0);
*pcha++ : 0);
db = (((mexp >= b->exp) && (cdigits + b->exp - c->exp >
(c->cdigit - b->cdigit))) ?
*pchb++ : 0);
switch (func) switch (func)
{ {
case FUNC_AND: case FUNC_AND:

View file

@ -78,11 +78,9 @@ void _addnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
a = *pa; a = *pa;
// Calculate the overlap of the numbers after alignment, this includes // Calculate the overlap of the numbers after alignment, this includes
// necessary padding 0's // necessary padding 0's
cdigits = max( a->cdigit+a->exp, b->cdigit+b->exp ) - cdigits = max(a->cdigit + a->exp, b->cdigit + b->exp) - min(a->exp, b->exp);
min( a->exp, b->exp );
createnum(c, cdigits + 1); createnum(c, cdigits + 1);
c->exp = min(a->exp, b->exp); c->exp = min(a->exp, b->exp);
@ -104,15 +102,10 @@ void _addnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
// aligned // aligned
for (; cdigits > 0; cdigits--, mexp++) for (; cdigits > 0; cdigits--, mexp++)
{ {
// Get digit from a, taking padding into account. // Get digit from a, taking padding into account.
da = ( ( ( mexp >= a->exp ) && ( cdigits + a->exp - c->exp > da = (((mexp >= a->exp) && (cdigits + a->exp - c->exp > (c->cdigit - a->cdigit))) ? *pcha++ : 0);
(c->cdigit - a->cdigit) ) ) ?
*pcha++ : 0 );
// Get digit from b, taking padding into account. // Get digit from b, taking padding into account.
db = ( ( ( mexp >= b->exp ) && ( cdigits + b->exp - c->exp > db = (((mexp >= b->exp) && (cdigits + b->exp - c->exp > (c->cdigit - b->cdigit))) ? *pchb++ : 0);
(c->cdigit - b->cdigit) ) ) ?
*pchb++ : 0 );
// Handle complementing for a and b digit. Might be a better way, but // Handle complementing for a and b digit. Might be a better way, but
// haven't found it yet. // haven't found it yet.
@ -157,9 +150,7 @@ void _addnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
// slower on average. // slower on average.
c->sign = -1; c->sign = -1;
cy = 1; cy = 1;
for ( ( cdigits = c->cdigit ), (pchc = c->mant); for ((cdigits = c->cdigit), (pchc = c->mant); cdigits > 0; cdigits--)
cdigits > 0;
cdigits-- )
{ {
cy = (MANTTYPE)radix - (MANTTYPE)1 - *pchc + cy; cy = (MANTTYPE)radix - (MANTTYPE)1 - *pchc + cy;
*pchc++ = (MANTTYPE)(cy % (MANTTYPE)radix); *pchc++ = (MANTTYPE)(cy % (MANTTYPE)radix);
@ -269,7 +260,6 @@ void _mulnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
// If result is nonzero, or while result of carry is nonzero... // If result is nonzero, or while result of carry is nonzero...
while (mcy || cy) while (mcy || cy)
{ {
// update carry from addition(s) and multiply. // update carry from addition(s) and multiply.
cy += (TWO_MANTTYPE)pchc[icdigit] + (mcy % (TWO_MANTTYPE)radix); cy += (TWO_MANTTYPE)pchc[icdigit] + (mcy % (TWO_MANTTYPE)radix);
@ -297,7 +287,6 @@ void _mulnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
*pa = c; *pa = c;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// //
// FUNCTION: remnum // FUNCTION: remnum
@ -357,11 +346,9 @@ void remnum( PNUMBER *pa, PNUMBER b, uint32_t radix)
destroynum(tmp); destroynum(tmp);
destroynum(lasttmp); destroynum(lasttmp);
} }
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// //
// FUNCTION: divnum // FUNCTION: divnum
@ -489,7 +476,6 @@ void _divnum( PNUMBER *pa, PNUMBER b, uint32_t radix, int32_t precision)
*pa = c; *pa = c;
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// //
// FUNCTION: equnum // FUNCTION: equnum
@ -541,10 +527,8 @@ bool equnum( PNUMBER a, PNUMBER b )
// difference in the digits. // difference in the digits.
for (; cdigits > 0; cdigits--) for (; cdigits > 0; cdigits--)
{ {
da = ( (cdigits > (ccdigits - a->cdigit) ) ? da = ((cdigits > (ccdigits - a->cdigit)) ? *pa-- : 0);
*pa-- : 0 ); db = ((cdigits > (ccdigits - b->cdigit)) ? *pb-- : 0);
db = ( (cdigits > (ccdigits - b->cdigit) ) ?
*pb-- : 0 );
if (da != db) if (da != db)
{ {
return false; return false;
@ -582,7 +566,6 @@ bool lessnum( PNUMBER a, PNUMBER b )
MANTTYPE da; MANTTYPE da;
MANTTYPE db; MANTTYPE db;
diff = (a->cdigit + a->exp) - (b->cdigit + b->exp); diff = (a->cdigit + a->exp) - (b->cdigit + b->exp);
if (diff < 0) if (diff < 0)
{ {
@ -605,10 +588,8 @@ bool lessnum( PNUMBER a, PNUMBER b )
ccdigits = cdigits; ccdigits = cdigits;
for (; cdigits > 0; cdigits--) for (; cdigits > 0; cdigits--)
{ {
da = ( (cdigits > (ccdigits - a->cdigit) ) ? da = ((cdigits > (ccdigits - a->cdigit)) ? *pa-- : 0);
*pa-- : 0 ); db = ((cdigits > (ccdigits - b->cdigit)) ? *pb-- : 0);
db = ( (cdigits > (ccdigits - b->cdigit) ) ?
*pb-- : 0 );
diff = da - db; diff = da - db;
if (diff) if (diff)
{ {

View file

@ -117,7 +117,6 @@ void mulrat( PRAT *pa, PRAT b, int32_t precision)
#ifdef MULGCD #ifdef MULGCD
gcdrat(pa); gcdrat(pa);
#endif #endif
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -133,11 +132,9 @@ void mulrat( PRAT *pa, PRAT b, int32_t precision)
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void divrat(PRAT* pa, PRAT b, int32_t precision) void divrat(PRAT* pa, PRAT b, int32_t precision)
{ {
if (!zernum((*pa)->pp)) if (!zernum((*pa)->pp))
{ {
// Only do the divide if the top isn't zero. // Only do the divide if the top isn't zero.
@ -170,7 +167,6 @@ void divrat( PRAT *pa, PRAT b, int32_t precision)
#ifdef DIVGCD #ifdef DIVGCD
gcdrat(pa); gcdrat(pa);
#endif #endif
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -244,11 +240,8 @@ void addrat( PRAT *pa, PRAT b, int32_t precision)
#ifdef ADDGCD #ifdef ADDGCD
gcdrat(pa); gcdrat(pa);
#endif #endif
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: rootrat // FUNCTION: rootrat
@ -274,7 +267,6 @@ void rootrat( PRAT *py, PRAT n, uint32_t radix, int32_t precision)
destroyrat(oneovern); destroyrat(oneovern);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: zerrat // FUNCTION: zerrat
@ -293,5 +285,3 @@ bool zerrat( PRAT a )
{ {
return (zernum(a->pp)); return (zernum(a->pp));
} }

View file

@ -4,481 +4,591 @@
#pragma once #pragma once
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_num_one= { inline const NUMBER init_num_one = { 1,
1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_num_two= { inline const NUMBER init_num_two = { 1,
1,
1, 1,
0, 0,
{ 2,} {
}; 2,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_num_five= { inline const NUMBER init_num_five = { 1,
1,
1, 1,
0, 0,
{ 5,} {
}; 5,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_num_six= { inline const NUMBER init_num_six = { 1,
1,
1, 1,
0, 0,
{ 6,} {
}; 6,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_num_ten= { inline const NUMBER init_num_ten = { 1,
1,
1, 1,
0, 0,
{ 10,} {
}; 10,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_smallest = { inline const NUMBER init_p_rat_smallest = { 1,
1,
1, 1,
0, 0,
{ 1,} {
};
inline const NUMBER init_q_rat_smallest = {
1, 1,
} };
inline const NUMBER init_q_rat_smallest = { 1,
4, 4,
0, 0,
{ 0, 190439170, 901055854, 10097,} {
}; 0,
190439170,
901055854,
10097,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_negsmallest = { inline const NUMBER init_p_rat_negsmallest = { -1,
-1,
1, 1,
0, 0,
{ 1,} {
};
inline const NUMBER init_q_rat_negsmallest = {
1, 1,
} };
inline const NUMBER init_q_rat_negsmallest = { 1,
4, 4,
0, 0,
{ 0, 190439170, 901055854, 10097,} {
}; 0,
190439170,
901055854,
10097,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_pt_eight_five = { inline const NUMBER init_p_pt_eight_five = { 1,
1,
1, 1,
0, 0,
{ 85,} {
}; 85,
inline const NUMBER init_q_pt_eight_five = { } };
1, inline const NUMBER init_q_pt_eight_five = { 1,
1, 1,
0, 0,
{ 100,} {
}; 100,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_six = { inline const NUMBER init_p_rat_six = { 1,
1,
1, 1,
0, 0,
{ 6,} {
}; 6,
inline const NUMBER init_q_rat_six = { } };
1, inline const NUMBER init_q_rat_six = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_two = { inline const NUMBER init_p_rat_two = { 1,
1,
1, 1,
0, 0,
{ 2,} {
}; 2,
inline const NUMBER init_q_rat_two = { } };
1, inline const NUMBER init_q_rat_two = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_zero = { inline const NUMBER init_p_rat_zero = { 1,
1,
1, 1,
0, 0,
{ 0,} {
}; 0,
inline const NUMBER init_q_rat_zero = { } };
1, inline const NUMBER init_q_rat_zero = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_one = { inline const NUMBER init_p_rat_one = { 1,
1,
1, 1,
0, 0,
{ 1,} {
};
inline const NUMBER init_q_rat_one = {
1, 1,
} };
inline const NUMBER init_q_rat_one = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_neg_one = { inline const NUMBER init_p_rat_neg_one = { -1,
-1,
1, 1,
0, 0,
{ 1,} {
};
inline const NUMBER init_q_rat_neg_one = {
1, 1,
} };
inline const NUMBER init_q_rat_neg_one = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_half = { inline const NUMBER init_p_rat_half = { 1,
1,
1, 1,
0, 0,
{ 1,} {
};
inline const NUMBER init_q_rat_half = {
1, 1,
} };
inline const NUMBER init_q_rat_half = { 1,
1, 1,
0, 0,
{ 2,} {
}; 2,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_ten = { inline const NUMBER init_p_rat_ten = { 1,
1,
1, 1,
0, 0,
{ 10,} {
}; 10,
inline const NUMBER init_q_rat_ten = { } };
1, inline const NUMBER init_q_rat_ten = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_pi = { inline const NUMBER init_p_pi = { 1,
1,
6, 6,
0, 0,
{ 125527896, 283898350, 1960493936, 1672850762, 1288168272, 8,} {
}; 125527896,
inline const NUMBER init_q_pi = { 283898350,
1, 1960493936,
1672850762,
1288168272,
8,
} };
inline const NUMBER init_q_pi = { 1,
6, 6,
0, 0,
{ 1288380402, 1120116153, 1860424692, 1944118326, 1583591604, 2,} {
}; 1288380402,
1120116153,
1860424692,
1944118326,
1583591604,
2,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_two_pi = { inline const NUMBER init_p_two_pi = { 1,
1,
6, 6,
0, 0,
{ 251055792, 567796700, 1773504224, 1198217877, 428852897, 17,} {
}; 251055792,
inline const NUMBER init_q_two_pi = { 567796700,
1, 1773504224,
1198217877,
428852897,
17,
} };
inline const NUMBER init_q_two_pi = { 1,
6, 6,
0, 0,
{ 1288380402, 1120116153, 1860424692, 1944118326, 1583591604, 2,} {
}; 1288380402,
1120116153,
1860424692,
1944118326,
1583591604,
2,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_pi_over_two = { inline const NUMBER init_p_pi_over_two = { 1,
1,
6, 6,
0, 0,
{ 125527896, 283898350, 1960493936, 1672850762, 1288168272, 8,} {
}; 125527896,
inline const NUMBER init_q_pi_over_two = { 283898350,
1, 1960493936,
1672850762,
1288168272,
8,
} };
inline const NUMBER init_q_pi_over_two = { 1,
6, 6,
0, 0,
{ 429277156, 92748659, 1573365737, 1740753005, 1019699561, 5,} {
}; 429277156,
92748659,
1573365737,
1740753005,
1019699561,
5,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_one_pt_five_pi = { inline const NUMBER init_p_one_pt_five_pi = { 1,
1,
6, 6,
0, 0,
{ 1241201312, 270061909, 1051574664, 1924965045, 1340320627, 70,} {
}; 1241201312,
inline const NUMBER init_q_one_pt_five_pi = { 270061909,
1, 1051574664,
1924965045,
1340320627,
70,
} };
inline const NUMBER init_q_one_pt_five_pi = { 1,
6, 6,
0, 0,
{ 1579671539, 1837970263, 1067644340, 523549916, 2119366659, 14,} {
}; 1579671539,
1837970263,
1067644340,
523549916,
2119366659,
14,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_e_to_one_half = { inline const NUMBER init_p_e_to_one_half = { 1,
1,
6, 6,
0, 0,
{ 256945612, 216219427, 223516738, 477442596, 581063757, 23,} {
}; 256945612,
inline const NUMBER init_q_e_to_one_half = { 216219427,
1, 223516738,
477442596,
581063757,
23,
} };
inline const NUMBER init_q_e_to_one_half = { 1,
6, 6,
0, 0,
{ 1536828363, 698484484, 1127331835, 224219346, 245499408, 14,} {
}; 1536828363,
698484484,
1127331835,
224219346,
245499408,
14,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_exp = { inline const NUMBER init_p_rat_exp = { 1,
1,
6, 6,
0, 0,
{ 943665199, 1606559160, 1094967530, 1759391384, 1671799163, 1123581,} {
}; 943665199,
inline const NUMBER init_q_rat_exp = { 1606559160,
1, 1094967530,
1759391384,
1671799163,
1123581,
} };
inline const NUMBER init_q_rat_exp = { 1,
6, 6,
0, 0,
{ 879242208, 2022880100, 617392930, 1374929092, 1367479163, 413342,} {
}; 879242208,
2022880100,
617392930,
1374929092,
1367479163,
413342,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_ln_ten = { inline const NUMBER init_p_ln_ten = { 1,
1,
6, 6,
0, 0,
{ 2086268922, 165794492, 1416063951, 1851428830, 1893239400, 65366841,} {
}; 2086268922,
inline const NUMBER init_q_ln_ten = { 165794492,
1, 1416063951,
1851428830,
1893239400,
65366841,
} };
inline const NUMBER init_q_ln_ten = { 1,
6, 6,
0, 0,
{ 26790652, 564532679, 783998273, 216030448, 1564709968, 28388458,} {
}; 26790652,
564532679,
783998273,
216030448,
1564709968,
28388458,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_ln_two = { inline const NUMBER init_p_ln_two = { 1,
1,
6, 6,
0, 0,
{ 1789230241, 1057927868, 715399197, 908801241, 1411265331, 3,} {
}; 1789230241,
inline const NUMBER init_q_ln_two = { 1057927868,
1, 715399197,
908801241,
1411265331,
3,
} };
inline const NUMBER init_q_ln_two = { 1,
6, 6,
0, 0,
{ 1559869847, 1930657510, 1228561531, 219003871, 593099283, 5,} {
}; 1559869847,
1930657510,
1228561531,
219003871,
593099283,
5,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rad_to_deg = { inline const NUMBER init_p_rad_to_deg = { 1,
1,
6, 6,
0, 0,
{ 2127722024, 1904928383, 2016479213, 2048947859, 1578647346, 492,} {
}; 2127722024,
inline const NUMBER init_q_rad_to_deg = { 1904928383,
1, 2016479213,
2048947859,
1578647346,
492,
} };
inline const NUMBER init_q_rad_to_deg = { 1,
6, 6,
0, 0,
{ 125527896, 283898350, 1960493936, 1672850762, 1288168272, 8,} {
}; 125527896,
283898350,
1960493936,
1672850762,
1288168272,
8,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rad_to_grad = { inline const NUMBER init_p_rad_to_grad = { 1,
1,
6, 6,
0, 0,
{ 2125526288, 684931327, 570267400, 129125085, 1038224725, 547,} {
}; 2125526288,
inline const NUMBER init_q_rad_to_grad = { 684931327,
1, 570267400,
129125085,
1038224725,
547,
} };
inline const NUMBER init_q_rad_to_grad = { 1,
6, 6,
0, 0,
{ 125527896, 283898350, 1960493936, 1672850762, 1288168272, 8,} {
}; 125527896,
283898350,
1960493936,
1672850762,
1288168272,
8,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_qword = { inline const NUMBER init_p_rat_qword = { 1,
1,
3, 3,
0, 0,
{ 2147483647, 2147483647, 3,} {
}; 2147483647,
inline const NUMBER init_q_rat_qword = { 2147483647,
1, 3,
} };
inline const NUMBER init_q_rat_qword = { 1,
1, 1,
0, 0,
{ 1,} {
};
// Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_dword = {
1, 1,
} };
// Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_dword = { 1,
2, 2,
0, 0,
{ 2147483647, 1,} {
}; 2147483647,
inline const NUMBER init_q_rat_dword = {
1, 1,
} };
inline const NUMBER init_q_rat_dword = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_max_i32 = { inline const NUMBER init_p_rat_max_i32 = { 1,
1,
1, 1,
0, 0,
{ 2147483647,} {
}; 2147483647,
inline const NUMBER init_q_rat_max_i32 = { } };
1, inline const NUMBER init_q_rat_max_i32 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_min_i32 = { inline const NUMBER init_p_rat_min_i32 = { -1,
-1,
2, 2,
0, 0,
{ 0, 1,} {
}; 0,
inline const NUMBER init_q_rat_min_i32 = {
1, 1,
} };
inline const NUMBER init_q_rat_min_i32 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_word = { inline const NUMBER init_p_rat_word = { 1,
1,
1, 1,
0, 0,
{ 65535,} {
}; 65535,
inline const NUMBER init_q_rat_word = { } };
1, inline const NUMBER init_q_rat_word = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_byte = { inline const NUMBER init_p_rat_byte = { 1,
1,
1, 1,
0, 0,
{ 255,} {
}; 255,
inline const NUMBER init_q_rat_byte = { } };
1, inline const NUMBER init_q_rat_byte = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_400 = { inline const NUMBER init_p_rat_400 = { 1,
1,
1, 1,
0, 0,
{ 400,} {
}; 400,
inline const NUMBER init_q_rat_400 = { } };
1, inline const NUMBER init_q_rat_400 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_360 = { inline const NUMBER init_p_rat_360 = { 1,
1,
1, 1,
0, 0,
{ 360,} {
}; 360,
inline const NUMBER init_q_rat_360 = { } };
1, inline const NUMBER init_q_rat_360 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_200 = { inline const NUMBER init_p_rat_200 = { 1,
1,
1, 1,
0, 0,
{ 200,} {
}; 200,
inline const NUMBER init_q_rat_200 = { } };
1, inline const NUMBER init_q_rat_200 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_180 = { inline const NUMBER init_p_rat_180 = { 1,
1,
1, 1,
0, 0,
{ 180,} {
}; 180,
inline const NUMBER init_q_rat_180 = { } };
1, inline const NUMBER init_q_rat_180 = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_max_exp = { inline const NUMBER init_p_rat_max_exp = { 1,
1,
1, 1,
0, 0,
{ 100000,} {
}; 100000,
inline const NUMBER init_q_rat_max_exp = { } };
1, inline const NUMBER init_q_rat_max_exp = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_min_exp = { inline const NUMBER init_p_rat_min_exp = { -1,
-1,
1, 1,
0, 0,
{ 100000,} {
}; 100000,
inline const NUMBER init_q_rat_min_exp = { } };
1, inline const NUMBER init_q_rat_min_exp = { 1,
1, 1,
0, 0,
{ 1,} {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_max_fact = { inline const NUMBER init_p_rat_max_fact = { 1,
1,
1, 1,
0, 0,
{ 3249, } {
}; 3249,
inline const NUMBER init_q_rat_max_fact = { } };
1, inline const NUMBER init_q_rat_max_fact = { 1,
1, 1,
0, 0,
{ 1, } {
}; 1,
} };
// Autogenerated by _dumprawrat in support.cpp // Autogenerated by _dumprawrat in support.cpp
inline const NUMBER init_p_rat_min_fact = { inline const NUMBER init_p_rat_min_fact = { -1,
-1,
1, 1,
0, 0,
{ 1000, } {
}; 1000,
inline const NUMBER init_q_rat_min_fact = { } };
1, inline const NUMBER init_q_rat_min_fact = { 1,
1, 1,
0, 0,
{ 1, } {
}; 1,
} };

View file

@ -31,14 +31,16 @@ static constexpr uint32_t BASEX = 0x80000000; // Internal radix used in calculat
typedef uint32_t MANTTYPE; typedef uint32_t MANTTYPE;
typedef uint64_t TWO_MANTTYPE; typedef uint64_t TWO_MANTTYPE;
enum eNUMOBJ_FMT { enum eNUMOBJ_FMT
{
FMT_FLOAT, // returns floating point, or exponential if number is too big FMT_FLOAT, // returns floating point, or exponential if number is too big
FMT_SCIENTIFIC, // always returns scientific notation FMT_SCIENTIFIC, // always returns scientific notation
FMT_ENGINEERING // always returns engineering notation such that exponent is a multiple of 3 FMT_ENGINEERING // always returns engineering notation such that exponent is a multiple of 3
}; };
enum eANGLE_TYPE { enum eANGLE_TYPE
{
ANGLE_DEG, // Calculate trig using 360 degrees per revolution ANGLE_DEG, // Calculate trig using 360 degrees per revolution
ANGLE_RAD, // Calculate trig using 2 pi radians per revolution ANGLE_RAD, // Calculate trig using 2 pi radians per revolution
ANGLE_GRAD // Calculate trig using 400 gradients per revolution ANGLE_GRAD // Calculate trig using 400 gradients per revolution
@ -69,7 +71,6 @@ typedef struct _number
} NUMBER, *PNUMBER, **PPNUMBER; } NUMBER, *PNUMBER, **PPNUMBER;
#pragma warning(pop) #pragma warning(pop)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// RAT type is a representation radix on 2 NUMBER types. // RAT type is a representation radix on 2 NUMBER types.
@ -135,10 +136,17 @@ extern PRAT rat_max_i32;
extern PRAT rat_min_i32; extern PRAT rat_min_i32;
// DUPNUM Duplicates a number taking care of allocation and internals // DUPNUM Duplicates a number taking care of allocation and internals
#define DUPNUM(a,b) destroynum(a);createnum( a, (b)->cdigit );_dupnum(a, b); #define DUPNUM(a, b) \
destroynum(a); \
createnum(a, (b)->cdigit); \
_dupnum(a, b);
// DUPRAT Duplicates a rational taking care of allocation and internals // DUPRAT Duplicates a rational taking care of allocation and internals
#define DUPRAT(a,b) destroyrat(a);createrat(a);DUPNUM((a)->pp,(b)->pp);DUPNUM((a)->pq,(b)->pq); #define DUPRAT(a, b) \
destroyrat(a); \
createrat(a); \
DUPNUM((a)->pp, (b)->pp); \
DUPNUM((a)->pq, (b)->pq);
// LOG*RADIX calculates the integral portion of the log of a number in // LOG*RADIX calculates the integral portion of the log of a number in
// the base currently being used, only accurate to within g_ratio // the base currently being used, only accurate to within g_ratio
@ -163,7 +171,8 @@ extern PRAT rat_min_i32;
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#define createrat(y) (y)=_createrat(); \ #define createrat(y) \
(y) = _createrat(); \
{ \ { \
std::wstringstream outputString; \ std::wstringstream outputString; \
outputString << "createrat " << y << " " << #y << " file= " << __FILE__ << ", line= " << __LINE__ << "\n"; \ outputString << "createrat " << y << " " << #y << " file= " << __FILE__ << ", line= " << __LINE__ << "\n"; \
@ -176,7 +185,8 @@ extern PRAT rat_min_i32;
OutputDebugString(outputString.str().c_str()); \ OutputDebugString(outputString.str().c_str()); \
} \ } \
_destroyrat(x), (x) = nullptr _destroyrat(x), (x) = nullptr
#define createnum(y,x) (y)=_createnum(x); \ #define createnum(y, x) \
(y) = _createnum(x); \
{ \ { \
std::wstringstream outputString; \ std::wstringstream outputString; \
outputString << "createnum " << y << " " << #y << " file= " << __FILE__ << ", line= " << __LINE__ << "\n"; \ outputString << "createnum " << y << " " << #y << " file= " << __FILE__ << ", line= " << __LINE__ << "\n"; \
@ -204,17 +214,22 @@ _destroynum(x),(x)=nullptr
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// RENORMALIZE, gets the exponents non-negative. // RENORMALIZE, gets the exponents non-negative.
#define RENORMALIZE(x) if ( (x)->pp->exp < 0 ) { \ #define RENORMALIZE(x) \
if ((x)->pp->exp < 0) \
{ \
(x)->pq->exp -= (x)->pp->exp; \ (x)->pq->exp -= (x)->pp->exp; \
(x)->pp->exp = 0; \ (x)->pp->exp = 0; \
} \ } \
if ( (x)->pq->exp < 0 ) { \ if ((x)->pq->exp < 0) \
{ \
(x)->pp->exp -= (x)->pq->exp; \ (x)->pp->exp -= (x)->pq->exp; \
(x)->pq->exp = 0; \ (x)->pq->exp = 0; \
} }
// TRIMNUM ASSUMES the number is in radix form NOT INTERNAL BASEX!!! // TRIMNUM ASSUMES the number is in radix form NOT INTERNAL BASEX!!!
#define TRIMNUM(x, precision) if ( !g_ftrueinfinite ) { \ #define TRIMNUM(x, precision) \
if (!g_ftrueinfinite) \
{ \
int32_t trim = (x)->cdigit - precision - g_ratio; \ int32_t trim = (x)->cdigit - precision - g_ratio; \
if (trim > 1) \ if (trim > 1) \
{ \ { \
@ -224,7 +239,9 @@ memmove( (x)->mant, &((x)->mant[trim]), sizeof(MANTTYPE)*((x)->cdigit-trim) ); \
} \ } \
} }
// TRIMTOP ASSUMES the number is in INTERNAL BASEX!!! // TRIMTOP ASSUMES the number is in INTERNAL BASEX!!!
#define TRIMTOP(x, precision) if ( !g_ftrueinfinite ) { \ #define TRIMTOP(x, precision) \
if (!g_ftrueinfinite) \
{ \
int32_t trim = (x)->pp->cdigit - (precision / g_ratio) - 2; \ int32_t trim = (x)->pp->cdigit - (precision / g_ratio) - 2; \
if (trim > 1) \ if (trim > 1) \
{ \ { \
@ -246,7 +263,8 @@ memmove( (x)->pp->mant, &((x)->pp->mant[trim]), sizeof(MANTTYPE)*((x)->pp->cdigi
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#define CREATETAYLOR() PRAT xx=nullptr;\ #define CREATETAYLOR() \
PRAT xx = nullptr; \
PNUMBER n2 = nullptr; \ PNUMBER n2 = nullptr; \
PRAT pret = nullptr; \ PRAT pret = nullptr; \
PRAT thisterm = nullptr; \ PRAT thisterm = nullptr; \
@ -256,7 +274,8 @@ memmove( (x)->pp->mant, &((x)->pp->mant[trim]), sizeof(MANTTYPE)*((x)->pp->cdigi
pret->pp = i32tonum(0L, BASEX); \ pret->pp = i32tonum(0L, BASEX); \
pret->pq = i32tonum(0L, BASEX); pret->pq = i32tonum(0L, BASEX);
#define DESTROYTAYLOR() destroynum( n2 ); \ #define DESTROYTAYLOR() \
destroynum(n2); \
destroyrat(xx); \ destroyrat(xx); \
destroyrat(thisterm); \ destroyrat(thisterm); \
destroyrat(*px); \ destroyrat(*px); \
@ -265,7 +284,8 @@ memmove( (x)->pp->mant, &((x)->pp->mant[trim]), sizeof(MANTTYPE)*((x)->pp->cdigi
// INC(a) is the rational equivalent of a++ // INC(a) is the rational equivalent of a++
// Check to see if we can avoid doing this the hard way. // Check to see if we can avoid doing this the hard way.
#define INC(a) if ( (a)->mant[0] < BASEX - 1 ) \ #define INC(a) \
if ((a)->mant[0] < BASEX - 1) \
{ \ { \
(a)->mant[0]++; \ (a)->mant[0]++; \
} \ } \
@ -289,7 +309,9 @@ memmove( (x)->pp->mant, &((x)->pp->mant[trim]), sizeof(MANTTYPE)*((x)->pp->cdigi
// thisterm *= p // thisterm *= p
// d <d is usually an expansion of operations to get thisterm updated.> // d <d is usually an expansion of operations to get thisterm updated.>
// pret += thisterm // pret += thisterm
#define NEXTTERM(p,d,precision) mulrat(&thisterm,p,precision);d addrat( &pret, thisterm, precision ) #define NEXTTERM(p, d, precision) \
mulrat(&thisterm, p, precision); \
d addrat(&pret, thisterm, precision)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
@ -334,10 +356,12 @@ uint64_t rattoUi64(_In_ PRAT prat, uint32_t radix, int32_t precision);
extern PNUMBER _createnum(_In_ uint32_t size); // returns an empty number structure with size digits extern PNUMBER _createnum(_In_ uint32_t size); // returns an empty number structure with size digits
extern PNUMBER nRadixxtonum(_In_ PNUMBER a, uint32_t radix, int32_t precision); extern PNUMBER nRadixxtonum(_In_ PNUMBER a, uint32_t radix, int32_t precision);
extern PNUMBER gcd(_In_ PNUMBER a, _In_ PNUMBER b); extern PNUMBER gcd(_In_ PNUMBER a, _In_ PNUMBER b);
extern PNUMBER StringToNumber(std::wstring_view numberString, uint32_t radix, int32_t precision); // takes a text representation of a number and returns a number. extern PNUMBER StringToNumber(std::wstring_view numberString, uint32_t radix,
int32_t precision); // takes a text representation of a number and returns a number.
// takes a text representation of a number as a mantissa with sign and an exponent with sign. // takes a text representation of a number as a mantissa with sign and an exponent with sign.
extern PRAT StringToRat(bool mantissaIsNegative, std::wstring_view mantissa, bool exponentIsNegative, std::wstring_view exponent, uint32_t radix, int32_t precision); extern PRAT StringToRat(bool mantissaIsNegative, std::wstring_view mantissa, bool exponentIsNegative, std::wstring_view exponent, uint32_t radix,
int32_t precision);
extern PNUMBER i32factnum(int32_t ini32, uint32_t radix); extern PNUMBER i32factnum(int32_t ini32, uint32_t radix);
extern PNUMBER i32prodnum(int32_t start, int32_t stop, uint32_t radix); extern PNUMBER i32prodnum(int32_t start, int32_t stop, uint32_t radix);

View file

@ -32,23 +32,34 @@ static int cbitsofprecision = 0;
#define READRAWRAT(v) #define READRAWRAT(v)
#define READRAWNUM(v) #define READRAWNUM(v)
#define DUMPRAWRAT(v) _dumprawrat(#v, v, wcout) #define DUMPRAWRAT(v) _dumprawrat(#v, v, wcout)
#define DUMPRAWNUM(v) fprintf( stderr, \ #define DUMPRAWNUM(v) \
"// Autogenerated by _dumprawrat in support.cpp\n" ); \ fprintf(stderr, "// Autogenerated by _dumprawrat in support.cpp\n"); \
fprintf(stderr, "inline const NUMBER init_" #v "= {\n"); \ fprintf(stderr, "inline const NUMBER init_" #v "= {\n"); \
_dumprawnum(v, wcout); \ _dumprawnum(v, wcout); \
fprintf(stderr, "};\n") fprintf(stderr, "};\n")
#else #else
#define DUMPRAWRAT(v) #define DUMPRAWRAT(v)
#define DUMPRAWNUM(v) #define DUMPRAWNUM(v)
#define READRAWRAT(v) createrat(v); DUPNUM((v)->pp,(&(init_p_##v))); \ #define READRAWRAT(v) \
createrat(v); \
DUPNUM((v)->pp, (&(init_p_##v))); \
DUPNUM((v)->pq, (&(init_q_##v))); DUPNUM((v)->pq, (&(init_q_##v)));
#define READRAWNUM(v) DUPNUM(v, (&(init_##v))) #define READRAWNUM(v) DUPNUM(v, (&(init_##v)))
#define INIT_AND_DUMP_RAW_NUM_IF_NULL(r, v) if (r == nullptr) { r = i32tonum(v, BASEX); DUMPRAWNUM(v); } #define INIT_AND_DUMP_RAW_NUM_IF_NULL(r, v) \
#define INIT_AND_DUMP_RAW_RAT_IF_NULL(r, v) if (r == nullptr) { r = i32torat(v); DUMPRAWRAT(v); } if (r == nullptr) \
{ \
r = i32tonum(v, BASEX); \
DUMPRAWNUM(v); \
}
#define INIT_AND_DUMP_RAW_RAT_IF_NULL(r, v) \
if (r == nullptr) \
{ \
r = i32torat(v); \
DUMPRAWRAT(v); \
}
static constexpr int RATIO_FOR_DECIMAL = 9; static constexpr int RATIO_FOR_DECIMAL = 9;
static constexpr int DECIMAL = 10; static constexpr int DECIMAL = 10;
@ -253,7 +264,6 @@ void ChangeConstants(uint32_t radix, int32_t precision)
lograt(&ln_two, extraPrecision); lograt(&ln_two, extraPrecision);
DUMPRAWRAT(ln_two); DUMPRAWRAT(ln_two);
destroyrat(rad_to_deg); destroyrat(rad_to_deg);
rad_to_deg = i32torat(180L); rad_to_deg = i32torat(180L);
divrat(&rad_to_deg, pi, extraPrecision); divrat(&rad_to_deg, pi, extraPrecision);
@ -273,7 +283,6 @@ void ChangeConstants(uint32_t radix, int32_t precision)
DUPRAT(rat_negsmallest, rat_smallest); DUPRAT(rat_negsmallest, rat_smallest);
rat_negsmallest->pp->sign = -1; rat_negsmallest->pp->sign = -1;
} }
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
@ -355,7 +364,6 @@ bool rat_ge( PRAT a, PRAT b, int32_t precision)
return (bret); return (bret);
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// //
// FUNCTION: rat_gt // FUNCTION: rat_gt
@ -394,7 +402,6 @@ bool rat_gt( PRAT a, PRAT b, int32_t precision)
bool rat_le(PRAT a, PRAT b, int32_t precision) bool rat_le(PRAT a, PRAT b, int32_t precision)
{ {
PRAT rattmp = nullptr; PRAT rattmp = nullptr;
DUPRAT(rattmp, a); DUPRAT(rattmp, a);
b->pp->sign *= -1; b->pp->sign *= -1;
@ -405,7 +412,6 @@ bool rat_le( PRAT a, PRAT b, int32_t precision)
return (bret); return (bret);
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// //
// FUNCTION: rat_lt // FUNCTION: rat_lt
@ -430,7 +436,6 @@ bool rat_lt( PRAT a, PRAT b, int32_t precision)
return (bret); return (bret);
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// //
// FUNCTION: rat_neq // FUNCTION: rat_neq
@ -442,7 +447,6 @@ bool rat_lt( PRAT a, PRAT b, int32_t precision)
// //
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
bool rat_neq(PRAT a, PRAT b, int32_t precision) bool rat_neq(PRAT a, PRAT b, int32_t precision)
{ {
@ -473,8 +477,7 @@ void scale( PRAT *px, PRAT scalefact, uint32_t radix, int32_t precision )
// Logscale is a quick way to tell how much extra precision is needed for // Logscale is a quick way to tell how much extra precision is needed for
// scaling by scalefact. // scaling by scalefact.
int32_t logscale = g_ratio * ( (pret->pp->cdigit+pret->pp->exp) - int32_t logscale = g_ratio * ((pret->pp->cdigit + pret->pp->exp) - (pret->pq->cdigit + pret->pq->exp));
(pret->pq->cdigit+pret->pq->exp) );
if (logscale > 0) if (logscale > 0)
{ {
precision += logscale; precision += logscale;
@ -508,8 +511,7 @@ void scale2pi( PRAT *px, uint32_t radix, int32_t precision )
// Logscale is a quick way to tell how much extra precision is needed for // Logscale is a quick way to tell how much extra precision is needed for
// scaling by 2 pi. // scaling by 2 pi.
int32_t logscale = g_ratio * ( (pret->pp->cdigit+pret->pp->exp) - int32_t logscale = g_ratio * ((pret->pp->cdigit + pret->pp->exp) - (pret->pq->cdigit + pret->pq->exp));
(pret->pq->cdigit+pret->pq->exp) );
if (logscale > 0) if (logscale > 0)
{ {
precision += logscale; precision += logscale;

View file

@ -16,8 +16,6 @@
#include "ratpak.h" #include "ratpak.h"
void scalerat(_Inout_ PRAT* pa, ANGLE_TYPE angletype, uint32_t radix, int32_t precision) void scalerat(_Inout_ PRAT* pa, ANGLE_TYPE angletype, uint32_t radix, int32_t precision)
{ {
switch (angletype) switch (angletype)
@ -34,7 +32,6 @@ void scalerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, uint32_t radix, int32_t p
} }
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// //
// FUNCTION: sinrat, _sinrat // FUNCTION: sinrat, _sinrat
@ -66,7 +63,6 @@ void scalerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, uint32_t radix, int32_t p
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _sinrat(PRAT* px, int32_t precision) void _sinrat(PRAT* px, int32_t precision)
{ {
@ -78,7 +74,8 @@ void _sinrat( PRAT *px, int32_t precision)
DUPNUM(n2, num_one); DUPNUM(n2, num_one);
xx->pp->sign *= -1; xx->pp->sign *= -1;
do { do
{
NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -158,7 +155,6 @@ void sinanglerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, uint32_t radix, int32_
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _cosrat(PRAT* px, uint32_t radix, int32_t precision) void _cosrat(PRAT* px, uint32_t radix, int32_t precision)
{ {
@ -175,7 +171,8 @@ void _cosrat( PRAT *px, uint32_t radix, int32_t precision)
n2 = i32tonum(0L, radix); n2 = i32tonum(0L, radix);
xx->pp->sign *= -1; xx->pp->sign *= -1;
do { do
{
NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -242,7 +239,6 @@ void cosanglerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, uint32_t radix, int32_
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _tanrat(PRAT* px, uint32_t radix, int32_t precision) void _tanrat(PRAT* px, uint32_t radix, int32_t precision)
{ {
@ -259,7 +255,6 @@ void _tanrat( PRAT *px, uint32_t radix, int32_t precision)
divrat(px, ptmp, precision); divrat(px, ptmp, precision);
destroyrat(ptmp); destroyrat(ptmp);
} }
void tanrat(PRAT* px, uint32_t radix, int32_t precision) void tanrat(PRAT* px, uint32_t radix, int32_t precision)
@ -293,4 +288,3 @@ void tananglerat( _Inout_ PRAT *pa, ANGLE_TYPE angletype, uint32_t radix, int32_
} }
_tanrat(pa, radix, precision); _tanrat(pa, radix, precision);
} }

View file

@ -16,8 +16,6 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "ratpak.h" #include "ratpak.h"
bool IsValidForHypFunc(PRAT px, int32_t precision) bool IsValidForHypFunc(PRAT px, int32_t precision)
{ {
PRAT ptmp = nullptr; PRAT ptmp = nullptr;
@ -31,7 +29,6 @@ bool IsValidForHypFunc(PRAT px, int32_t precision)
} }
destroyrat(ptmp); destroyrat(ptmp);
return bRet; return bRet;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -67,7 +64,6 @@ bool IsValidForHypFunc(PRAT px, int32_t precision)
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _sinhrat(PRAT* px, int32_t precision) void _sinhrat(PRAT* px, int32_t precision)
{ {
@ -84,7 +80,8 @@ void _sinhrat( PRAT *px, int32_t precision)
DUPNUM(n2, num_one); DUPNUM(n2, num_one);
do { do
{
NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -146,7 +143,6 @@ void sinhrat( PRAT *px, uint32_t radix, int32_t precision)
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void _coshrat(PRAT* px, uint32_t radix, int32_t precision) void _coshrat(PRAT* px, uint32_t radix, int32_t precision)
{ {
@ -165,7 +161,8 @@ void _coshrat( PRAT *px, uint32_t radix, int32_t precision)
n2 = i32tonum(0L, radix); n2 = i32tonum(0L, radix);
do { do
{
NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision); NEXTTERM(xx, INC(n2) DIVNUM(n2) INC(n2) DIVNUM(n2), precision);
} while (!SMALL_ENOUGH_RAT(thisterm, precision)); } while (!SMALL_ENOUGH_RAT(thisterm, precision));
@ -226,5 +223,4 @@ void tanhrat( PRAT *px, uint32_t radix, int32_t precision)
mulnumx(&((*px)->pq), ptmp->pp); mulnumx(&((*px)->pq), ptmp->pp);
destroyrat(ptmp); destroyrat(ptmp);
} }

View file

@ -34,8 +34,7 @@ unordered_map<wstring, wchar_t> unquoteConversions;
/// Constructor, sets up all the variables and requires a configLoader /// Constructor, sets up all the variables and requires a configLoader
/// </summary> /// </summary>
/// <param name="dataLoader">An instance of the IConverterDataLoader interface which we use to read in category/unit names and conversion data</param> /// <param name="dataLoader">An instance of the IConverterDataLoader interface which we use to read in category/unit names and conversion data</param>
UnitConverter::UnitConverter(_In_ const shared_ptr<IConverterDataLoader>& dataLoader) : UnitConverter::UnitConverter(_In_ const shared_ptr<IConverterDataLoader>& dataLoader) : UnitConverter::UnitConverter(dataLoader, nullptr)
UnitConverter::UnitConverter(dataLoader, nullptr)
{ {
} }
@ -232,7 +231,9 @@ Category UnitConverter::StringToCategory(const wstring& w)
wstring UnitConverter::UnitToString(const Unit& u, const wchar_t* delimiter) wstring UnitConverter::UnitToString(const Unit& u, const wchar_t* delimiter)
{ {
wstringstream out(wstringstream::out); wstringstream out(wstringstream::out);
out << Quote(std::to_wstring(u.id)) << delimiter << Quote(u.name) << delimiter << Quote(u.abbreviation) << delimiter << std::to_wstring(u.isConversionSource) << delimiter << std::to_wstring(u.isConversionTarget) << delimiter << std::to_wstring(u.isWhimsical) << delimiter; out << Quote(std::to_wstring(u.id)) << delimiter << Quote(u.name) << delimiter << Quote(u.abbreviation) << delimiter
<< std::to_wstring(u.isConversionSource) << delimiter << std::to_wstring(u.isConversionTarget) << delimiter << std::to_wstring(u.isWhimsical)
<< delimiter;
return out.str(); return out.str();
} }
@ -294,7 +295,8 @@ wstring UnitConverter::Serialize()
out << UnitToString(m_fromType, delimiter) << "|"; out << UnitToString(m_fromType, delimiter) << "|";
out << UnitToString(m_toType, delimiter) << "|"; out << UnitToString(m_toType, delimiter) << "|";
out << CategoryToString(m_currentCategory, delimiter) << "|"; out << CategoryToString(m_currentCategory, delimiter) << "|";
out << std::to_wstring(m_currentHasDecimal) << delimiter << std::to_wstring(m_returnHasDecimal) << delimiter << std::to_wstring(m_switchedActive) << delimiter; out << std::to_wstring(m_currentHasDecimal) << delimiter << std::to_wstring(m_returnHasDecimal) << delimiter << std::to_wstring(m_switchedActive)
<< delimiter;
out << m_currentDisplay << delimiter << m_returnDisplay << delimiter << "|"; out << m_currentDisplay << delimiter << m_returnDisplay << delimiter << "|";
wstringstream categoryString(wstringstream::out); wstringstream categoryString(wstringstream::out);
wstringstream categoryToUnitString(wstringstream::out); wstringstream categoryToUnitString(wstringstream::out);
@ -311,7 +313,8 @@ wstring UnitConverter::Serialize()
{ {
categoryToUnitString << UnitToString(u, delimiter) << ","; categoryToUnitString << UnitToString(u, delimiter) << ",";
} }
categoryToUnitString << "[" << "]"; categoryToUnitString << "["
<< "]";
} }
for (const auto& cur : m_ratioMap) for (const auto& cur : m_ratioMap)
@ -322,7 +325,8 @@ wstring UnitConverter::Serialize()
unitToUnitToDoubleString << UnitToString(curConversion.first, delimiter) << ":"; unitToUnitToDoubleString << UnitToString(curConversion.first, delimiter) << ":";
unitToUnitToDoubleString << ConversionDataToString(curConversion.second, delimiter) << ":,"; unitToUnitToDoubleString << ConversionDataToString(curConversion.second, delimiter) << ":,";
} }
unitToUnitToDoubleString << "[" << "]"; unitToUnitToDoubleString << "["
<< "]";
} }
out << categoryString.str() << "|"; out << categoryString.str() << "|";
@ -429,7 +433,6 @@ void UnitConverter::RestoreUserPreferences(const wstring& userPreferences)
m_toType = toType; m_toType = toType;
} }
} }
} }
/// <summary> /// <summary>
@ -529,7 +532,8 @@ void UnitConverter::SendCommand(Command command)
clearFront = true; clearFront = true;
} }
bool clearBack = false; bool clearBack = false;
if ((m_currentHasDecimal && m_currentDisplay.size() - 1 >= MAXIMUMDIGITSALLOWED) || (!m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED)) if ((m_currentHasDecimal && m_currentDisplay.size() - 1 >= MAXIMUMDIGITSALLOWED)
|| (!m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED))
{ {
clearBack = true; clearBack = true;
} }
@ -643,7 +647,6 @@ void UnitConverter::SendCommand(Command command)
break; break;
} }
if (clearFront) if (clearFront)
{ {
m_currentDisplay.erase(0, 1); m_currentDisplay.erase(0, 1);
@ -684,8 +687,7 @@ void UnitConverter::SetViewModelCurrencyCallback(_In_ const shared_ptr<IViewMode
task<pair<bool, wstring>> UnitConverter::RefreshCurrencyRatios() task<pair<bool, wstring>> UnitConverter::RefreshCurrencyRatios()
{ {
shared_ptr<ICurrencyConverterDataLoader> currencyDataLoader = GetCurrencyConverterDataLoader(); shared_ptr<ICurrencyConverterDataLoader> currencyDataLoader = GetCurrencyConverterDataLoader();
return create_task([this, currencyDataLoader]() return create_task([this, currencyDataLoader]() {
{
if (currencyDataLoader != nullptr) if (currencyDataLoader != nullptr)
{ {
return currencyDataLoader->TryLoadDataFromWebOverrideAsync(); return currencyDataLoader->TryLoadDataFromWebOverrideAsync();
@ -694,8 +696,9 @@ task<pair<bool, wstring>> UnitConverter::RefreshCurrencyRatios()
{ {
return task_from_result(false); return task_from_result(false);
} }
}).then([this, currencyDataLoader](bool didLoad) })
{ .then(
[this, currencyDataLoader](bool didLoad) {
wstring timestamp = L""; wstring timestamp = L"";
if (currencyDataLoader != nullptr) if (currencyDataLoader != nullptr)
{ {
@ -703,7 +706,8 @@ task<pair<bool, wstring>> UnitConverter::RefreshCurrencyRatios()
} }
return make_pair(didLoad, timestamp); return make_pair(didLoad, timestamp);
}, task_continuation_context::use_default()); },
task_continuation_context::use_default());
} }
shared_ptr<ICurrencyConverterDataLoader> UnitConverter::GetCurrencyConverterDataLoader() shared_ptr<ICurrencyConverterDataLoader> UnitConverter::GetCurrencyConverterDataLoader()
@ -760,9 +764,7 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
} }
// Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value // Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value
sort(intermediateVector.begin(), intermediateVector.end(), [] sort(intermediateVector.begin(), intermediateVector.end(), [](SuggestedValueIntermediate first, SuggestedValueIntermediate second) {
(SuggestedValueIntermediate first, SuggestedValueIntermediate second)
{
if (abs(first.magnitude) == abs(second.magnitude)) if (abs(first.magnitude) == abs(second.magnitude))
{ {
return first.magnitude > second.magnitude; return first.magnitude > second.magnitude;
@ -798,9 +800,7 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
// The Whimsicals are determined differently // The Whimsicals are determined differently
// Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value // Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value
sort(intermediateWhimsicalVector.begin(), intermediateWhimsicalVector.end(), [] sort(intermediateWhimsicalVector.begin(), intermediateWhimsicalVector.end(), [](SuggestedValueIntermediate first, SuggestedValueIntermediate second) {
(SuggestedValueIntermediate first, SuggestedValueIntermediate second)
{
if (abs(first.magnitude) == abs(second.magnitude)) if (abs(first.magnitude) == abs(second.magnitude))
{ {
return first.magnitude > second.magnitude; return first.magnitude > second.magnitude;
@ -922,7 +922,6 @@ shared_ptr<IConverterDataLoader> UnitConverter::GetDataLoaderForCategory(const C
/// </summary> /// </summary>
void UnitConverter::InitializeSelectedUnits() void UnitConverter::InitializeSelectedUnits()
{ {
if (m_categoryToUnits.empty()) if (m_categoryToUnits.empty())
{ {
return; return;

View file

@ -15,13 +15,22 @@ namespace UnitConversionManager
struct Unit struct Unit
{ {
Unit(){} Unit()
{
}
Unit(int id, std::wstring name, std::wstring abbreviation, bool isConversionSource, bool isConversionTarget, bool isWhimsical) Unit(int id, std::wstring name, std::wstring abbreviation, bool isConversionSource, bool isConversionTarget, bool isWhimsical)
: id(id), name(name), accessibleName(name), abbreviation(abbreviation), isConversionSource(isConversionSource), isConversionTarget(isConversionTarget), isWhimsical(isWhimsical) : id(id)
, name(name)
, accessibleName(name)
, abbreviation(abbreviation)
, isConversionSource(isConversionSource)
, isConversionTarget(isConversionTarget)
, isWhimsical(isWhimsical)
{ {
} }
Unit(int id, std::wstring currencyName, std::wstring countryName, std::wstring abbreviation, bool isRtlLanguage, bool isConversionSource, bool isConversionTarget) Unit(int id, std::wstring currencyName, std::wstring countryName, std::wstring abbreviation, bool isRtlLanguage, bool isConversionSource,
bool isConversionTarget)
: id(id), abbreviation(abbreviation), isConversionSource(isConversionSource), isConversionTarget(isConversionTarget), isWhimsical(false) : id(id), abbreviation(abbreviation), isConversionSource(isConversionSource), isConversionTarget(isConversionTarget), isWhimsical(false)
{ {
std::wstring nameValue1 = isRtlLanguage ? currencyName : countryName; std::wstring nameValue1 = isRtlLanguage ? currencyName : countryName;
@ -31,7 +40,9 @@ namespace UnitConversionManager
accessibleName = nameValue1 + L" " + nameValue2; accessibleName = nameValue1 + L" " + nameValue2;
} }
virtual ~Unit() {} virtual ~Unit()
{
}
int id; int id;
std::wstring name; std::wstring name;
@ -61,7 +72,9 @@ namespace UnitConversionManager
struct Category struct Category
{ {
Category(){} Category()
{
}
Category(int id, std::wstring name, bool supportsNegative) : id(id), name(name), supportsNegative(supportsNegative) Category(int id, std::wstring name, bool supportsNegative) : id(id), name(name), supportsNegative(supportsNegative)
{ {
@ -85,7 +98,8 @@ namespace UnitConversionManager
class UnitHash class UnitHash
{ {
public: public:
size_t operator() (const Unit & x) const { size_t operator()(const Unit& x) const
{
return x.id; return x.id;
} }
}; };
@ -93,7 +107,8 @@ namespace UnitConversionManager
class CategoryHash class CategoryHash
{ {
public: public:
size_t operator() (const Category & x) const { size_t operator()(const Category& x) const
{
return x.id; return x.id;
} }
}; };
@ -107,12 +122,16 @@ namespace UnitConversionManager
struct ConversionData struct ConversionData
{ {
ConversionData(){} ConversionData()
{
}
ConversionData(double ratio, double offset, bool offsetFirst) : ratio(ratio), offset(offset), offsetFirst(offsetFirst) ConversionData(double ratio, double offset, bool offsetFirst) : ratio(ratio), offset(offset), offsetFirst(offsetFirst)
{ {
} }
virtual ~ConversionData() {} virtual ~ConversionData()
{
}
double ratio; double ratio;
double offset; double offset;
@ -136,8 +155,12 @@ namespace UnitConversionManager
}; };
typedef std::tuple<std::vector<UnitConversionManager::Unit>, UnitConversionManager::Unit, UnitConversionManager::Unit> CategorySelectionInitializer; typedef std::tuple<std::vector<UnitConversionManager::Unit>, UnitConversionManager::Unit, UnitConversionManager::Unit> CategorySelectionInitializer;
typedef std::unordered_map<UnitConversionManager::Unit, std::unordered_map<UnitConversionManager::Unit, UnitConversionManager::ConversionData, UnitConversionManager::UnitHash>, UnitConversionManager::UnitHash> UnitToUnitToConversionDataMap; typedef std::unordered_map<UnitConversionManager::Unit,
typedef std::unordered_map<UnitConversionManager::Category, std::vector<UnitConversionManager::Unit>, UnitConversionManager::CategoryHash> CategoryToUnitVectorMap; std::unordered_map<UnitConversionManager::Unit, UnitConversionManager::ConversionData, UnitConversionManager::UnitHash>,
UnitConversionManager::UnitHash>
UnitToUnitToConversionDataMap;
typedef std::unordered_map<UnitConversionManager::Category, std::vector<UnitConversionManager::Unit>, UnitConversionManager::CategoryHash>
CategoryToUnitVectorMap;
class IViewModelCurrencyCallback class IViewModelCurrencyCallback
{ {
@ -165,8 +188,10 @@ namespace UnitConversionManager
{ {
public: public:
virtual void SetViewModelCallback(const std::shared_ptr<UnitConversionManager::IViewModelCurrencyCallback>& callback) = 0; virtual void SetViewModelCallback(const std::shared_ptr<UnitConversionManager::IViewModelCurrencyCallback>& callback) = 0;
virtual std::pair<std::wstring, std::wstring> GetCurrencySymbols(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) = 0; virtual std::pair<std::wstring, std::wstring> GetCurrencySymbols(_In_ const UnitConversionManager::Unit& unit1,
virtual std::pair<std::wstring, std::wstring> GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) = 0; _In_ const UnitConversionManager::Unit& unit2) = 0;
virtual std::pair<std::wstring, std::wstring> GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1,
_In_ const UnitConversionManager::Unit& unit2) = 0;
virtual std::wstring GetCurrencyTimestamp() = 0; virtual std::wstring GetCurrencyTimestamp() = 0;
virtual concurrency::task<bool> TryLoadDataFromCacheAsync() = 0; virtual concurrency::task<bool> TryLoadDataFromCacheAsync() = 0;
@ -186,7 +211,9 @@ namespace UnitConversionManager
class IUnitConverter class IUnitConverter
{ {
public: public:
virtual ~IUnitConverter() { } virtual ~IUnitConverter()
{
}
virtual void Initialize() = 0; // Use to initialize first time, use deserialize instead to rehydrate virtual void Initialize() = 0; // Use to initialize first time, use deserialize instead to rehydrate
virtual std::vector<Category> GetCategories() = 0; virtual std::vector<Category> GetCategories() = 0;
virtual CategorySelectionInitializer SetCurrentCategory(const Category& input) = 0; virtual CategorySelectionInitializer SetCurrentCategory(const Category& input) = 0;

View file

@ -38,13 +38,13 @@ namespace
StringReference ClearMemoryVisibilityPropertyName(L"ClearMemoryVisibility"); StringReference ClearMemoryVisibilityPropertyName(L"ClearMemoryVisibility");
} }
ApplicationViewModel::ApplicationViewModel() : ApplicationViewModel::ApplicationViewModel()
m_CalculatorViewModel(nullptr), : m_CalculatorViewModel(nullptr)
m_DateCalcViewModel(nullptr), , m_DateCalcViewModel(nullptr)
m_ConverterViewModel(nullptr), , m_ConverterViewModel(nullptr)
m_PreviousMode(ViewMode::None), , m_PreviousMode(ViewMode::None)
m_mode(ViewMode::None), , m_mode(ViewMode::None)
m_categories(nullptr) , m_categories(nullptr)
{ {
SetMenuCategories(); SetMenuCategories();
} }

View file

@ -11,8 +11,7 @@ namespace CalculatorApp
{ {
namespace ViewModel namespace ViewModel
{ {
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class ApplicationViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class ApplicationViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
public: public:
ApplicationViewModel(); ApplicationViewModel();
@ -60,8 +59,7 @@ namespace CalculatorApp
{ {
Windows::UI::Xaml::Visibility get() Windows::UI::Xaml::Visibility get()
{ {
return CalculatorApp::Common::NavCategory::IsCalculatorViewMode(Mode) return CalculatorApp::Common::NavCategory::IsCalculatorViewMode(Mode) ? Windows::UI::Xaml::Visibility::Visible
? Windows::UI::Xaml::Visibility::Visible
: Windows::UI::Xaml::Visibility::Collapsed; : Windows::UI::Xaml::Visibility::Collapsed;
} }
} }

View file

@ -3,30 +3,30 @@
#pragma once #pragma once
namespace CalculatorApp { namespace Common namespace CalculatorApp
{ {
ref class AlwaysSelectedCollectionView sealed: namespace Common
public Windows::UI::Xaml::DependencyObject,
public Windows::UI::Xaml::Data::ICollectionView
{ {
internal: ref class AlwaysSelectedCollectionView sealed : public Windows::UI::Xaml::DependencyObject, public Windows::UI::Xaml::Data::ICollectionView
AlwaysSelectedCollectionView(Windows::UI::Xaml::Interop::IBindableVector^ source): {
m_currentPosition(-1) internal : AlwaysSelectedCollectionView(Windows::UI::Xaml::Interop::IBindableVector ^ source) : m_currentPosition(-1)
{ {
m_source = source; m_source = source;
Windows::UI::Xaml::Interop::IBindableObservableVector^ observable = dynamic_cast<Windows::UI::Xaml::Interop::IBindableObservableVector^>(source); Windows::UI::Xaml::Interop::IBindableObservableVector ^ observable =
dynamic_cast<Windows::UI::Xaml::Interop::IBindableObservableVector ^>(source);
if (observable) if (observable)
{ {
observable->VectorChanged += observable->VectorChanged += ref new Windows::UI::Xaml::Interop::BindableVectorChangedEventHandler(
ref new Windows::UI::Xaml::Interop::BindableVectorChangedEventHandler(this, &AlwaysSelectedCollectionView::OnSourceBindableVectorChanged); this, &AlwaysSelectedCollectionView::OnSourceBindableVectorChanged);
} }
} }
private: private:
// ICollectionView // ICollectionView
// Not implemented methods // Not implemented methods
virtual WF::IAsyncOperation<Windows::UI::Xaml::Data::LoadMoreItemsResult>^ LoadMoreItemsAsync(unsigned int) = Windows::UI::Xaml::Data::ICollectionView::LoadMoreItemsAsync virtual WF::IAsyncOperation<
Windows::UI::Xaml::Data::LoadMoreItemsResult> ^ LoadMoreItemsAsync(unsigned int) = Windows::UI::Xaml::Data::ICollectionView::LoadMoreItemsAsync
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
@ -46,14 +46,13 @@ namespace CalculatorApp { namespace Common
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
property Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ CollectionGroups property Windows::Foundation::Collections::IObservableVector<Platform::Object ^> ^ CollectionGroups {
{ virtual Windows::Foundation::Collections::IObservableVector<Platform::Object
virtual Windows::Foundation::Collections::IObservableVector<Platform::Object^>^ get() = Windows::UI::Xaml::Data::ICollectionView::CollectionGroups::get ^> ^ get() = Windows::UI::Xaml::Data::ICollectionView::CollectionGroups::get
{ {
return ref new Platform::Collections::Vector<Platform::Object ^>(); return ref new Platform::Collections::Vector<Platform::Object ^>();
} }
} } property bool HasMoreItems
property bool HasMoreItems
{ {
virtual bool get() = Windows::UI::Xaml::Data::ICollectionView::HasMoreItems::get virtual bool get() = Windows::UI::Xaml::Data::ICollectionView::HasMoreItems::get
{ {
@ -82,11 +81,7 @@ namespace CalculatorApp { namespace Common
if (m_currentPosition >= 0 && m_currentPosition < static_cast<int>(m_source->Size)) if (m_currentPosition >= 0 && m_currentPosition < static_cast<int>(m_source->Size))
{ {
this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler( ref new Windows::UI::Core::DispatchedHandler([this]() { m_currentChanged(this, nullptr); }));
[this]()
{
m_currentChanged(this, nullptr);
}));
} }
return false; return false;
} }
@ -172,11 +167,14 @@ namespace CalculatorApp { namespace Common
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
virtual unsigned int GetMany(unsigned int /*startIndex*/, Platform::WriteOnlyArray<Platform::Object^>^ /*items*/) = Windows::Foundation::Collections::IVector<Platform::Object^>::GetMany virtual unsigned int
GetMany(unsigned int /*startIndex*/,
Platform::WriteOnlyArray<Platform::Object ^> ^ /*items*/) = Windows::Foundation::Collections::IVector<Platform::Object ^>::GetMany
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
virtual Windows::Foundation::Collections::IVectorView<Platform::Object^>^ GetView() = Windows::Foundation::Collections::IVector<Platform::Object^>::GetView virtual Windows::Foundation::Collections::IVectorView<Platform::Object ^> ^ GetView() = Windows::Foundation::Collections::IVector<Platform::Object
^>::GetView
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
@ -192,7 +190,8 @@ namespace CalculatorApp { namespace Common
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
virtual void ReplaceAll(const Platform::Array<Platform::Object^>^ /*items*/) = Windows::Foundation::Collections::IVector<Platform::Object^>::ReplaceAll virtual void
ReplaceAll(const Platform::Array<Platform::Object ^> ^ /*items*/) = Windows::Foundation::Collections::IVector<Platform::Object ^>::ReplaceAll
{ {
throw ref new Platform::NotImplementedException(); throw ref new Platform::NotImplementedException();
} }
@ -254,17 +253,17 @@ namespace CalculatorApp { namespace Common
event Windows::Foundation::Collections::VectorChangedEventHandler<Platform::Object ^> ^ m_vectorChanged; event Windows::Foundation::Collections::VectorChangedEventHandler<Platform::Object ^> ^ m_vectorChanged;
}; };
public ref class AlwaysSelectedCollectionViewConverter sealed: public Windows::UI::Xaml::Data::IValueConverter public
ref class AlwaysSelectedCollectionViewConverter sealed : public Windows::UI::Xaml::Data::IValueConverter
{ {
public: public:
AlwaysSelectedCollectionViewConverter() AlwaysSelectedCollectionViewConverter()
{ } {
}
private: private:
virtual Platform::Object^ Convert( virtual Platform::Object
Platform::Object^ value, ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert
{ {
auto result = dynamic_cast<Windows::UI::Xaml::Interop::IBindableVector ^>(value); auto result = dynamic_cast<Windows::UI::Xaml::Interop::IBindableVector ^>(value);
@ -275,13 +274,12 @@ namespace CalculatorApp { namespace Common
return Windows::UI::Xaml::DependencyProperty::UnsetValue; // Can't convert return Windows::UI::Xaml::DependencyProperty::UnsetValue; // Can't convert
} }
virtual Platform::Object^ ConvertBack( virtual Platform::Object
Platform::Object^ /*value*/, ^ ConvertBack(Platform::Object ^ /*value*/, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack
{ {
return Windows::UI::Xaml::DependencyProperty::UnsetValue; return Windows::UI::Xaml::DependencyProperty::UnsetValue;
} }
}; };
}} }
}

View file

@ -11,7 +11,8 @@
namespace CalculatorApp::Common::Automation namespace CalculatorApp::Common::Automation
{ {
public interface class INarratorAnnouncementHost public
interface class INarratorAnnouncementHost
{ {
public: public:
// Is the host available on this OS. // Is the host available on this OS.

View file

@ -9,9 +9,9 @@ using namespace Windows::UI::Xaml::Automation;
using namespace Windows::UI::Xaml::Automation::Peers; using namespace Windows::UI::Xaml::Automation::Peers;
using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls;
LiveRegionHost::LiveRegionHost() : LiveRegionHost::LiveRegionHost() : m_host(nullptr)
m_host(nullptr) {
{} }
bool LiveRegionHost::IsHostAvailable() bool LiveRegionHost::IsHostAvailable()
{ {

View file

@ -16,7 +16,8 @@ namespace CalculatorApp::Common::Automation
// When the app switches to min version RS3, this class can be removed // When the app switches to min version RS3, this class can be removed
// and the app will switch to using the Notification API. // and the app will switch to using the Notification API.
// TODO - MSFT 12735088 // TODO - MSFT 12735088
public ref class LiveRegionHost sealed : public INarratorAnnouncementHost public
ref class LiveRegionHost sealed : public INarratorAnnouncementHost
{ {
public: public:
LiveRegionHost(); LiveRegionHost();

View file

@ -25,17 +25,11 @@ namespace CalculatorApp::Common::Automation
} }
} }
NarratorAnnouncement::NarratorAnnouncement( NarratorAnnouncement::NarratorAnnouncement(String ^ announcement, String ^ activityId, AutomationNotificationKind kind,
String^ announcement,
String^ activityId,
AutomationNotificationKind kind,
AutomationNotificationProcessing processing) AutomationNotificationProcessing processing)
: : m_announcement(announcement), m_activityId(activityId), m_kind(kind), m_processing(processing)
m_announcement(announcement), {
m_activityId(activityId), }
m_kind(kind),
m_processing(processing)
{}
String ^ NarratorAnnouncement::Announcement::get() String ^ NarratorAnnouncement::Announcement::get()
{ {
@ -59,106 +53,71 @@ AutomationNotificationProcessing NarratorAnnouncement::Processing::get()
bool NarratorAnnouncement::IsValid(NarratorAnnouncement ^ announcement) bool NarratorAnnouncement::IsValid(NarratorAnnouncement ^ announcement)
{ {
return announcement != nullptr return announcement != nullptr && announcement->Announcement != nullptr && !announcement->Announcement->IsEmpty();
&& announcement->Announcement != nullptr
&& !announcement->Announcement->IsEmpty();
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayUpdatedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayUpdatedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::DisplayUpdated, AutomationNotificationKind::Other,
announcement,
CalculatorActivityIds::DisplayUpdated,
AutomationNotificationKind::Other,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetMaxDigitsReachedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetMaxDigitsReachedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MaxDigitsReached, AutomationNotificationKind::Other,
announcement,
CalculatorActivityIds::MaxDigitsReached,
AutomationNotificationKind::Other,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryClearedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryClearedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryCleared, AutomationNotificationKind::ItemRemoved,
announcement,
CalculatorActivityIds::MemoryCleared,
AutomationNotificationKind::ItemRemoved,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemChangedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemChangedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryItemChanged, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::MemoryItemChanged,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::MostRecent); AutomationNotificationProcessing::MostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemAddedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemAddedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryItemAdded, AutomationNotificationKind::ItemAdded,
announcement,
CalculatorActivityIds::MemoryItemAdded,
AutomationNotificationKind::ItemAdded,
AutomationNotificationProcessing::MostRecent); AutomationNotificationProcessing::MostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetHistoryClearedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetHistoryClearedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::HistoryCleared, AutomationNotificationKind::ItemRemoved,
announcement,
CalculatorActivityIds::HistoryCleared,
AutomationNotificationKind::ItemRemoved,
AutomationNotificationProcessing::MostRecent); AutomationNotificationProcessing::MostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetCategoryNameChangedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetCategoryNameChangedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::CategoryNameChanged, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::CategoryNameChanged,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetUpdateCurrencyRatesAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetUpdateCurrencyRatesAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::UpdateCurrencyRates, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::UpdateCurrencyRates,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayCopiedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayCopiedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::DisplayCopied, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::DisplayCopied,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetOpenParenthesisCountChangedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetOpenParenthesisCountChangedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::OpenParenthesisCountChanged, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::OpenParenthesisCountChanged,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }
NarratorAnnouncement ^ CalculatorAnnouncement::GetNoRightParenthesisAddedAnnouncement(String ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetNoRightParenthesisAddedAnnouncement(String ^ announcement)
{ {
return ref new NarratorAnnouncement( return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::NoParenthesisAdded, AutomationNotificationKind::ActionCompleted,
announcement,
CalculatorActivityIds::NoParenthesisAdded,
AutomationNotificationKind::ActionCompleted,
AutomationNotificationProcessing::ImportantMostRecent); AutomationNotificationProcessing::ImportantMostRecent);
} }

View file

@ -11,7 +11,8 @@ namespace CalculatorApp::Common::Automation
// enums should be removed and the Windows types should be used // enums should be removed and the Windows types should be used
// instead. // instead.
// TODO - MSFT 12735088 // TODO - MSFT 12735088
public enum class AutomationNotificationKind public
enum class AutomationNotificationKind
{ {
ItemAdded = 0, ItemAdded = 0,
ItemRemoved = 1, ItemRemoved = 1,
@ -20,7 +21,8 @@ namespace CalculatorApp::Common::Automation
Other = 4 Other = 4
}; };
public enum class AutomationNotificationProcessing public
enum class AutomationNotificationProcessing
{ {
ImportantAll = 0, ImportantAll = 0,
ImportantMostRecent = 1, ImportantMostRecent = 1,
@ -29,18 +31,15 @@ namespace CalculatorApp::Common::Automation
CurrentThenMostRecent = 4 CurrentThenMostRecent = 4
}; };
public ref class NarratorAnnouncement sealed public
ref class NarratorAnnouncement sealed
{ {
public: public:
property Platform::String^ Announcement property Platform::String
{ ^ Announcement { Platform::String ^ get(); }
Platform::String^ get();
}
property Platform::String^ ActivityId property Platform::String
{ ^ ActivityId { Platform::String ^ get(); }
Platform::String^ get();
}
property AutomationNotificationKind Kind property AutomationNotificationKind Kind
{ {
@ -59,10 +58,7 @@ namespace CalculatorApp::Common::Automation
// class that can access the private constructor. // class that can access the private constructor.
friend class CalculatorAnnouncement; friend class CalculatorAnnouncement;
NarratorAnnouncement( NarratorAnnouncement(Platform::String ^ announcement, Platform::String ^ activityId, AutomationNotificationKind kind,
Platform::String^ announcement,
Platform::String^ activityId,
AutomationNotificationKind kind,
AutomationNotificationProcessing processing); AutomationNotificationProcessing processing);
Platform::String ^ m_announcement; Platform::String ^ m_announcement;

View file

@ -32,10 +32,7 @@ void NarratorAnnouncementHostFactory::RegisterHosts()
{ {
// The host that will be used is the first available host, // The host that will be used is the first available host,
// therefore, order of hosts is important here. // therefore, order of hosts is important here.
NarratorAnnouncementHostFactory::s_hosts = { NarratorAnnouncementHostFactory::s_hosts = { ref new NotificationHost(), ref new LiveRegionHost() };
ref new NotificationHost(),
ref new LiveRegionHost()
};
} }
INarratorAnnouncementHost ^ NarratorAnnouncementHostFactory::GetHostProducer() INarratorAnnouncementHost ^ NarratorAnnouncementHostFactory::GetHostProducer()

View file

@ -17,7 +17,9 @@ namespace CalculatorApp::Common::Automation
static INarratorAnnouncementHost ^ MakeHost(); static INarratorAnnouncementHost ^ MakeHost();
private: private:
NarratorAnnouncementHostFactory() {} NarratorAnnouncementHostFactory()
{
}
static int Initialize(); static int Initialize();
static void RegisterHosts(); static void RegisterHosts();

View file

@ -22,8 +22,7 @@ NarratorNotifier::NarratorNotifier()
void NarratorNotifier::Announce(NarratorAnnouncement ^ announcement) void NarratorNotifier::Announce(NarratorAnnouncement ^ announcement)
{ {
if (NarratorAnnouncement::IsValid(announcement) if (NarratorAnnouncement::IsValid(announcement) && m_announcementHost != nullptr)
&& m_announcementHost != nullptr)
{ {
m_announcementHost->Announce(announcement); m_announcementHost->Announce(announcement);
} }
@ -31,12 +30,10 @@ void NarratorNotifier::Announce(NarratorAnnouncement^ announcement)
void NarratorNotifier::RegisterDependencyProperties() void NarratorNotifier::RegisterDependencyProperties()
{ {
s_announcementProperty = DependencyProperty::Register( s_announcementProperty = DependencyProperty::Register(L"Announcement", // The name of the dependency property.
L"Announcement", // The name of the dependency property.
NarratorAnnouncement::typeid, // The type of the dependency property. NarratorAnnouncement::typeid, // The type of the dependency property.
NarratorNotifier::typeid, // The owner of the dependency property. NarratorNotifier::typeid, // The owner of the dependency property.
ref new PropertyMetadata( ref new PropertyMetadata(nullptr, // Default value of the dependency property.
nullptr, // Default value of the dependency property.
ref new PropertyChangedCallback(OnAnnouncementChanged))); ref new PropertyChangedCallback(OnAnnouncementChanged)));
} }

View file

@ -8,7 +8,8 @@
namespace CalculatorApp::Common::Automation namespace CalculatorApp::Common::Automation
{ {
public ref class NarratorNotifier sealed : public Windows::UI::Xaml::DependencyObject public
ref class NarratorNotifier sealed : public Windows::UI::Xaml::DependencyObject
{ {
public: public:
NarratorNotifier(); NarratorNotifier();
@ -26,18 +27,12 @@ namespace CalculatorApp::Common::Automation
static void RegisterDependencyProperties(); static void RegisterDependencyProperties();
static property Windows::UI::Xaml::DependencyProperty^ AnnouncementProperty static property Windows::UI::Xaml::DependencyProperty
{ ^ AnnouncementProperty { Windows::UI::Xaml::DependencyProperty ^ get() { return s_announcementProperty; } }
Windows::UI::Xaml::DependencyProperty^ get()
{
return s_announcementProperty;
}
}
static NarratorAnnouncement^ GetAnnouncement(Windows::UI::Xaml::DependencyObject^ element) static NarratorAnnouncement
{ ^ GetAnnouncement(Windows::UI::Xaml::DependencyObject
return safe_cast<NarratorAnnouncement^>(element->GetValue(s_announcementProperty)); ^ element) { return safe_cast<NarratorAnnouncement ^>(element->GetValue(s_announcementProperty)); }
}
static void SetAnnouncement(Windows::UI::Xaml::DependencyObject ^ element, NarratorAnnouncement ^ value) static void SetAnnouncement(Windows::UI::Xaml::DependencyObject ^ element, NarratorAnnouncement ^ value)
{ {
@ -45,8 +40,7 @@ namespace CalculatorApp::Common::Automation
} }
private: private:
static void OnAnnouncementChanged( static void OnAnnouncementChanged(_In_ Windows::UI::Xaml::DependencyObject ^ dependencyObject,
_In_ Windows::UI::Xaml::DependencyObject^ dependencyObject,
_In_ Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ eventArgs); _In_ Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ eventArgs);
static Windows::UI::Xaml::DependencyProperty ^ s_announcementProperty; static Windows::UI::Xaml::DependencyProperty ^ s_announcementProperty;

View file

@ -10,15 +10,13 @@ using namespace Windows::UI::Xaml::Automation;
using namespace Windows::UI::Xaml::Automation::Peers; using namespace Windows::UI::Xaml::Automation::Peers;
using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls;
NotificationHost::NotificationHost() : NotificationHost::NotificationHost() : m_host(nullptr)
m_host(nullptr) {
{} }
bool NotificationHost::IsHostAvailable() bool NotificationHost::IsHostAvailable()
{ {
return ApiInformation::IsMethodPresent( return ApiInformation::IsMethodPresent(L"Windows.UI.Xaml.Automation.Peers.AutomationPeer", L"RaiseNotificationEvent");
L"Windows.UI.Xaml.Automation.Peers.AutomationPeer",
L"RaiseNotificationEvent");
} }
INarratorAnnouncementHost ^ NotificationHost::MakeHost() INarratorAnnouncementHost ^ NotificationHost::MakeHost()
@ -36,16 +34,12 @@ void NotificationHost::Announce(NarratorAnnouncement^ announcement)
auto peer = FrameworkElementAutomationPeer::FromElement(m_host); auto peer = FrameworkElementAutomationPeer::FromElement(m_host);
if (peer != nullptr) if (peer != nullptr)
{ {
peer->RaiseNotificationEvent( peer->RaiseNotificationEvent(GetWindowsNotificationKind(announcement->Kind), GetWindowsNotificationProcessing(announcement->Processing),
GetWindowsNotificationKind(announcement->Kind), announcement->Announcement, announcement->ActivityId);
GetWindowsNotificationProcessing(announcement->Processing),
announcement->Announcement,
announcement->ActivityId);
} }
} }
StandardPeers::AutomationNotificationKind NotificationHost::GetWindowsNotificationKind( StandardPeers::AutomationNotificationKind NotificationHost::GetWindowsNotificationKind(CustomPeers::AutomationNotificationKind customKindType)
CustomPeers::AutomationNotificationKind customKindType)
{ {
switch (customKindType) switch (customKindType)
{ {
@ -71,8 +65,8 @@ StandardPeers::AutomationNotificationKind NotificationHost::GetWindowsNotificati
return StandardPeers::AutomationNotificationKind::Other; return StandardPeers::AutomationNotificationKind::Other;
} }
StandardPeers::AutomationNotificationProcessing NotificationHost::GetWindowsNotificationProcessing( StandardPeers::AutomationNotificationProcessing
CustomPeers::AutomationNotificationProcessing customProcessingType) NotificationHost::GetWindowsNotificationProcessing(CustomPeers::AutomationNotificationProcessing customProcessingType)
{ {
switch (customProcessingType) switch (customProcessingType)
{ {

View file

@ -10,7 +10,8 @@
namespace CalculatorApp::Common::Automation namespace CalculatorApp::Common::Automation
{ {
public ref class NotificationHost sealed : public INarratorAnnouncementHost public
ref class NotificationHost sealed : public INarratorAnnouncementHost
{ {
public: public:
NotificationHost(); NotificationHost();
@ -21,14 +22,13 @@ namespace CalculatorApp::Common::Automation
virtual void Announce(NarratorAnnouncement ^ announcement); virtual void Announce(NarratorAnnouncement ^ announcement);
private: private:
static Windows::UI::Xaml::Automation::Peers::AutomationNotificationKind GetWindowsNotificationKind( static Windows::UI::Xaml::Automation::Peers::AutomationNotificationKind
CalculatorApp::Common::Automation::AutomationNotificationKind customKindType); GetWindowsNotificationKind(CalculatorApp::Common::Automation::AutomationNotificationKind customKindType);
static Windows::UI::Xaml::Automation::Peers::AutomationNotificationProcessing GetWindowsNotificationProcessing( static Windows::UI::Xaml::Automation::Peers::AutomationNotificationProcessing
CalculatorApp::Common::Automation::AutomationNotificationProcessing customProcessingType); GetWindowsNotificationProcessing(CalculatorApp::Common::Automation::AutomationNotificationProcessing customProcessingType);
private: private:
Windows::UI::Xaml::UIElement ^ m_host; Windows::UI::Xaml::UIElement ^ m_host;
}; };
} }

View file

@ -10,8 +10,9 @@ namespace CalculatorApp
/// <summary> /// <summary>
/// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models. /// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models.
/// </summary> /// </summary>
[Windows::Foundation::Metadata::WebHostHidden] [Windows::Foundation::Metadata::WebHostHidden] public ref class BindableBase : Windows::UI::Xaml::DependencyObject,
public ref class BindableBase : Windows::UI::Xaml::DependencyObject, Windows::UI::Xaml::Data::INotifyPropertyChanged, Windows::UI::Xaml::Data::ICustomPropertyProvider Windows::UI::Xaml::Data::INotifyPropertyChanged,
Windows::UI::Xaml::Data::ICustomPropertyProvider
{ {
public: public:
virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged; virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged;
@ -24,9 +25,11 @@ namespace CalculatorApp
property Windows::UI::Xaml::Interop::TypeName Type property Windows::UI::Xaml::Interop::TypeName Type
{ {
virtual Windows::UI::Xaml::Interop::TypeName get() { return this->GetType(); } virtual Windows::UI::Xaml::Interop::TypeName get()
{
return this->GetType();
}
} }
protected: protected:
virtual void OnPropertyChanged(Platform::String ^ propertyName); virtual void OnPropertyChanged(Platform::String ^ propertyName);

View file

@ -33,4 +33,3 @@ String^ CalculatorButtonPressedEventArgs::GetAuditoryFeedbackFromCommandParamete
return nullptr; return nullptr;
} }
} }

View file

@ -10,15 +10,17 @@ namespace CalculatorApp
{ {
namespace Common namespace Common
{ {
public ref class CalculatorButtonPressedEventArgs sealed public
ref class CalculatorButtonPressedEventArgs sealed
{ {
public: public:
PROPERTY_R(Platform::String ^, AuditoryFeedback); PROPERTY_R(Platform::String ^, AuditoryFeedback);
PROPERTY_R(CalculatorApp::NumbersAndOperatorsEnum, Operation); PROPERTY_R(CalculatorApp::NumbersAndOperatorsEnum, Operation);
CalculatorButtonPressedEventArgs( CalculatorButtonPressedEventArgs(Platform::String ^ feedback, CalculatorApp::NumbersAndOperatorsEnum operation)
Platform::String^ feedback, CalculatorApp::NumbersAndOperatorsEnum operation) : : m_AuditoryFeedback(feedback), m_Operation(operation)
m_AuditoryFeedback(feedback), m_Operation(operation) {} {
}
static CalculatorApp::NumbersAndOperatorsEnum GetOperationFromCommandParameter(_In_ Platform::Object ^ commandParameter); static CalculatorApp::NumbersAndOperatorsEnum GetOperationFromCommandParameter(_In_ Platform::Object ^ commandParameter);
static Platform::String ^ GetAuditoryFeedbackFromCommandParameter(_In_ Platform::Object ^ commandParameter); static Platform::String ^ GetAuditoryFeedbackFromCommandParameter(_In_ Platform::Object ^ commandParameter);

View file

@ -9,7 +9,8 @@ namespace CalculatorApp
{ {
namespace CM = CalculationManager; namespace CM = CalculationManager;
public enum class NumbersAndOperatorsEnum public
enum class NumbersAndOperatorsEnum
{ {
Zero = (int)CM::Command::Command0, Zero = (int)CM::Command::Command0,
One = (int)CM::Command::Command1, One = (int)CM::Command::Command1,
@ -164,7 +165,8 @@ namespace CalculatorApp
}; };
// This contains list of functions whose usage we are tracelogging // This contains list of functions whose usage we are tracelogging
public enum class FunctionLogEnum public
enum class FunctionLogEnum
{ {
Invert = (int)CM::Command::CommandREC, Invert = (int)CM::Command::CommandREC,
Sqrt = (int)CM::Command::CommandSQRT, Sqrt = (int)CM::Command::CommandSQRT,

View file

@ -69,7 +69,8 @@ void CalculatorDisplay::SetIsInError(bool isError)
} }
} }
void CalculatorDisplay::SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const &tokens, _Inout_ std::shared_ptr<CalculatorVector <std::shared_ptr<IExpressionCommand>>> const &commands) void CalculatorDisplay::SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& tokens,
_Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& commands)
{ {
if (m_callbackReference != nullptr) if (m_callbackReference != nullptr)
{ {

View file

@ -18,7 +18,8 @@ namespace CalculatorApp
private: private:
void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override; void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override;
void SetIsInError(bool isError) override; void SetIsInError(bool isError) override;
void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const &tokens, _Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const &commands) override; void SetExpressionDisplay(_Inout_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& tokens,
_Inout_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& commands) override;
void SetMemorizedNumbers(_In_ const std::vector<std::wstring>& memorizedNumbers) override; void SetMemorizedNumbers(_In_ const std::vector<std::wstring>& memorizedNumbers) override;
void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override; void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override;
void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override; void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override;

View file

@ -8,19 +8,19 @@ using namespace CalculatorApp::Common;
using namespace concurrency; using namespace concurrency;
using namespace std; using namespace std;
ConversionResultTaskHelper::ConversionResultTaskHelper(unsigned int delay, const function<void()> functionToRun) : ConversionResultTaskHelper::ConversionResultTaskHelper(unsigned int delay, const function<void()> functionToRun)
m_delay{ delay }, : m_delay{ delay }, m_storedFunction{ functionToRun }
m_storedFunction{ functionToRun }
{ {
auto token = m_cts.get_token(); auto token = m_cts.get_token();
auto delayTask = CompleteAfter(delay); auto delayTask = CompleteAfter(delay);
delayTask.then([this, token]() delayTask.then(
{ [this, token]() {
if (!token.is_canceled()) if (!token.is_canceled())
{ {
m_storedFunction(); m_storedFunction();
} }
}, task_continuation_context::use_current()); },
task_continuation_context::use_current());
} }
ConversionResultTaskHelper::~ConversionResultTaskHelper() ConversionResultTaskHelper::~ConversionResultTaskHelper()

View file

@ -15,10 +15,7 @@ using namespace Windows::Foundation;
using namespace Windows::System; using namespace Windows::System;
using namespace Windows::ApplicationModel::DataTransfer; using namespace Windows::ApplicationModel::DataTransfer;
String^ CopyPasteManager::supportedFormats[] = String ^ CopyPasteManager::supportedFormats[] = { StandardDataFormats::Text };
{
StandardDataFormats::Text
};
static constexpr wstring_view c_validCharacterSet{ L"0123456789()+-*/.abcdefABCDEF" }; static constexpr wstring_view c_validCharacterSet{ L"0123456789()+-*/.abcdefABCDEF" };
@ -40,41 +37,24 @@ static const wstring c_binProgrammerChars = L"[0-1]+((_|'|`)[0-1]+)*";
static const wstring c_uIntSuffixes = L"[uU]?[lL]{0,2}"; static const wstring c_uIntSuffixes = L"[uU]?[lL]{0,2}";
// RegEx Patterns used by various modes // RegEx Patterns used by various modes
static const array<wregex, 1> standardModePatterns = static const array<wregex, 1> standardModePatterns = { wregex(c_wspc + c_signedDecFloat + c_wspc) };
{ static const array<wregex, 2> scientificModePatterns = { wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + c_wspcRParens),
wregex(c_wspc + c_signedDecFloat + c_wspc) wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat
}; + L"[e]([+]|[-])+\\d+" + c_wspcRParens) };
static const array<wregex, 2> scientificModePatterns = static const array<array<wregex, 5>, 4> programmerModePatterns = {
{ { // Hex numbers like 5F, 4A0C, 0xa9, 0xFFull, 47CDh
wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + c_wspcRParens), { wregex(c_wspcLParens + L"(0[xX])?" + c_hexProgrammerChars + c_uIntSuffixes + c_wspcRParens),
wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + L"[e]([+]|[-])+\\d+" + c_wspcRParens) wregex(c_wspcLParens + c_hexProgrammerChars + L"[hH]?" + c_wspcRParens) },
};
static const array<array<wregex, 5>, 4> programmerModePatterns =
{ {
// Hex numbers like 5F, 4A0C, 0xa9, 0xFFull, 47CDh
{
wregex(c_wspcLParens + L"(0[xX])?" + c_hexProgrammerChars + c_uIntSuffixes + c_wspcRParens),
wregex(c_wspcLParens + c_hexProgrammerChars + L"[hH]?" + c_wspcRParens)
},
// Decimal numbers like -145, 145, 0n145, 123ull etc // Decimal numbers like -145, 145, 0n145, 123ull etc
{ { wregex(c_wspcLParens + L"[-+]?" + c_decProgrammerChars + L"[lL]{0,2}" + c_wspcRParens),
wregex(c_wspcLParens + L"[-+]?" + c_decProgrammerChars + L"[lL]{0,2}" +c_wspcRParens), wregex(c_wspcLParens + L"(0[nN])?" + c_decProgrammerChars + c_uIntSuffixes + c_wspcRParens) },
wregex(c_wspcLParens + L"(0[nN])?" + c_decProgrammerChars + c_uIntSuffixes + c_wspcRParens)
},
// Octal numbers like 06, 010, 0t77, 0o77, 077ull etc // Octal numbers like 06, 010, 0t77, 0o77, 077ull etc
{ { wregex(c_wspcLParens + L"(0[otOT])?" + c_octProgrammerChars + c_uIntSuffixes + c_wspcRParens) },
wregex(c_wspcLParens + L"(0[otOT])?" + c_octProgrammerChars + c_uIntSuffixes + c_wspcRParens)
},
// Binary numbers like 011010110, 0010110, 10101001, 1001b, 0b1001, 0y1001, 0b1001ull // Binary numbers like 011010110, 0010110, 10101001, 1001b, 0b1001, 0y1001, 0b1001ull
{ { wregex(c_wspcLParens + L"(0[byBY])?" + c_binProgrammerChars + c_uIntSuffixes + c_wspcRParens),
wregex(c_wspcLParens + L"(0[byBY])?" + c_binProgrammerChars + c_uIntSuffixes + c_wspcRParens), wregex(c_wspcLParens + c_binProgrammerChars + L"[bB]?" + c_wspcRParens) } }
wregex(c_wspcLParens + c_binProgrammerChars + L"[bB]?" + c_wspcRParens)
}
} };
static const array<wregex, 1> unitConverterPatterns =
{
wregex(c_wspc + L"[-+]?\\d*[.]?\\d*" + c_wspc)
}; };
static const array<wregex, 1> unitConverterPatterns = { wregex(c_wspc + L"[-+]?\\d*[.]?\\d*" + c_wspc) };
void CopyPasteManager::CopyToClipboard(String ^ stringToCopy) void CopyPasteManager::CopyToClipboard(String ^ stringToCopy)
{ {
@ -95,11 +75,9 @@ task<String^> CopyPasteManager::GetStringToPaste(ViewMode mode, CategoryGroupTyp
//-- add support to allow pasting for expressions like 1.3e12(as of now we allow 1.3e+12) //-- add support to allow pasting for expressions like 1.3e12(as of now we allow 1.3e+12)
return create_task((dataPackageView->GetTextAsync(::StandardDataFormats::Text))) return create_task((dataPackageView->GetTextAsync(::StandardDataFormats::Text)))
.then([mode, modeType, programmerNumberBase, bitLengthType](String^ pastedText) .then([mode, modeType, programmerNumberBase,
{ bitLengthType](String ^ pastedText) { return ValidatePasteExpression(pastedText, mode, modeType, programmerNumberBase, bitLengthType); },
return ValidatePasteExpression(pastedText, mode, modeType, programmerNumberBase, bitLengthType); task_continuation_context::use_arbitrary());
}
, task_continuation_context::use_arbitrary());
} }
int CopyPasteManager::ClipboardTextFormat() int CopyPasteManager::ClipboardTextFormat()
@ -223,7 +201,8 @@ vector<wstring> CopyPasteManager::ExtractOperands(const wstring& pasteExpression
if ((pasteExpression.at(i) == L'+') || (pasteExpression.at(i) == L'-')) if ((pasteExpression.at(i) == L'+') || (pasteExpression.at(i) == L'-'))
{ {
// don't break the expression into operands if the encountered character corresponds to sign command(+-) // don't break the expression into operands if the encountered character corresponds to sign command(+-)
if (isPreviousOpenParen || startOfExpression || isPreviousOperator || ((mode != ViewMode::Programmer) && !((i != 0) && (pasteExpression.at(i - 1) != L'e')))) if (isPreviousOpenParen || startOfExpression || isPreviousOperator
|| ((mode != ViewMode::Programmer) && !((i != 0) && (pasteExpression.at(i - 1) != L'e'))))
{ {
isPreviousOperator = false; isPreviousOperator = false;
continue; continue;
@ -453,11 +432,13 @@ bool CopyPasteManager::TryOperandToULL(const wstring& operand, int numberBase, u
size_t CopyPasteManager::OperandLength(const wstring& operand, ViewMode mode, CategoryGroupType modeType, int programmerNumberBase) size_t CopyPasteManager::OperandLength(const wstring& operand, ViewMode mode, CategoryGroupType modeType, int programmerNumberBase)
{ {
if (modeType == CategoryGroupType::Converter) { if (modeType == CategoryGroupType::Converter)
{
return operand.length(); return operand.length();
} }
switch(mode) { switch (mode)
{
case ViewMode::Standard: case ViewMode::Standard:
case ViewMode::Scientific: case ViewMode::Scientific:
return StandardScientificOperandLength(operand); return StandardScientificOperandLength(operand);
@ -494,7 +475,6 @@ size_t CopyPasteManager::StandardScientificOperandLength(const wstring& operand)
size_t CopyPasteManager::ProgrammerOperandLength(const wstring& operand, int numberBase) size_t CopyPasteManager::ProgrammerOperandLength(const wstring& operand, int numberBase)
{ {
vector<wstring> prefixes{}; vector<wstring> prefixes{};
vector<wstring> suffixes{}; vector<wstring> suffixes{};
switch (numberBase) switch (numberBase)

View file

@ -26,7 +26,8 @@ namespace CalculatorApp
{ {
public: public:
static void CopyToClipboard(Platform::String ^ stringToCopy); static void CopyToClipboard(Platform::String ^ stringToCopy);
static concurrency::task<Platform::String^> GetStringToPaste(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1, int bitLengthType = -1); static concurrency::task<Platform::String ^> GetStringToPaste(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType,
int programmerNumberBase = -1, int bitLengthType = -1);
static bool HasStringToPaste() static bool HasStringToPaste()
{ {
return ClipboardTextFormat() >= 0; return ClipboardTextFormat() >= 0;
@ -36,25 +37,23 @@ namespace CalculatorApp
private: private:
static int ClipboardTextFormat(); static int ClipboardTextFormat();
static Platform::String^ ValidatePasteExpression( static Platform::String
Platform::String^ pastedText, ^ ValidatePasteExpression(Platform::String ^ pastedText, CalculatorApp::Common::ViewMode mode, int programmerNumberBase, int bitLengthType);
CalculatorApp::Common::ViewMode mode, static Platform::String
int programmerNumberBase, ^ ValidatePasteExpression(Platform::String ^ pastedText, CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType,
int bitLengthType); int programmerNumberBase, int bitLengthType);
static Platform::String^ ValidatePasteExpression(
Platform::String^ pastedText,
CalculatorApp::Common::ViewMode mode,
CalculatorApp::Common::CategoryGroupType modeType,
int programmerNumberBase,
int bitLengthType);
static std::vector<std::wstring> ExtractOperands(const std::wstring& pasteExpression, CalculatorApp::Common::ViewMode mode, int programmerNumberBase = -1, int bitLengthType = -1); static std::vector<std::wstring> ExtractOperands(const std::wstring& pasteExpression, CalculatorApp::Common::ViewMode mode,
static bool ExpressionRegExMatch(std::vector<std::wstring> operands, CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1, int bitLengthType = -1); int programmerNumberBase = -1, int bitLengthType = -1);
static bool ExpressionRegExMatch(std::vector<std::wstring> operands, CalculatorApp::Common::ViewMode mode,
CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1, int bitLengthType = -1);
static std::pair<size_t, uint64_t> GetMaxOperandLengthAndValue(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1, int bitLengthType = -1); static std::pair<size_t, uint64_t> GetMaxOperandLengthAndValue(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType,
int programmerNumberBase = -1, int bitLengthType = -1);
static std::wstring SanitizeOperand(const std::wstring& operand); static std::wstring SanitizeOperand(const std::wstring& operand);
static bool TryOperandToULL(const std::wstring& operand, int numberBase, unsigned long long int& result); static bool TryOperandToULL(const std::wstring& operand, int numberBase, unsigned long long int& result);
static size_t OperandLength(const std::wstring& operand, CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1); static size_t OperandLength(const std::wstring& operand, CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType,
int programmerNumberBase = -1);
static size_t StandardScientificOperandLength(const std::wstring& operand); static size_t StandardScientificOperandLength(const std::wstring& operand);
static size_t ProgrammerOperandLength(const std::wstring& operand, int numberBase); static size_t ProgrammerOperandLength(const std::wstring& operand, int numberBase);
static std::wstring RemoveUnwantedCharsFromWstring(const std::wstring& input); static std::wstring RemoveUnwantedCharsFromWstring(const std::wstring& input);

View file

@ -28,9 +28,10 @@ bool DateCalculationEngine::AddDuration(_In_ DateTime startDate, _In_ const Date
// The Japanese Era system can have multiple year partitions within the same year. // The Japanese Era system can have multiple year partitions within the same year.
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1. // For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results in a date in Heisei 31. // The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results
// To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date math, and then convert back to the Japanese era system. // in a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date
// This works because the Japanese era system maintains the same year/month boundaries and durations as the Gregorian system and is only different in display value. // math, and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and
// durations as the Gregorian system and is only different in display value.
if (currentCalendarSystem == CalendarIdentifiers::Japanese) if (currentCalendarSystem == CalendarIdentifiers::Japanese)
{ {
m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian); m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian);
@ -79,9 +80,10 @@ bool DateCalculationEngine::SubtractDuration(_In_ DateTime startDate, _In_ const
// The Japanese Era system can have multiple year partitions within the same year. // The Japanese Era system can have multiple year partitions within the same year.
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1. // For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results in a date in Heisei 31. // The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results
// To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date math, and then convert back to the Japanese era system. // in a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date
// This works because the Japanese era system maintains the same year/month boundaries and durations as the Gregorian system and is only different in display value. // math, and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and
// durations as the Gregorian system and is only different in display value.
if (currentCalendarSystem == CalendarIdentifiers::Japanese) if (currentCalendarSystem == CalendarIdentifiers::Japanese)
{ {
m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian); m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian);
@ -149,8 +151,7 @@ void DateCalculationEngine::GetDateDifference(_In_ DateTime date1, _In_ DateTime
UINT approximateDaysInYear; UINT approximateDaysInYear;
// If we're unable to calculate the days-in-month or days-in-year, we'll leave the values at 0. // If we're unable to calculate the days-in-month or days-in-year, we'll leave the values at 0.
if (TryGetCalendarDaysInMonth(startDate, daysInMonth) if (TryGetCalendarDaysInMonth(startDate, daysInMonth) && TryGetCalendarDaysInYear(endDate, approximateDaysInYear))
&& TryGetCalendarDaysInYear(endDate, approximateDaysInYear))
{ {
UINT daysIn[c_unitsOfDate] = { approximateDaysInYear, daysInMonth, c_daysInWeek, 1 }; UINT daysIn[c_unitsOfDate] = { approximateDaysInYear, daysInMonth, c_daysInWeek, 1 };
@ -233,7 +234,6 @@ void DateCalculationEngine::GetDateDifference(_In_ DateTime date1, _In_ DateTime
difference->day = differenceInDates[3]; difference->day = differenceInDates[3];
} }
// Private Methods // Private Methods
// Gets number of days between the two date time values // Gets number of days between the two date time values
@ -311,9 +311,10 @@ DateTime DateCalculationEngine::AdjustCalendarDate(Windows::Foundation::DateTime
// The Japanese Era system can have multiple year partitions within the same year. // The Japanese Era system can have multiple year partitions within the same year.
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1. // For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results in a date in Heisei 31. // The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results in
// To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date math, and then convert back to the Japanese era system. // a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date math,
// This works because the Japanese era system maintains the same year/month boundaries and durations as the Gregorian system and is only different in display value. // and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and durations as
// the Gregorian system and is only different in display value.
auto currentCalendarSystem = m_calendar->GetCalendarSystem(); auto currentCalendarSystem = m_calendar->GetCalendarSystem();
if (currentCalendarSystem == CalendarIdentifiers::Japanese) if (currentCalendarSystem == CalendarIdentifiers::Japanese)
{ {

View file

@ -19,7 +19,8 @@ namespace CalculatorApp
{ {
namespace DateCalculation namespace DateCalculation
{ {
public enum class _Enum_is_bitflag_ DateUnit public
enum class _Enum_is_bitflag_ DateUnit
{ {
Year = 0x01, Year = 0x01,
Month = 0x02, Month = 0x02,
@ -43,9 +44,12 @@ namespace CalculatorApp
DateCalculationEngine(_In_ Platform::String ^ calendarIdentifier); DateCalculationEngine(_In_ Platform::String ^ calendarIdentifier);
// Public Methods // Public Methods
bool __nothrow AddDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration, _Out_ Windows::Foundation::DateTime *endDate); bool __nothrow AddDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration,
bool __nothrow SubtractDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration, _Out_ Windows::Foundation::DateTime *endDate); _Out_ Windows::Foundation::DateTime* endDate);
void __nothrow GetDateDifference(_In_ Windows::Foundation::DateTime date1, _In_ Windows::Foundation::DateTime date2, _In_ DateUnit outputFormat, _Out_ DateDifference *difference); bool __nothrow SubtractDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration,
_Out_ Windows::Foundation::DateTime* endDate);
void __nothrow GetDateDifference(_In_ Windows::Foundation::DateTime date1, _In_ Windows::Foundation::DateTime date2, _In_ DateUnit outputFormat,
_Out_ DateDifference* difference);
private: private:
// Private Variables // Private Variables

View file

@ -14,13 +14,11 @@ namespace CalculatorApp
typedef void (TTarget::*CommandHandlerFunc)(Platform::Object ^); typedef void (TTarget::*CommandHandlerFunc)(Platform::Object ^);
DelegateCommand(TTarget^ target, CommandHandlerFunc func): DelegateCommand(TTarget ^ target, CommandHandlerFunc func) : m_weakTarget(target), m_function(func)
m_weakTarget(target), {
m_function(func) }
{ }
private: private:
// Explicit, and private, implementation of ICommand, this way of programming makes it so // Explicit, and private, implementation of ICommand, this way of programming makes it so
// the ICommand methods will only be available if the ICommand interface is requested via a dynamic_cast // the ICommand methods will only be available if the ICommand interface is requested via a dynamic_cast
// The ICommand interface is meant to be consumed by Xaml and not by the app, this is a defensive measure against // The ICommand interface is meant to be consumed by Xaml and not by the app, this is a defensive measure against
@ -57,12 +55,10 @@ namespace CalculatorApp
CommandHandlerFunc m_function; CommandHandlerFunc m_function;
Platform::WeakReference m_weakTarget; Platform::WeakReference m_weakTarget;
}; };
template <typename TTarget, typename TFuncPtr> template <typename TTarget, typename TFuncPtr>
DelegateCommand<TTarget>^ MakeDelegate(TTarget^ target, TFuncPtr&& function) DelegateCommand<TTarget> ^ MakeDelegate(TTarget ^ target, TFuncPtr&& function) {
{
return ref new DelegateCommand<TTarget>(target, std::forward<TFuncPtr>(function)); return ref new DelegateCommand<TTarget>(target, std::forward<TFuncPtr>(function));
} }

View file

@ -7,20 +7,21 @@
namespace CalculatorApp::Common namespace CalculatorApp::Common
{ {
public enum class TokenType public
enum class TokenType
{ {
Operator, Operator,
Operand, Operand,
Separator Separator
}; };
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class DisplayExpressionToken sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class DisplayExpressionToken sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
internal: internal : DisplayExpressionToken(Platform::String ^ token, int tokenPosition, bool fEditable, TokenType type)
DisplayExpressionToken(Platform::String^ token, int tokenPosition, bool fEditable, TokenType type) : : m_Token(token), m_TokenPosition(tokenPosition), m_IsTokenEditable(fEditable), m_Type(type), m_OriginalToken(token), m_InEditMode(false)
m_Token(token), m_TokenPosition(tokenPosition), m_IsTokenEditable(fEditable), m_Type(type), m_OriginalToken(token), m_InEditMode(false) {
{} }
public: public:
OBSERVABLE_OBJECT(); OBSERVABLE_OBJECT();
OBSERVABLE_PROPERTY_RW(Platform::String ^, Token); OBSERVABLE_PROPERTY_RW(Platform::String ^, Token);
@ -29,8 +30,12 @@ namespace CalculatorApp::Common
OBSERVABLE_PROPERTY_RW(int, CommandIndex); OBSERVABLE_PROPERTY_RW(int, CommandIndex);
OBSERVABLE_PROPERTY_R(Platform::String ^, OriginalToken); OBSERVABLE_PROPERTY_R(Platform::String ^, OriginalToken);
property bool IsTokenInEditMode { property bool IsTokenInEditMode
bool get() { return m_InEditMode; } {
bool get()
{
return m_InEditMode;
}
void set(bool val) void set(bool val)
{ {
if (!val) if (!val)
@ -40,8 +45,8 @@ namespace CalculatorApp::Common
m_InEditMode = val; m_InEditMode = val;
} }
} }
internal: internal : OBSERVABLE_PROPERTY_RW(TokenType, Type);
OBSERVABLE_PROPERTY_RW(TokenType, Type);
private: private:
bool m_InEditMode; bool m_InEditMode;
}; };

View file

@ -7,7 +7,9 @@
using namespace CalculatorApp::Common; using namespace CalculatorApp::Common;
using namespace Windows::Storage::Streams; using namespace Windows::Storage::Streams;
CommandDeserializer::CommandDeserializer(_In_ DataReader^ dataReader) :m_dataReader(dataReader){} CommandDeserializer::CommandDeserializer(_In_ DataReader ^ dataReader) : m_dataReader(dataReader)
{
}
std::shared_ptr<IExpressionCommand> CommandDeserializer::Deserialize(_In_ CalculationManager::CommandType cmdType) std::shared_ptr<IExpressionCommand> CommandDeserializer::Deserialize(_In_ CalculationManager::CommandType cmdType)
{ {

View file

@ -92,9 +92,7 @@ namespace CalculatorApp
WeakReference timerWeakReference(timer); WeakReference timerWeakReference(timer);
WeakReference buttonWeakReference(button); WeakReference buttonWeakReference(button);
timer->Tick += ref new EventHandler<Object^>( timer->Tick += ref new EventHandler<Object ^>([buttonWeakReference, timerWeakReference](Object ^, Object ^) {
[buttonWeakReference, timerWeakReference](Object^, Object^)
{
auto button = buttonWeakReference.Resolve<ButtonBase>(); auto button = buttonWeakReference.Resolve<ButtonBase>();
if (button) if (button)
{ {
@ -205,10 +203,7 @@ void KeyboardShortcutManager::HonorEscape()
} }
} }
void KeyboardShortcutManager::OnCharacterPropertyChanged( void KeyboardShortcutManager::OnCharacterPropertyChanged(DependencyObject ^ target, String ^ oldValue, String ^ newValue)
DependencyObject^ target,
String^ oldValue,
String^ newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -254,10 +249,7 @@ void KeyboardShortcutManager::OnCharacterPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -280,10 +272,7 @@ void KeyboardShortcutManager::OnVirtualKeyPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyControlChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyControlChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -312,10 +301,7 @@ void KeyboardShortcutManager::OnVirtualKeyControlChordPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyShiftChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyShiftChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -338,10 +324,7 @@ void KeyboardShortcutManager::OnVirtualKeyShiftChordPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyAltChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyAltChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -364,10 +347,7 @@ void KeyboardShortcutManager::OnVirtualKeyAltChordPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyControlShiftChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyControlShiftChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -390,10 +370,7 @@ void KeyboardShortcutManager::OnVirtualKeyControlShiftChordPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyInverseChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyInverseChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -416,10 +393,7 @@ void KeyboardShortcutManager::OnVirtualKeyInverseChordPropertyChanged(
} }
} }
void KeyboardShortcutManager::OnVirtualKeyControlInverseChordPropertyChanged( void KeyboardShortcutManager::OnVirtualKeyControlInverseChordPropertyChanged(DependencyObject ^ target, MyVirtualKey /*oldValue*/, MyVirtualKey newValue)
DependencyObject^ target,
MyVirtualKey /*oldValue*/,
MyVirtualKey newValue)
{ {
// Writer lock for the static maps // Writer lock for the static maps
reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock); reader_writer_lock::scoped_lock lock(s_keyboardShortcutMapLock);
@ -472,7 +446,8 @@ const std::multimap<MyVirtualKey, WeakReference>& GetCurrentKeyDictionary(MyVirt
{ {
return s_VirtualKeyAltChordsForButtons.find(viewId)->second; return s_VirtualKeyAltChordsForButtons.find(viewId)->second;
} }
else if ((s_ShiftKeyPressed.find(viewId)->second) && ((Window::Current->CoreWindow->GetKeyState(VirtualKey::Control) & CoreVirtualKeyStates::Down) == CoreVirtualKeyStates::Down)) else if ((s_ShiftKeyPressed.find(viewId)->second)
&& ((Window::Current->CoreWindow->GetKeyState(VirtualKey::Control) & CoreVirtualKeyStates::Down) == CoreVirtualKeyStates::Down))
{ {
return s_VirtualKeyControlShiftChordsForButtons.find(viewId)->second; return s_VirtualKeyControlShiftChordsForButtons.find(viewId)->second;
} }
@ -536,9 +511,7 @@ void KeyboardShortcutManager::OnKeyDownHandler(CoreWindow^ sender, KeyEventArgs^
bool isShiftKeyPressed = (currentShiftKeyPressed != s_ShiftKeyPressed.end()) && (currentShiftKeyPressed->second); bool isShiftKeyPressed = (currentShiftKeyPressed != s_ShiftKeyPressed.end()) && (currentShiftKeyPressed->second);
// Handle Ctrl + E for DateCalculator // Handle Ctrl + E for DateCalculator
if ((key == VirtualKey::E) && if ((key == VirtualKey::E) && isControlKeyPressed && !isShiftKeyPressed)
isControlKeyPressed &&
!isShiftKeyPressed)
{ {
const auto& lookupMap = GetCurrentKeyDictionary(static_cast<MyVirtualKey>(key)); const auto& lookupMap = GetCurrentKeyDictionary(static_cast<MyVirtualKey>(key));
auto buttons = lookupMap.equal_range(static_cast<MyVirtualKey>(key)); auto buttons = lookupMap.equal_range(static_cast<MyVirtualKey>(key));
@ -615,9 +588,9 @@ void KeyboardShortcutManager::OnKeyDownHandler(CoreWindow^ sender, KeyEventArgs^
{ {
RunFirstEnabledButtonCommand(buttons); RunFirstEnabledButtonCommand(buttons);
// Ctrl+C and Ctrl+V shifts focus to some button because of which enter doesn't work after copy/paste. So don't shift focus if Ctrl+C or Ctrl+V is pressed. // Ctrl+C and Ctrl+V shifts focus to some button because of which enter doesn't work after copy/paste. So don't shift focus if Ctrl+C or Ctrl+V
// When drop down is open, pressing escape shifts focus to clear button. So dont's shift focus if drop down is open. // is pressed. When drop down is open, pressing escape shifts focus to clear button. So dont's shift focus if drop down is open. Ctrl+Insert is
// Ctrl+Insert is equivalent to Ctrl+C and Shift+Insert is equivalent to Ctrl+V // equivalent to Ctrl+C and Shift+Insert is equivalent to Ctrl+V
if (currentIsDropDownOpen != s_IsDropDownOpen.end() && !currentIsDropDownOpen->second) if (currentIsDropDownOpen != s_IsDropDownOpen.end() && !currentIsDropDownOpen->second)
{ {
// Do not Light Up Buttons when Ctrl+C, Ctrl+V, Ctrl+Insert or Shift+Insert is pressed // Do not Light Up Buttons when Ctrl+C, Ctrl+V, Ctrl+Insert or Shift+Insert is pressed
@ -723,10 +696,8 @@ void KeyboardShortcutManager::Initialize()
auto coreWindow = Window::Current->CoreWindow; auto coreWindow = Window::Current->CoreWindow;
coreWindow->CharacterReceived += coreWindow->CharacterReceived +=
ref new TypedEventHandler<CoreWindow ^, CharacterReceivedEventArgs ^>(&KeyboardShortcutManager::OnCharacterReceivedHandler); ref new TypedEventHandler<CoreWindow ^, CharacterReceivedEventArgs ^>(&KeyboardShortcutManager::OnCharacterReceivedHandler);
coreWindow->KeyDown += coreWindow->KeyDown += ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(&KeyboardShortcutManager::OnKeyDownHandler);
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(&KeyboardShortcutManager::OnKeyDownHandler); coreWindow->KeyUp += ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(&KeyboardShortcutManager::OnKeyUpHandler);
coreWindow->KeyUp +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(&KeyboardShortcutManager::OnKeyUpHandler);
coreWindow->Dispatcher->AcceleratorKeyActivated += coreWindow->Dispatcher->AcceleratorKeyActivated +=
ref new TypedEventHandler<CoreDispatcher ^, AcceleratorKeyEventArgs ^>(&KeyboardShortcutManager::OnAcceleratorKeyActivated); ref new TypedEventHandler<CoreDispatcher ^, AcceleratorKeyEventArgs ^>(&KeyboardShortcutManager::OnAcceleratorKeyActivated);

View file

@ -10,10 +10,13 @@ namespace CalculatorApp
{ {
namespace Common namespace Common
{ {
public ref class KeyboardShortcutManager sealed public
ref class KeyboardShortcutManager sealed
{ {
public: public:
KeyboardShortcutManager() {} KeyboardShortcutManager()
{
}
DEPENDENCY_PROPERTY_OWNER(KeyboardShortcutManager); DEPENDENCY_PROPERTY_OWNER(KeyboardShortcutManager);
@ -28,7 +31,8 @@ namespace CalculatorApp
internal : internal :
static void Initialize(); static void
Initialize();
// Sometimes, like with popups, escape is treated as special and even // Sometimes, like with popups, escape is treated as special and even
// though it is handled we get it passed through to us. In those cases // though it is handled we get it passed through to us. In those cases
@ -48,45 +52,22 @@ namespace CalculatorApp
static void OnWindowClosed(int viewId); static void OnWindowClosed(int viewId);
private: private:
static void OnCharacterPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, Platform::String ^ oldValue, Platform::String ^ newValue);
static void OnCharacterPropertyChanged( static void OnVirtualKeyPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue);
Windows::UI::Xaml::DependencyObject^ target,
Platform::String^ oldValue,
Platform::String^ newValue);
static void OnVirtualKeyPropertyChanged( static void OnVirtualKeyControlChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue);
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue, static void OnVirtualKeyShiftChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue);
static void OnVirtualKeyInverseChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue);
static void OnVirtualKeyControlInverseChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue,
MyVirtualKey newValue); MyVirtualKey newValue);
static void OnVirtualKeyControlChordPropertyChanged( static void OnVirtualKeyAltChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue);
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue);
static void OnVirtualKeyShiftChordPropertyChanged( static void OnVirtualKeyControlShiftChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue,
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue);
static void OnVirtualKeyInverseChordPropertyChanged(
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue);
static void OnVirtualKeyControlInverseChordPropertyChanged(
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue);
static void OnVirtualKeyAltChordPropertyChanged(
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue);
static void OnVirtualKeyControlShiftChordPropertyChanged(
Windows::UI::Xaml::DependencyObject^ target,
MyVirtualKey oldValue,
MyVirtualKey newValue); MyVirtualKey newValue);
static void OnCharacterReceivedHandler(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args); static void OnCharacterReceivedHandler(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args);

View file

@ -42,7 +42,6 @@ static constexpr auto s_openParenResourceKey = L"48";
LocalizationService ^ LocalizationService::GetInstance() LocalizationService ^ LocalizationService::GetInstance()
{ {
if (s_singletonInstance == nullptr) if (s_singletonInstance == nullptr)
{ {
// Writer lock for the static maps // Writer lock for the static maps
@ -59,8 +58,8 @@ LocalizationService^ LocalizationService::GetInstance()
LocalizationService::LocalizationService() LocalizationService::LocalizationService()
{ {
m_language = ApplicationLanguages::Languages->GetAt(0); m_language = ApplicationLanguages::Languages->GetAt(0);
m_flowDirection = ResourceContext::GetForCurrentView()->QualifierValues->Lookup(L"LayoutDirection") m_flowDirection =
!= L"LTR" ? FlowDirection::RightToLeft : FlowDirection::LeftToRight; ResourceContext::GetForCurrentView()->QualifierValues->Lookup(L"LayoutDirection") != L"LTR" ? FlowDirection::RightToLeft : FlowDirection::LeftToRight;
auto resourceLoader = AppResourceProvider::GetInstance(); auto resourceLoader = AppResourceProvider::GetInstance();
m_fontFamilyOverride = resourceLoader.GetResourceString(L"LocalizedFontFamilyOverride"); m_fontFamilyOverride = resourceLoader.GetResourceString(L"LocalizedFontFamilyOverride");
@ -368,10 +367,8 @@ DateTimeFormatter^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatte
// If successful, returns a formatter that respects the user's regional format settings, // If successful, returns a formatter that respects the user's regional format settings,
// as configured by running intl.cpl. // as configured by running intl.cpl.
DateTimeFormatter^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter( DateTimeFormatter
_In_ String^ format, ^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(_In_ String ^ format, _In_ String ^ calendarIdentifier, _In_ String ^ clockIdentifier)
_In_ String^ calendarIdentifier,
_In_ String^ clockIdentifier)
{ {
IIterable<String ^> ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); IIterable<String ^> ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers();
if (languageIdentifiers == nullptr) if (languageIdentifiers == nullptr)
@ -379,19 +376,13 @@ DateTimeFormatter^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatte
languageIdentifiers = ApplicationLanguages::Languages; languageIdentifiers = ApplicationLanguages::Languages;
} }
return ref new DateTimeFormatter( return ref new DateTimeFormatter(format, languageIdentifiers, GlobalizationPreferences::HomeGeographicRegion, calendarIdentifier, clockIdentifier);
format,
languageIdentifiers,
GlobalizationPreferences::HomeGeographicRegion,
calendarIdentifier,
clockIdentifier);
} }
CurrencyFormatter ^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatter() CurrencyFormatter ^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatter()
{ {
String^ userCurrency = (GlobalizationPreferences::Currencies->Size > 0) String ^ userCurrency =
? GlobalizationPreferences::Currencies->GetAt(0) (GlobalizationPreferences::Currencies->Size > 0) ? GlobalizationPreferences::Currencies->GetAt(0) : StringReference(DefaultCurrencyCode.data());
: StringReference(DefaultCurrencyCode.data());
IIterable<String ^> ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); IIterable<String ^> ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers();
if (languageIdentifiers == nullptr) if (languageIdentifiers == nullptr)
@ -399,10 +390,7 @@ CurrencyFormatter^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatte
languageIdentifiers = ApplicationLanguages::Languages; languageIdentifiers = ApplicationLanguages::Languages;
} }
auto currencyFormatter = ref new CurrencyFormatter( auto currencyFormatter = ref new CurrencyFormatter(userCurrency, languageIdentifiers, GlobalizationPreferences::HomeGeographicRegion);
userCurrency,
languageIdentifiers,
GlobalizationPreferences::HomeGeographicRegion);
int fractionDigits = LocalizationSettings::GetInstance().GetCurrencyTrailingDigits(); int fractionDigits = LocalizationSettings::GetInstance().GetCurrencyTrailingDigits();
currencyFormatter->FractionDigits = fractionDigits; currencyFormatter->FractionDigits = fractionDigits;
@ -448,44 +436,29 @@ unordered_map<wstring, wstring> LocalizationService::GetTokenToReadableNameMap()
// standard project resources. // standard project resources.
static vector<pair<wstring, wstring>> s_parenEngineKeyResourceMap = { static vector<pair<wstring, wstring>> s_parenEngineKeyResourceMap = {
// Sine permutations // Sine permutations
make_pair<wstring, wstring>(L"67", L"SineDegrees"), make_pair<wstring, wstring>(L"67", L"SineDegrees"), make_pair<wstring, wstring>(L"73", L"SineRadians"),
make_pair<wstring, wstring>(L"73", L"SineRadians"), make_pair<wstring, wstring>(L"79", L"SineGradians"), make_pair<wstring, wstring>(L"70", L"InverseSineDegrees"),
make_pair<wstring, wstring>(L"79", L"SineGradians"), make_pair<wstring, wstring>(L"76", L"InverseSineRadians"), make_pair<wstring, wstring>(L"82", L"InverseSineGradians"),
make_pair<wstring, wstring>(L"70", L"InverseSineDegrees"), make_pair<wstring, wstring>(L"25", L"HyperbolicSine"), make_pair<wstring, wstring>(L"85", L"InverseHyperbolicSine"),
make_pair<wstring, wstring>(L"76", L"InverseSineRadians"),
make_pair<wstring, wstring>(L"82", L"InverseSineGradians"),
make_pair<wstring, wstring>(L"25", L"HyperbolicSine"),
make_pair<wstring, wstring>(L"85", L"InverseHyperbolicSine"),
// Cosine permutations // Cosine permutations
make_pair<wstring, wstring>(L"68", L"CosineDegrees"), make_pair<wstring, wstring>(L"68", L"CosineDegrees"), make_pair<wstring, wstring>(L"74", L"CosineRadians"),
make_pair<wstring, wstring>(L"74", L"CosineRadians"), make_pair<wstring, wstring>(L"80", L"CosineGradians"), make_pair<wstring, wstring>(L"71", L"InverseCosineDegrees"),
make_pair<wstring, wstring>(L"80", L"CosineGradians"), make_pair<wstring, wstring>(L"77", L"InverseCosineRadians"), make_pair<wstring, wstring>(L"83", L"InverseCosineGradians"),
make_pair<wstring, wstring>(L"71", L"InverseCosineDegrees"), make_pair<wstring, wstring>(L"26", L"HyperbolicCosine"), make_pair<wstring, wstring>(L"86", L"InverseHyperbolicCosine"),
make_pair<wstring, wstring>(L"77", L"InverseCosineRadians"),
make_pair<wstring, wstring>(L"83", L"InverseCosineGradians"),
make_pair<wstring, wstring>(L"26", L"HyperbolicCosine"),
make_pair<wstring, wstring>(L"86", L"InverseHyperbolicCosine"),
// Tangent permutations // Tangent permutations
make_pair<wstring, wstring>(L"69", L"TangentDegrees"), make_pair<wstring, wstring>(L"69", L"TangentDegrees"), make_pair<wstring, wstring>(L"75", L"TangentRadians"),
make_pair<wstring, wstring>(L"75", L"TangentRadians"), make_pair<wstring, wstring>(L"81", L"TangentGradians"), make_pair<wstring, wstring>(L"72", L"InverseTangentDegrees"),
make_pair<wstring, wstring>(L"81", L"TangentGradians"), make_pair<wstring, wstring>(L"78", L"InverseTangentRadians"), make_pair<wstring, wstring>(L"84", L"InverseTangentGradians"),
make_pair<wstring, wstring>(L"72", L"InverseTangentDegrees"), make_pair<wstring, wstring>(L"27", L"HyperbolicTangent"), make_pair<wstring, wstring>(L"87", L"InverseHyperbolicTangent"),
make_pair<wstring, wstring>(L"78", L"InverseTangentRadians"),
make_pair<wstring, wstring>(L"84", L"InverseTangentGradians"),
make_pair<wstring, wstring>(L"27", L"HyperbolicTangent"),
make_pair<wstring, wstring>(L"87", L"InverseHyperbolicTangent"),
// Miscellaneous Scientific functions // Miscellaneous Scientific functions
make_pair<wstring, wstring>(L"94", L"Factorial"), make_pair<wstring, wstring>(L"94", L"Factorial"), make_pair<wstring, wstring>(L"35", L"DegreeMinuteSecond"),
make_pair<wstring, wstring>(L"35", L"DegreeMinuteSecond"), make_pair<wstring, wstring>(L"28", L"NaturalLog"), make_pair<wstring, wstring>(L"91", L"Square")
make_pair<wstring, wstring>(L"28", L"NaturalLog"),
make_pair<wstring, wstring>(L"91", L"Square")
}; };
static vector<pair<wstring, wstring>> s_noParenEngineKeyResourceMap = { static vector<pair<wstring, wstring>> s_noParenEngineKeyResourceMap = { // Programmer mode functions
// Programmer mode functions
make_pair<wstring, wstring>(L"9", L"LeftShift"), make_pair<wstring, wstring>(L"9", L"LeftShift"),
make_pair<wstring, wstring>(L"10", L"RightShift"), make_pair<wstring, wstring>(L"10", L"RightShift"),

View file

@ -5,30 +5,32 @@
#include "Utils.h" #include "Utils.h"
namespace CalculatorApp { namespace Common namespace CalculatorApp
{
namespace Common
{ {
namespace LocalizationServiceProperties namespace LocalizationServiceProperties
{ {
static constexpr std::wstring_view DefaultCurrencyCode{ L"USD" }; static constexpr std::wstring_view DefaultCurrencyCode{ L"USD" };
} }
public enum class LanguageFontType public
enum class LanguageFontType
{ {
UIText, UIText,
UICaption, UICaption,
}; };
public ref class LocalizationService sealed public
ref class LocalizationService sealed
{ {
public: public:
DEPENDENCY_PROPERTY_OWNER(LocalizationService); DEPENDENCY_PROPERTY_OWNER(LocalizationService);
DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT_AND_CALLBACK(LanguageFontType, FontType, LanguageFontType::UIText); DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT_AND_CALLBACK(LanguageFontType, FontType, LanguageFontType::UIText);
DEPENDENCY_PROPERTY_ATTACHED_WITH_CALLBACK(double, FontSize); DEPENDENCY_PROPERTY_ATTACHED_WITH_CALLBACK(double, FontSize);
internal: internal : static LocalizationService ^ GetInstance();
static LocalizationService^ GetInstance();
Windows::UI::Xaml::FlowDirection GetFlowDirection(); Windows::UI::Xaml::FlowDirection GetFlowDirection();
bool IsRtlLayout(); bool IsRtlLayout();
@ -41,9 +43,8 @@ namespace CalculatorApp { namespace Common
static Windows::Globalization::NumberFormatting::DecimalFormatter ^ GetRegionalSettingsAwareDecimalFormatter(); static Windows::Globalization::NumberFormatting::DecimalFormatter ^ GetRegionalSettingsAwareDecimalFormatter();
static Windows::Globalization::DateTimeFormatting::DateTimeFormatter ^ GetRegionalSettingsAwareDateTimeFormatter(_In_ Platform::String ^ format); static Windows::Globalization::DateTimeFormatting::DateTimeFormatter ^ GetRegionalSettingsAwareDateTimeFormatter(_In_ Platform::String ^ format);
static Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ GetRegionalSettingsAwareDateTimeFormatter( static Windows::Globalization::DateTimeFormatting::DateTimeFormatter
_In_ Platform::String^ format, ^ GetRegionalSettingsAwareDateTimeFormatter(_In_ Platform::String ^ format, _In_ Platform::String ^ calendarIdentifier,
_In_ Platform::String^ calendarIdentifier,
_In_ Platform::String ^ clockIdentifier); _In_ Platform::String ^ clockIdentifier);
static Windows::Globalization::NumberFormatting::CurrencyFormatter ^ GetRegionalSettingsAwareCurrencyFormatter(); static Windows::Globalization::NumberFormatting::CurrencyFormatter ^ GetRegionalSettingsAwareCurrencyFormatter();
@ -59,7 +60,8 @@ namespace CalculatorApp { namespace Common
// Attached property callbacks // Attached property callbacks
static void OnFontTypePropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, LanguageFontType oldValue, LanguageFontType newValue); static void OnFontTypePropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, LanguageFontType oldValue, LanguageFontType newValue);
static void OnFontWeightPropertyChanged(Windows::UI::Xaml::DependencyObject^ target, Windows::UI::Text::FontWeight oldValue, Windows::UI::Text::FontWeight newValue); static void OnFontWeightPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, Windows::UI::Text::FontWeight oldValue,
Windows::UI::Text::FontWeight newValue);
static void OnFontSizePropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, double oldValue, double newValue); static void OnFontSizePropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, double oldValue, double newValue);
static void UpdateFontFamilyAndSize(Windows::UI::Xaml::DependencyObject ^ target); static void UpdateFontFamilyAndSize(Windows::UI::Xaml::DependencyObject ^ target);
@ -81,5 +83,5 @@ namespace CalculatorApp { namespace Common
double m_uiCaptionFontScaleFactorOverride; double m_uiCaptionFontScaleFactorOverride;
}; };
}} }
}

View file

@ -29,9 +29,7 @@ namespace CalculatorApp
} }
wchar_t resolvedName[LOCALE_NAME_MAX_LENGTH]; wchar_t resolvedName[LOCALE_NAME_MAX_LENGTH];
result = ResolveLocaleName(formatter->ResolvedLanguage->Data(), result = ResolveLocaleName(formatter->ResolvedLanguage->Data(), resolvedName, LOCALE_NAME_MAX_LENGTH);
resolvedName,
LOCALE_NAME_MAX_LENGTH);
if (result == 0) if (result == 0)
{ {
throw std::runtime_error("Unexpected error resolving locale name"); throw std::runtime_error("Unexpected error resolving locale name");
@ -40,30 +38,21 @@ namespace CalculatorApp
{ {
m_resolvedName = resolvedName; m_resolvedName = resolvedName;
wchar_t decimalString[LocaleSettingBufferSize] = L""; wchar_t decimalString[LocaleSettingBufferSize] = L"";
result = GetLocaleInfoEx(m_resolvedName.c_str(), result = GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_SDECIMAL, decimalString, static_cast<int>(std::size(decimalString)));
LOCALE_SDECIMAL,
decimalString,
static_cast<int>(std::size(decimalString)));
if (result == 0) if (result == 0)
{ {
throw std::runtime_error("Unexpected error while getting locale info"); throw std::runtime_error("Unexpected error while getting locale info");
} }
wchar_t groupingSymbolString[LocaleSettingBufferSize] = L""; wchar_t groupingSymbolString[LocaleSettingBufferSize] = L"";
result = GetLocaleInfoEx(m_resolvedName.c_str(), result = GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_STHOUSAND, groupingSymbolString, static_cast<int>(std::size(groupingSymbolString)));
LOCALE_STHOUSAND,
groupingSymbolString,
static_cast<int>(std::size(groupingSymbolString)));
if (result == 0) if (result == 0)
{ {
throw std::runtime_error("Unexpected error while getting locale info"); throw std::runtime_error("Unexpected error while getting locale info");
} }
wchar_t numberGroupingString[LocaleSettingBufferSize] = L""; wchar_t numberGroupingString[LocaleSettingBufferSize] = L"";
result = GetLocaleInfoEx(m_resolvedName.c_str(), result = GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_SGROUPING, numberGroupingString, static_cast<int>(std::size(numberGroupingString)));
LOCALE_SGROUPING,
numberGroupingString,
static_cast<int>(std::size(numberGroupingString)));
if (result == 0) if (result == 0)
{ {
throw std::runtime_error("Unexpected error while getting locale info"); throw std::runtime_error("Unexpected error while getting locale info");
@ -71,9 +60,7 @@ namespace CalculatorApp
// Get locale info for List Separator, eg. comma is used in many locales // Get locale info for List Separator, eg. comma is used in many locales
wchar_t listSeparatorString[4] = L""; wchar_t listSeparatorString[4] = L"";
result = ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, result = ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SLIST, listSeparatorString,
LOCALE_SLIST,
listSeparatorString,
static_cast<int>(std::size(listSeparatorString))); // Max length of the expected return value is 4 static_cast<int>(std::size(listSeparatorString))); // Max length of the expected return value is 4
if (result == 0) if (result == 0)
{ {
@ -81,9 +68,7 @@ namespace CalculatorApp
} }
int currencyTrailingDigits = 0; int currencyTrailingDigits = 0;
result = GetLocaleInfoEx(m_resolvedName.c_str(), result = GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER, (LPWSTR)&currencyTrailingDigits,
LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER,
(LPWSTR)&currencyTrailingDigits,
sizeof(currencyTrailingDigits) / sizeof(WCHAR)); sizeof(currencyTrailingDigits) / sizeof(WCHAR));
if (result == 0) if (result == 0)
{ {
@ -93,9 +78,7 @@ namespace CalculatorApp
// Currency symbol precedence is either 0 or 1. // Currency symbol precedence is either 0 or 1.
// A value of 0 indicates the symbol follows the currency value. // A value of 0 indicates the symbol follows the currency value.
int currencySymbolPrecedence = 1; int currencySymbolPrecedence = 1;
result = GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, result = GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_IPOSSYMPRECEDES | LOCALE_RETURN_NUMBER, (LPWSTR)&currencySymbolPrecedence,
LOCALE_IPOSSYMPRECEDES | LOCALE_RETURN_NUMBER,
(LPWSTR)&currencySymbolPrecedence,
sizeof(currencySymbolPrecedence) / sizeof(WCHAR)); sizeof(currencySymbolPrecedence) / sizeof(WCHAR));
// As CalcEngine only supports the first character of the decimal separator, // As CalcEngine only supports the first character of the decimal separator,
@ -112,10 +95,7 @@ namespace CalculatorApp
// Note: This function returns 0 on failure. // Note: This function returns 0 on failure.
// We'll ignore the failure in that case and the CalendarIdentifier would get set to GregorianCalendar. // We'll ignore the failure in that case and the CalendarIdentifier would get set to GregorianCalendar.
CALID calId; CALID calId;
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_ICALENDARTYPE | LOCALE_RETURN_NUMBER, reinterpret_cast<PWSTR>(&calId), sizeof(calId));
LOCALE_ICALENDARTYPE | LOCALE_RETURN_NUMBER,
reinterpret_cast<PWSTR>(&calId),
sizeof(calId));
m_calendarIdentifier = GetCalendarIdentifierFromCalid(calId); m_calendarIdentifier = GetCalendarIdentifierFromCalid(calId);

View file

@ -19,13 +19,7 @@ namespace CalculatorApp
std::unique_ptr<wchar_t[]> spBuffer = std::unique_ptr<wchar_t[]>(new wchar_t[length]); std::unique_ptr<wchar_t[]> spBuffer = std::unique_ptr<wchar_t[]>(new wchar_t[length]);
va_list args = NULL; va_list args = NULL;
va_start(args, pMessage); va_start(args, pMessage);
DWORD fmtReturnVal = FormatMessage(FORMAT_MESSAGE_FROM_STRING, DWORD fmtReturnVal = FormatMessage(FORMAT_MESSAGE_FROM_STRING, pMessage, 0, 0, spBuffer.get(), length, &args);
pMessage,
0,
0,
spBuffer.get(),
length,
&args);
va_end(args); va_end(args);
if (fmtReturnVal != 0) if (fmtReturnVal != 0)

View file

@ -7,7 +7,8 @@ namespace CalculatorApp
{ {
namespace Common namespace Common
{ {
public enum class MyVirtualKey public
enum class MyVirtualKey
{ {
None = 0, None = 0,
LeftButton = 1, LeftButton = 1,

View file

@ -50,37 +50,49 @@ static constexpr int CURRENCY_ID = 16;
// The order of items in this list determines the order of items in the menu. // The order of items in this list determines the order of items in the menu.
static constexpr array<const NavCategoryInitializer, 17> s_categoryManifest = { static constexpr array<const NavCategoryInitializer, 17> s_categoryManifest = {
NavCategoryInitializer { ViewMode::Standard, STANDARD_ID, L"Standard", L"StandardMode", L"\uE8EF", CategoryGroupType::Calculator, MyVirtualKey::Number1, SUPPORTS_ALL }, NavCategoryInitializer{ ViewMode::Standard, STANDARD_ID, L"Standard", L"StandardMode", L"\uE8EF", CategoryGroupType::Calculator, MyVirtualKey::Number1,
NavCategoryInitializer { ViewMode::Scientific, SCIENTIFIC_ID, L"Scientific", L"ScientificMode", L"\uF196", CategoryGroupType::Calculator, MyVirtualKey::Number2, SUPPORTS_ALL }, SUPPORTS_ALL },
NavCategoryInitializer { ViewMode::Programmer, PROGRAMMER_ID, L"Programmer", L"ProgrammerMode", L"\uECCE", CategoryGroupType::Calculator, MyVirtualKey::Number3, SUPPORTS_ALL }, NavCategoryInitializer{ ViewMode::Scientific, SCIENTIFIC_ID, L"Scientific", L"ScientificMode", L"\uF196", CategoryGroupType::Calculator,
NavCategoryInitializer { ViewMode::Date, DATE_ID, L"Date", L"DateCalculationMode", L"\uE787", CategoryGroupType::Calculator, MyVirtualKey::Number4, SUPPORTS_ALL }, MyVirtualKey::Number2, SUPPORTS_ALL },
NavCategoryInitializer { ViewMode::Currency, CURRENCY_ID, L"Currency", L"CategoryName_Currency", L"\uEB0D", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, NavCategoryInitializer{ ViewMode::Programmer, PROGRAMMER_ID, L"Programmer", L"ProgrammerMode", L"\uECCE", CategoryGroupType::Calculator,
NavCategoryInitializer { ViewMode::Volume, VOLUME_ID, L"Volume", L"CategoryName_Volume", L"\uF1AA", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, MyVirtualKey::Number3, SUPPORTS_ALL },
NavCategoryInitializer { ViewMode::Length, LENGTH_ID, L"Length", L"CategoryName_Length", L"\uECC6", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, NavCategoryInitializer{ ViewMode::Date, DATE_ID, L"Date", L"DateCalculationMode", L"\uE787", CategoryGroupType::Calculator, MyVirtualKey::Number4,
NavCategoryInitializer { ViewMode::Weight, WEIGHT_ID, L"Weight and Mass", L"CategoryName_Weight", L"\uF4C1", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, SUPPORTS_ALL },
NavCategoryInitializer { ViewMode::Temperature, TEMPERATURE_ID, L"Temperature", L"CategoryName_Temperature", L"\uE7A3", CategoryGroupType::Converter, MyVirtualKey::None, SUPPORTS_NEGATIVE }, NavCategoryInitializer{ ViewMode::Currency, CURRENCY_ID, L"Currency", L"CategoryName_Currency", L"\uEB0D", CategoryGroupType::Converter, MyVirtualKey::None,
NavCategoryInitializer { ViewMode::Energy, ENERGY_ID, L"Energy", L"CategoryName_Energy", L"\uECAD", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, POSITIVE_ONLY },
NavCategoryInitializer { ViewMode::Area, AREA_ID, L"Area", L"CategoryName_Area", L"\uE809", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, NavCategoryInitializer{ ViewMode::Volume, VOLUME_ID, L"Volume", L"CategoryName_Volume", L"\uF1AA", CategoryGroupType::Converter, MyVirtualKey::None,
NavCategoryInitializer { ViewMode::Speed, SPEED_ID, L"Speed", L"CategoryName_Speed", L"\uEADA", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, POSITIVE_ONLY },
NavCategoryInitializer { ViewMode::Time, TIME_ID, L"Time", L"CategoryName_Time", L"\uE917", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, NavCategoryInitializer{ ViewMode::Length, LENGTH_ID, L"Length", L"CategoryName_Length", L"\uECC6", CategoryGroupType::Converter, MyVirtualKey::None,
NavCategoryInitializer { ViewMode::Power, POWER_ID, L"Power", L"CategoryName_Power", L"\uE945", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, POSITIVE_ONLY },
NavCategoryInitializer { ViewMode::Data, DATA_ID, L"Data", L"CategoryName_Data", L"\uF20F", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, NavCategoryInitializer{ ViewMode::Weight, WEIGHT_ID, L"Weight and Mass", L"CategoryName_Weight", L"\uF4C1", CategoryGroupType::Converter,
NavCategoryInitializer { ViewMode::Pressure, PRESSURE_ID, L"Pressure", L"CategoryName_Pressure", L"\uEC4A", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY }, MyVirtualKey::None, POSITIVE_ONLY },
NavCategoryInitializer { ViewMode::Angle, ANGLE_ID, L"Angle", L"CategoryName_Angle", L"\uF515", CategoryGroupType::Converter, MyVirtualKey::None, POSITIVE_ONLY } NavCategoryInitializer{ ViewMode::Temperature, TEMPERATURE_ID, L"Temperature", L"CategoryName_Temperature", L"\uE7A3", CategoryGroupType::Converter,
MyVirtualKey::None, SUPPORTS_NEGATIVE },
NavCategoryInitializer{ ViewMode::Energy, ENERGY_ID, L"Energy", L"CategoryName_Energy", L"\uECAD", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Area, AREA_ID, L"Area", L"CategoryName_Area", L"\uE809", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Speed, SPEED_ID, L"Speed", L"CategoryName_Speed", L"\uEADA", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Time, TIME_ID, L"Time", L"CategoryName_Time", L"\uE917", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Power, POWER_ID, L"Power", L"CategoryName_Power", L"\uE945", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Data, DATA_ID, L"Data", L"CategoryName_Data", L"\uF20F", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Pressure, PRESSURE_ID, L"Pressure", L"CategoryName_Pressure", L"\uEC4A", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY },
NavCategoryInitializer{ ViewMode::Angle, ANGLE_ID, L"Angle", L"CategoryName_Angle", L"\uF515", CategoryGroupType::Converter, MyVirtualKey::None,
POSITIVE_ONLY }
}; };
// This function should only be used when storing the mode to app data. // This function should only be used when storing the mode to app data.
int NavCategory::Serialize(ViewMode mode) int NavCategory::Serialize(ViewMode mode)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter =
[mode](const NavCategoryInitializer& initializer) find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode; });
{
return initializer.viewMode == mode;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? iter->serializationId : -1;
? iter->serializationId
: -1;
} }
// This function should only be used when restoring the mode from app data. // This function should only be used when restoring the mode from app data.
@ -94,10 +106,7 @@ ViewMode NavCategory::Deserialize(Platform::Object^ obj)
{ {
int serializationId = boxed->Value; int serializationId = boxed->Value;
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest),
[serializationId](const NavCategoryInitializer& initializer) [serializationId](const NavCategoryInitializer& initializer) { return initializer.serializationId == serializationId; });
{
return initializer.serializationId == serializationId;
});
if (iter != s_categoryManifest.end()) if (iter != s_categoryManifest.end())
{ {
@ -110,11 +119,8 @@ ViewMode NavCategory::Deserialize(Platform::Object^ obj)
bool NavCategory::IsValidViewMode(ViewMode mode) bool NavCategory::IsValidViewMode(ViewMode mode)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter =
[mode](const NavCategoryInitializer& initializer) find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode; });
{
return initializer.viewMode == mode;
});
return iter != s_categoryManifest.end(); return iter != s_categoryManifest.end();
} }
@ -139,64 +145,41 @@ bool NavCategory::IsConverterViewMode(ViewMode mode)
bool NavCategory::IsModeInCategoryGroup(ViewMode mode, CategoryGroupType type) bool NavCategory::IsModeInCategoryGroup(ViewMode mode, CategoryGroupType type)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest),
[mode, type](const NavCategoryInitializer& initializer) [mode, type](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode && initializer.groupType == type; });
{
return initializer.viewMode == mode && initializer.groupType == type;
});
return iter != s_categoryManifest.end(); return iter != s_categoryManifest.end();
} }
String ^ NavCategory::GetFriendlyName(ViewMode mode) String ^ NavCategory::GetFriendlyName(ViewMode mode)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter =
[mode](const NavCategoryInitializer& initializer) find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode; });
{
return initializer.viewMode == mode;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? StringReference(iter->friendlyName) : L"None";
? StringReference(iter->friendlyName)
: L"None";
} }
ViewMode NavCategory::GetViewModeForFriendlyName(String ^ name) ViewMode NavCategory::GetViewModeForFriendlyName(String ^ name)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest),
[name](const NavCategoryInitializer& initializer) [name](const NavCategoryInitializer& initializer) { return wcscmp(initializer.friendlyName, name->Data()) == 0; });
{
return wcscmp(initializer.friendlyName, name->Data()) == 0;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? iter->viewMode : ViewMode::None;
? iter->viewMode
: ViewMode::None;
} }
String ^ NavCategory::GetNameResourceKey(ViewMode mode) String ^ NavCategory::GetNameResourceKey(ViewMode mode)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter =
[mode](const NavCategoryInitializer& initializer) find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode; });
{
return initializer.viewMode == mode;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? StringReference(iter->nameResourceKey) + "Text" : nullptr;
? StringReference(iter->nameResourceKey) + "Text"
: nullptr;
} }
CategoryGroupType NavCategory::GetGroupType(ViewMode mode) CategoryGroupType NavCategory::GetGroupType(ViewMode mode)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter =
[mode](const NavCategoryInitializer& initializer) find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode; });
{
return initializer.viewMode == mode;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? iter->groupType : CategoryGroupType::None;
? iter->groupType
: CategoryGroupType::None;
} }
// GetIndex is 0-based, GetPosition is 1-based // GetIndex is 0-based, GetPosition is 1-based
@ -210,9 +193,7 @@ int NavCategory::GetFlatIndex(ViewMode mode)
{ {
int index = -1; int index = -1;
CategoryGroupType type = CategoryGroupType::None; CategoryGroupType type = CategoryGroupType::None;
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode, &type, &index](const NavCategoryInitializer& initializer) {
[mode, &type, &index](const NavCategoryInitializer& initializer)
{
index++; index++;
if (initializer.groupType != type) if (initializer.groupType != type)
{ {
@ -223,18 +204,14 @@ int NavCategory::GetFlatIndex(ViewMode mode)
return initializer.viewMode == mode; return initializer.viewMode == mode;
}); });
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? index : -1;
? index
: -1;
} }
// GetIndex is 0-based, GetPosition is 1-based // GetIndex is 0-based, GetPosition is 1-based
int NavCategory::GetIndexInGroup(ViewMode mode, CategoryGroupType type) int NavCategory::GetIndexInGroup(ViewMode mode, CategoryGroupType type)
{ {
int index = -1; int index = -1;
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode, type, &index](const NavCategoryInitializer& initializer) {
[mode, type, &index](const NavCategoryInitializer& initializer)
{
if (initializer.groupType == type) if (initializer.groupType == type)
{ {
index++; index++;
@ -244,38 +221,27 @@ int NavCategory::GetIndexInGroup(ViewMode mode, CategoryGroupType type)
return false; return false;
}); });
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? index : -1;
? index
: -1;
} }
// GetIndex is 0-based, GetPosition is 1-based // GetIndex is 0-based, GetPosition is 1-based
int NavCategory::GetPosition(ViewMode mode) int NavCategory::GetPosition(ViewMode mode)
{ {
int position = 0; int position = 0;
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode, &position](const NavCategoryInitializer& initializer) {
[mode, &position](const NavCategoryInitializer& initializer)
{
position++; position++;
return initializer.viewMode == mode; return initializer.viewMode == mode;
}); });
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? position : -1;
? position
: -1;
} }
ViewMode NavCategory::GetViewModeForVirtualKey(MyVirtualKey virtualKey) ViewMode NavCategory::GetViewModeForVirtualKey(MyVirtualKey virtualKey)
{ {
auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest),
[virtualKey](const NavCategoryInitializer& initializer) [virtualKey](const NavCategoryInitializer& initializer) { return initializer.virtualKey == virtualKey; });
{
return initializer.virtualKey == virtualKey;
});
return (iter != s_categoryManifest.end()) return (iter != s_categoryManifest.end()) ? iter->viewMode : ViewMode::None;
? iter->viewMode
: ViewMode::None;
} }
vector<MyVirtualKey> NavCategory::GetCategoryAcceleratorKeys() vector<MyVirtualKey> NavCategory::GetCategoryAcceleratorKeys()
@ -292,8 +258,7 @@ vector<MyVirtualKey> NavCategory::GetCategoryAcceleratorKeys()
return accelerators; return accelerators;
} }
NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupInitializer) : NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupInitializer) : m_Categories(ref new Vector<NavCategory ^>())
m_Categories(ref new Vector<NavCategory^>())
{ {
m_GroupType = groupInitializer.type; m_GroupType = groupInitializer.type;
@ -306,9 +271,8 @@ NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupIniti
String ^ automationName = resProvider.GetResourceString(automationResourceKey); String ^ automationName = resProvider.GetResourceString(automationResourceKey);
String ^ navCategoryHeaderAutomationNameFormat = resProvider.GetResourceString(L"NavCategoryHeader_AutomationNameFormat"); String ^ navCategoryHeaderAutomationNameFormat = resProvider.GetResourceString(L"NavCategoryHeader_AutomationNameFormat");
m_AutomationName = ref new String(LocalizationStringUtil::GetLocalizedString( m_AutomationName =
navCategoryHeaderAutomationNameFormat->Data(), ref new String(LocalizationStringUtil::GetLocalizedString(navCategoryHeaderAutomationNameFormat->Data(), automationName->Data()).c_str());
automationName->Data()).c_str());
String ^ navCategoryItemAutomationNameFormat = resProvider.GetResourceString(L"NavCategoryItem_AutomationNameFormat"); String ^ navCategoryItemAutomationNameFormat = resProvider.GetResourceString(L"NavCategoryItem_AutomationNameFormat");
@ -318,18 +282,11 @@ NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupIniti
{ {
String ^ nameResourceKey = StringReference(categoryInitializer.nameResourceKey); String ^ nameResourceKey = StringReference(categoryInitializer.nameResourceKey);
String ^ categoryName = resProvider.GetResourceString(nameResourceKey + "Text"); String ^ categoryName = resProvider.GetResourceString(nameResourceKey + "Text");
String^ categoryAutomationName = ref new String(LocalizationStringUtil::GetLocalizedString( String ^ categoryAutomationName = ref new String(
navCategoryItemAutomationNameFormat->Data(), LocalizationStringUtil::GetLocalizedString(navCategoryItemAutomationNameFormat->Data(), categoryName->Data(), m_Name->Data()).c_str());
categoryName->Data(),
m_Name->Data()).c_str());
m_Categories->Append(ref new NavCategory( m_Categories->Append(ref new NavCategory(categoryName, categoryAutomationName, StringReference(categoryInitializer.glyph),
categoryName, resProvider.GetResourceString(nameResourceKey + "AccessKey"), groupMode, categoryInitializer.viewMode,
categoryAutomationName,
StringReference(categoryInitializer.glyph),
resProvider.GetResourceString(nameResourceKey + "AccessKey"),
groupMode,
categoryInitializer.viewMode,
categoryInitializer.supportsNegative)); categoryInitializer.supportsNegative));
} }
} }
@ -357,10 +314,7 @@ vector<NavCategoryInitializer> NavCategoryGroup::GetInitializerCategoryGroup(Cat
{ {
vector<NavCategoryInitializer> initializers{}; vector<NavCategoryInitializer> initializers{};
copy_if(begin(s_categoryManifest), end(s_categoryManifest), back_inserter(initializers), copy_if(begin(s_categoryManifest), end(s_categoryManifest), back_inserter(initializers),
[groupType](const NavCategoryInitializer& initializer) [groupType](const NavCategoryInitializer& initializer) { return initializer.groupType == groupType; });
{
return initializer.groupType == groupType;
});
return initializers; return initializers;
} }
@ -368,12 +322,7 @@ vector<NavCategoryInitializer> NavCategoryGroup::GetInitializerCategoryGroup(Cat
String ^ NavCategoryGroup::GetHeaderResourceKey(CategoryGroupType type) String ^ NavCategoryGroup::GetHeaderResourceKey(CategoryGroupType type)
{ {
auto iter = find_if(begin(s_categoryGroupManifest), end(s_categoryGroupManifest), auto iter = find_if(begin(s_categoryGroupManifest), end(s_categoryGroupManifest),
[type](const NavCategoryGroupInitializer& initializer) [type](const NavCategoryGroupInitializer& initializer) { return initializer.type == type; });
{
return initializer.type == type;
});
return (iter != s_categoryGroupManifest.end()) return (iter != s_categoryGroupManifest.end()) ? StringReference(iter->headerResourceKey) : nullptr;
? StringReference(iter->headerResourceKey)
: nullptr;
} }

View file

@ -24,7 +24,8 @@ namespace CalculatorApp
// Don't change the order of these enums // Don't change the order of these enums
// and definitely don't use int arithmetic // and definitely don't use int arithmetic
// to change modes. // to change modes.
public enum class ViewMode public
enum class ViewMode
{ {
None = -1, None = -1,
Standard = 0, Standard = 0,
@ -46,34 +47,29 @@ namespace CalculatorApp
Currency = 16 Currency = 16
}; };
public enum class CategoryGroupType public
enum class CategoryGroupType
{ {
None = -1, None = -1,
Calculator = 0, Calculator = 0,
Converter = 1 Converter = 1
}; };
private struct NavCategoryInitializer private
struct NavCategoryInitializer
{ {
constexpr NavCategoryInitializer( constexpr NavCategoryInitializer(ViewMode mode, int id, wchar_t const* name, wchar_t const* nameKey, wchar_t const* glyph, CategoryGroupType group,
ViewMode mode, MyVirtualKey vKey, bool categorySupportsNegative)
int id, : viewMode(mode)
wchar_t const * name, , serializationId(id)
wchar_t const * nameKey, , friendlyName(name)
wchar_t const * glyph, , nameResourceKey(nameKey)
CategoryGroupType group, , glyph(glyph)
MyVirtualKey vKey, , groupType(group)
bool categorySupportsNegative) , virtualKey(vKey)
: , supportsNegative(categorySupportsNegative)
viewMode(mode), {
serializationId(id), }
friendlyName(name),
nameResourceKey(nameKey),
glyph(glyph),
groupType(group),
virtualKey(vKey),
supportsNegative(categorySupportsNegative)
{}
const ViewMode viewMode; const ViewMode viewMode;
const int serializationId; const int serializationId;
@ -85,11 +81,13 @@ namespace CalculatorApp
const bool supportsNegative; const bool supportsNegative;
}; };
private struct NavCategoryGroupInitializer private
struct NavCategoryGroupInitializer
{ {
constexpr NavCategoryGroupInitializer(CategoryGroupType t, wchar_t const * h, wchar_t const * n, wchar_t const * a) : constexpr NavCategoryGroupInitializer(CategoryGroupType t, wchar_t const* h, wchar_t const* n, wchar_t const* a)
type(t), headerResourceKey(h), modeResourceKey(n), automationResourceKey(a) : type(t), headerResourceKey(h), modeResourceKey(n), automationResourceKey(a)
{} {
}
const CategoryGroupType type; const CategoryGroupType type;
const wchar_t* headerResourceKey; const wchar_t* headerResourceKey;
@ -97,30 +95,26 @@ namespace CalculatorApp
const wchar_t* automationResourceKey; const wchar_t* automationResourceKey;
}; };
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class NavCategory sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class NavCategory sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
public: public:
OBSERVABLE_OBJECT(); OBSERVABLE_OBJECT();
property Platform::String^ Name property Platform::String
{ ^ Name { Platform::String ^ get() { return m_name; } }
Platform::String^ get() { return m_name; }
}
property Platform::String^ AutomationName property Platform::String
{ ^ AutomationName { Platform::String ^ get() { return m_automationName; } }
Platform::String^ get() { return m_automationName; }
}
property Platform::String^ Glyph property Platform::String
{ ^ Glyph { Platform::String ^ get() { return m_glyph; } }
Platform::String^ get() { return m_glyph; }
}
property int Position property int Position
{ {
int get() { return m_position; } int get()
{
return m_position;
}
} }
property ViewMode Mode property ViewMode Mode
@ -131,22 +125,11 @@ namespace CalculatorApp
} }
} }
property Platform::String^ AutomationId property Platform::String
{ ^ AutomationId { Platform::String ^ get() { return m_viewMode.ToString(); } }
Platform::String^ get()
{
return m_viewMode.ToString();
}
}
property Platform::String^ AccessKey
{
Platform::String^ get()
{
return m_accessKey;
}
}
property Platform::String
^ AccessKey { Platform::String ^ get() { return m_accessKey; } }
property bool SupportsNegative property bool SupportsNegative
{ {
@ -178,15 +161,15 @@ namespace CalculatorApp
static ViewMode GetViewModeForVirtualKey(MyVirtualKey virtualKey); static ViewMode GetViewModeForVirtualKey(MyVirtualKey virtualKey);
internal: internal : NavCategory(Platform::String ^ name, Platform::String ^ automationName, Platform::String ^ glyph, Platform::String ^ accessKey,
NavCategory(Platform::String^ name, Platform::String^ automationName, Platform::String^ glyph, Platform::String^ accessKey, Platform::String^ mode, ViewMode viewMode, bool supportsNegative) : Platform::String ^ mode, ViewMode viewMode, bool supportsNegative)
m_name(name), : m_name(name)
m_automationName(automationName), , m_automationName(automationName)
m_glyph(glyph), , m_glyph(glyph)
m_accessKey(accessKey), , m_accessKey(accessKey)
m_mode(mode), , m_mode(mode)
m_viewMode(viewMode), , m_viewMode(viewMode)
m_supportsNegative(supportsNegative) , m_supportsNegative(supportsNegative)
{ {
m_position = NavCategory::GetPosition(m_viewMode); m_position = NavCategory::GetPosition(m_viewMode);
} }
@ -206,10 +189,8 @@ namespace CalculatorApp
bool m_supportsNegative; bool m_supportsNegative;
}; };
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class NavCategoryGroup sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class NavCategoryGroup sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
public: public:
OBSERVABLE_OBJECT(); OBSERVABLE_OBJECT();
OBSERVABLE_PROPERTY_R(Platform::String ^, Name); OBSERVABLE_PROPERTY_R(Platform::String ^, Name);
@ -221,8 +202,7 @@ namespace CalculatorApp
static Platform::String ^ GetHeaderResourceKey(CategoryGroupType type); static Platform::String ^ GetHeaderResourceKey(CategoryGroupType type);
internal: internal : static NavCategoryGroup ^ CreateCalculatorCategory();
static NavCategoryGroup^ CreateCalculatorCategory();
static NavCategoryGroup ^ CreateConverterCategory(); static NavCategoryGroup ^ CreateConverterCategory();
private: private:

View file

@ -10,9 +10,8 @@ using namespace Windows::Networking::Connectivity;
NetworkManager::NetworkManager() NetworkManager::NetworkManager()
{ {
m_NetworkStatusChangedToken = m_NetworkStatusChangedToken = NetworkInformation::NetworkStatusChanged +=
NetworkInformation::NetworkStatusChanged += ref new NetworkStatusChangedEventHandler( ref new NetworkStatusChangedEventHandler(this, &NetworkManager::OnNetworkStatusChange, CallbackContext::Same);
this, &NetworkManager::OnNetworkStatusChange, CallbackContext::Same);
} }
NetworkManager::~NetworkManager() NetworkManager::~NetworkManager()
@ -27,8 +26,7 @@ NetworkAccessBehavior NetworkManager::GetNetworkAccessBehavior()
if (connectionProfile != nullptr) if (connectionProfile != nullptr)
{ {
NetworkConnectivityLevel connectivityLevel = connectionProfile->GetNetworkConnectivityLevel(); NetworkConnectivityLevel connectivityLevel = connectionProfile->GetNetworkConnectivityLevel();
if (connectivityLevel == NetworkConnectivityLevel::InternetAccess if (connectivityLevel == NetworkConnectivityLevel::InternetAccess || connectivityLevel == NetworkConnectivityLevel::ConstrainedInternetAccess)
|| connectivityLevel == NetworkConnectivityLevel::ConstrainedInternetAccess)
{ {
ConnectionCost ^ connectionCost = connectionProfile->GetConnectionCost(); ConnectionCost ^ connectionCost = connectionProfile->GetConnectionCost();
behavior = ConvertCostInfoToBehavior(connectionCost); behavior = ConvertCostInfoToBehavior(connectionCost);
@ -46,8 +44,7 @@ void NetworkManager::OnNetworkStatusChange(_In_ Object^ /*sender*/)
// See app behavior guidelines at https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj835821(v=win.10).aspx // See app behavior guidelines at https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj835821(v=win.10).aspx
NetworkAccessBehavior NetworkManager::ConvertCostInfoToBehavior(_In_ ConnectionCost ^ connectionCost) NetworkAccessBehavior NetworkManager::ConvertCostInfoToBehavior(_In_ ConnectionCost ^ connectionCost)
{ {
if (connectionCost->Roaming || connectionCost->OverDataLimit if (connectionCost->Roaming || connectionCost->OverDataLimit || connectionCost->NetworkCostType == NetworkCostType::Variable
|| connectionCost->NetworkCostType == NetworkCostType::Variable
|| connectionCost->NetworkCostType == NetworkCostType::Fixed) || connectionCost->NetworkCostType == NetworkCostType::Fixed)
{ {
return NetworkAccessBehavior::OptIn; return NetworkAccessBehavior::OptIn;

View file

@ -5,16 +5,19 @@
namespace CalculatorApp namespace CalculatorApp
{ {
public enum class NetworkAccessBehavior public
enum class NetworkAccessBehavior
{ {
Normal = 0, Normal = 0,
OptIn = 1, OptIn = 1,
Offline = 2 Offline = 2
}; };
public delegate void NetworkBehaviorChangedHandler(NetworkAccessBehavior behavior); public
delegate void NetworkBehaviorChangedHandler(NetworkAccessBehavior behavior);
public ref class NetworkManager sealed public
ref class NetworkManager sealed
{ {
public: public:
NetworkManager(); NetworkManager();

View file

@ -11,30 +11,19 @@ namespace CalculatorApp
class TraceActivity class TraceActivity
{ {
public: public:
TraceActivity() : TraceActivity() : m_channel(nullptr), m_activity(nullptr), m_fields(nullptr)
m_channel(nullptr), {
m_activity(nullptr), }
m_fields(nullptr)
{ }
TraceActivity( TraceActivity(winrt::Windows::Foundation::Diagnostics::LoggingChannel channel, std::wstring_view activityName,
winrt::Windows::Foundation::Diagnostics::LoggingChannel channel, winrt::Windows::Foundation::Diagnostics::LoggingFields fields)
std::wstring_view activityName, : m_channel(channel), m_activityName(activityName), m_fields(fields), m_activity(nullptr)
winrt::Windows::Foundation::Diagnostics::LoggingFields fields) :
m_channel(channel),
m_activityName(activityName),
m_fields(fields),
m_activity(nullptr)
{ {
// Write the activity's START event. Note that you must not specify keyword // Write the activity's START event. Note that you must not specify keyword
// or level for START and STOP events because they always use the activity's // or level for START and STOP events because they always use the activity's
// keyword and level. // keyword and level.
m_activity = m_channel.StartActivity( m_activity = m_channel.StartActivity(m_activityName, m_fields, winrt::Windows::Foundation::Diagnostics::LoggingLevel::Verbose,
m_activityName, winrt::Windows::Foundation::Diagnostics::LoggingOptions(WINEVENT_KEYWORD_RESPONSE_TIME));
m_fields,
winrt::Windows::Foundation::Diagnostics::LoggingLevel::Verbose,
winrt::Windows::Foundation::Diagnostics::LoggingOptions(WINEVENT_KEYWORD_RESPONSE_TIME)
);
} }
~TraceActivity() ~TraceActivity()

View file

@ -21,10 +21,8 @@ namespace CalculatorApp
{ {
static multimap<int, vector<wstring>> s_memoryMap; static multimap<int, vector<wstring>> s_memoryMap;
static constexpr array<const wchar_t * const, 9> s_programmerType{ static constexpr array<const wchar_t* const, 9> s_programmerType{ L"N/A", L"QwordType", L"DwordType", L"WordType", L"ByteType",
L"N/A", L"QwordType", L"DwordType", L"HexBase", L"DecBase", L"OctBase", L"BinBase" };
L"WordType", L"ByteType", L"HexBase",
L"DecBase", L"OctBase", L"BinBase" };
static reader_writer_lock s_traceLoggerLock; static reader_writer_lock s_traceLoggerLock;
// Telemetry events. Uploaded to asimov. // Telemetry events. Uploaded to asimov.
@ -99,11 +97,12 @@ namespace CalculatorApp
#pragma region TraceLogger setup and cleanup #pragma region TraceLogger setup and cleanup
TraceLogger::TraceLogger() : TraceLogger::TraceLogger()
g_calculatorProvider( : g_calculatorProvider(
L"MicrosoftCalculator", L"MicrosoftCalculator",
LoggingChannelOptions(GUID{ 0x4f50731a, 0x89cf, 0x4782, 0xb3, 0xe0, 0xdc, 0xe8, 0xc9, 0x4, 0x76, 0xba }), // Microsoft Telemetry group LoggingChannelOptions(GUID{ 0x4f50731a, 0x89cf, 0x4782, 0xb3, 0xe0, 0xdc, 0xe8, 0xc9, 0x4, 0x76, 0xba }), // Microsoft Telemetry group
GUID{ 0x905ca09, 0x610e, 0x401e, 0xb6, 0x50, 0x2f, 0x21, 0x29, 0x80, 0xb9, 0xe0 }), // Unique providerID {0905CA09-610E-401E-B650-2F212980B9E0} GUID{ 0x905ca09, 0x610e, 0x401e, 0xb6, 0x50, 0x2f, 0x21, 0x29, 0x80, 0xb9, 0xe0 })
, // Unique providerID {0905CA09-610E-401E-B650-2F212980B9E0}
m_appLaunchActivity{ nullptr } m_appLaunchActivity{ nullptr }
{ {
// initialize the function array // initialize the function array
@ -307,7 +306,8 @@ namespace CalculatorApp
void TraceLogger::LogSharedMemoryUsed(wstring_view fromMode, wstring_view toMode, unsigned int memorySize) const void TraceLogger::LogSharedMemoryUsed(wstring_view fromMode, wstring_view toMode, unsigned int memorySize) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"FromMode", fromMode); fields.AddString(L"FromMode", fromMode);
@ -318,7 +318,8 @@ namespace CalculatorApp
void TraceLogger::LogBitFlipPaneClicked() const void TraceLogger::LogBitFlipPaneClicked() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_BITFLIP_PANE_CLICKED, fields); LogTelemetryEvent(EVENT_NAME_BITFLIP_PANE_CLICKED, fields);
@ -326,7 +327,8 @@ namespace CalculatorApp
void TraceLogger::LogBitFlipUsed() const void TraceLogger::LogBitFlipUsed() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_BITFLIP_BUTTONS_USED, fields); LogTelemetryEvent(EVENT_NAME_BITFLIP_BUTTONS_USED, fields);
@ -339,11 +341,8 @@ namespace CalculatorApp
if (!isAppLaunchBeginLogged) if (!isAppLaunchBeginLogged)
{ {
m_appLaunchActivity = g_calculatorProvider.StartActivity( m_appLaunchActivity =
EVENT_NAME_APP_LAUNCH_BEGIN, g_calculatorProvider.StartActivity(EVENT_NAME_APP_LAUNCH_BEGIN, nullptr, LoggingLevel::Verbose, LoggingOptions(MICROSOFT_KEYWORD_TELEMETRY));
nullptr,
LoggingLevel::Verbose,
LoggingOptions(MICROSOFT_KEYWORD_TELEMETRY));
isAppLaunchBeginLogged = true; isAppLaunchBeginLogged = true;
} }
@ -376,7 +375,8 @@ namespace CalculatorApp
void TraceLogger::LogDebug(wstring_view debugData) void TraceLogger::LogDebug(wstring_view debugData)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"DebugData", debugData); fields.AddString(L"DebugData", debugData);
@ -385,7 +385,8 @@ namespace CalculatorApp
void TraceLogger::LogOnAppLaunch(wstring_view previousExecutionState) const void TraceLogger::LogOnAppLaunch(wstring_view previousExecutionState) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"PreviousExecutionState", previousExecutionState); fields.AddString(L"PreviousExecutionState", previousExecutionState);
@ -394,7 +395,8 @@ namespace CalculatorApp
void TraceLogger::LogAboutFlyoutOpened() const void TraceLogger::LogAboutFlyoutOpened() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_ABOUT_FLYOUT_OPENED, fields); LogTelemetryEvent(EVENT_NAME_ABOUT_FLYOUT_OPENED, fields);
@ -402,7 +404,8 @@ namespace CalculatorApp
void TraceLogger::LogNavBarOpened() const void TraceLogger::LogNavBarOpened() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_NAV_BAR_OPENED, fields); LogTelemetryEvent(EVENT_NAME_NAV_BAR_OPENED, fields);
@ -410,7 +413,8 @@ namespace CalculatorApp
void TraceLogger::LogClearHistory() const void TraceLogger::LogClearHistory() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_HISTORY_CLEAR, fields); LogTelemetryEvent(EVENT_NAME_HISTORY_CLEAR, fields);
@ -418,7 +422,8 @@ namespace CalculatorApp
void TraceLogger::LogHistoryFlyoutOpenBegin(unsigned int historyItemCount) const void TraceLogger::LogHistoryFlyoutOpenBegin(unsigned int historyItemCount) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
// we want to record the event only when history item count is atleast 20 // we want to record the event only when history item count is atleast 20
if (historyItemCount >= 20) if (historyItemCount >= 20)
@ -431,7 +436,8 @@ namespace CalculatorApp
void TraceLogger::LogHistoryFlyoutOpenEnd(int historyItemCount) const void TraceLogger::LogHistoryFlyoutOpenEnd(int historyItemCount) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
if (historyItemCount >= 20) if (historyItemCount >= 20)
{ {
@ -443,7 +449,8 @@ namespace CalculatorApp
void TraceLogger::LogHistoryBodyOpened() const void TraceLogger::LogHistoryBodyOpened() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_HISTORY_BODY_OPENED, fields); LogTelemetryEvent(EVENT_NAME_HISTORY_BODY_OPENED, fields);
@ -451,7 +458,8 @@ namespace CalculatorApp
void TraceLogger::LogMemoryFlyoutOpenBegin(unsigned int memoryItemCount) const void TraceLogger::LogMemoryFlyoutOpenBegin(unsigned int memoryItemCount) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
// we want to record the event only when memory item count is atleast 4 // we want to record the event only when memory item count is atleast 4
if (memoryItemCount >= 4) if (memoryItemCount >= 4)
@ -464,7 +472,8 @@ namespace CalculatorApp
void TraceLogger::LogMemoryFlyoutOpenEnd(unsigned int memoryItemCount) const void TraceLogger::LogMemoryFlyoutOpenEnd(unsigned int memoryItemCount) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
if (memoryItemCount >= 4) if (memoryItemCount >= 4)
{ {
@ -476,7 +485,8 @@ namespace CalculatorApp
void TraceLogger::LogMemoryBodyOpened() const void TraceLogger::LogMemoryBodyOpened() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_MEMORY_BODY_OPENED, fields); LogTelemetryEvent(EVENT_NAME_MEMORY_BODY_OPENED, fields);
@ -487,7 +497,8 @@ namespace CalculatorApp
// Use of this function is to analyze perf of mode change. // Use of this function is to analyze perf of mode change.
void TraceLogger::LogModeChangeBegin(ViewMode fromMode, ViewMode toMode, int windowId) void TraceLogger::LogModeChangeBegin(ViewMode fromMode, ViewMode toMode, int windowId)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
if (NavCategory::IsValidViewMode(fromMode) && NavCategory::IsValidViewMode(toMode)) if (NavCategory::IsValidViewMode(fromMode) && NavCategory::IsValidViewMode(toMode))
{ {
@ -502,7 +513,8 @@ namespace CalculatorApp
// comment: same as LogModeChangeBegin // comment: same as LogModeChangeBegin
void TraceLogger::LogModeChangeEnd(ViewMode toMode, int windowId) const void TraceLogger::LogModeChangeEnd(ViewMode toMode, int windowId) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
if (NavCategory::IsValidViewMode(toMode)) if (NavCategory::IsValidViewMode(toMode))
{ {
@ -515,7 +527,8 @@ namespace CalculatorApp
void TraceLogger::LogHistoryItemLoadBegin() const void TraceLogger::LogHistoryItemLoadBegin() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_HISTORY_ITEM_LOAD_BEGIN, fields); LogTelemetryEvent(EVENT_NAME_HISTORY_ITEM_LOAD_BEGIN, fields);
@ -523,7 +536,8 @@ namespace CalculatorApp
void TraceLogger::LogHistoryItemLoadEnd(unsigned int historyTokenCount) const void TraceLogger::LogHistoryItemLoadEnd(unsigned int historyTokenCount) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"HistoryTokenCount", historyTokenCount); fields.AddUInt32(L"HistoryTokenCount", historyTokenCount);
@ -532,7 +546,8 @@ namespace CalculatorApp
void TraceLogger::LogNewWindowCreationBegin(int windowId) void TraceLogger::LogNewWindowCreationBegin(int windowId)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"WindowId", windowId); fields.AddUInt32(L"WindowId", windowId);
@ -541,7 +556,8 @@ namespace CalculatorApp
void TraceLogger::LogNewWindowCreationEnd(int windowId) void TraceLogger::LogNewWindowCreationEnd(int windowId)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"WindowId", windowId); fields.AddUInt32(L"WindowId", windowId);
@ -550,7 +566,8 @@ namespace CalculatorApp
void TraceLogger::LogError(wstring_view errorString) void TraceLogger::LogError(wstring_view errorString)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"ErrorString", errorString); fields.AddString(L"ErrorString", errorString);
@ -559,7 +576,8 @@ namespace CalculatorApp
void TraceLogger::LogPrelaunchedAppActivatedByUser() void TraceLogger::LogPrelaunchedAppActivatedByUser()
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_PRELAUNCHED_APP_ACTIVATED_BY_USER, fields); LogTelemetryEvent(EVENT_NAME_PRELAUNCHED_APP_ACTIVATED_BY_USER, fields);
@ -567,7 +585,8 @@ namespace CalculatorApp
void TraceLogger::LogAppPrelaunchedBySystem() void TraceLogger::LogAppPrelaunchedBySystem()
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_APP_PRELAUNCHED_BY_SYSTEM, fields); LogTelemetryEvent(EVENT_NAME_APP_PRELAUNCHED_BY_SYSTEM, fields);
@ -588,9 +607,11 @@ namespace CalculatorApp
} }
} }
void TraceLogger::LogMemoryUsed(int windowId, unsigned int slotPosition, bool isStandard, bool isScientific, bool isProgrammer, unsigned int memorySize) const void TraceLogger::LogMemoryUsed(int windowId, unsigned int slotPosition, bool isStandard, bool isScientific, bool isProgrammer,
unsigned int memorySize) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
// Reader lock for the static resources // Reader lock for the static resources
reader_writer_lock::scoped_lock_read lock(s_traceLoggerLock); reader_writer_lock::scoped_lock_read lock(s_traceLoggerLock);
@ -625,7 +646,8 @@ namespace CalculatorApp
void TraceLogger::LogMultipleMemoryUsed(unsigned int slotPosition, unsigned int memorySize) const void TraceLogger::LogMultipleMemoryUsed(unsigned int slotPosition, unsigned int memorySize) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"MemoryIndex", slotPosition); fields.AddUInt32(L"MemoryIndex", slotPosition);
@ -635,7 +657,8 @@ namespace CalculatorApp
void TraceLogger::LogSingleMemoryUsed(unsigned int memorySize) const void TraceLogger::LogSingleMemoryUsed(unsigned int memorySize) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"MemoryListSize", memorySize); fields.AddUInt32(L"MemoryListSize", memorySize);
@ -644,7 +667,8 @@ namespace CalculatorApp
void TraceLogger::LogInvalidPastedInputOccurred(wstring_view reason, ViewMode mode, int programmerNumberBase, int bitLengthType) void TraceLogger::LogInvalidPastedInputOccurred(wstring_view reason, ViewMode mode, int programmerNumberBase, int bitLengthType)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"Mode", NavCategory::GetFriendlyName(mode)->Data()); fields.AddString(L"Mode", NavCategory::GetFriendlyName(mode)->Data());
@ -657,7 +681,8 @@ namespace CalculatorApp
void TraceLogger::LogValidInputPasted(ViewMode mode) const void TraceLogger::LogValidInputPasted(ViewMode mode) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"Mode", NavCategory::GetFriendlyName(mode)->Data()); fields.AddString(L"Mode", NavCategory::GetFriendlyName(mode)->Data());
@ -666,7 +691,8 @@ namespace CalculatorApp
void TraceLogger::LogStandardException(wstring_view functionName, const exception& e) const void TraceLogger::LogStandardException(wstring_view functionName, const exception& e) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"FunctionName", functionName); fields.AddString(L"FunctionName", functionName);
@ -678,7 +704,8 @@ namespace CalculatorApp
void TraceLogger::LogWinRTException(wstring_view functionName, hresult_error const& e) const void TraceLogger::LogWinRTException(wstring_view functionName, hresult_error const& e) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"FunctionName", functionName); fields.AddString(L"FunctionName", functionName);
@ -689,7 +716,8 @@ namespace CalculatorApp
void TraceLogger::LogPlatformException(wstring_view functionName, Platform::Exception ^ e) const void TraceLogger::LogPlatformException(wstring_view functionName, Platform::Exception ^ e) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"FunctionName", functionName); fields.AddString(L"FunctionName", functionName);
@ -755,7 +783,8 @@ namespace CalculatorApp
void TraceLogger::LogMaxWindowCount() void TraceLogger::LogMaxWindowCount()
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
fields.AddUInt32(L"WindowCount", (unsigned int)maxWindowCount); fields.AddUInt32(L"WindowCount", (unsigned int)maxWindowCount);
@ -764,7 +793,8 @@ namespace CalculatorApp
void TraceLogger::LogWindowActivated() const void TraceLogger::LogWindowActivated() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_WINDOW_LAUNCHED_PROTOCOL, fields); LogTelemetryEvent(EVENT_NAME_WINDOW_LAUNCHED_PROTOCOL, fields);
@ -772,7 +802,8 @@ namespace CalculatorApp
void TraceLogger::LogWindowLaunched() const void TraceLogger::LogWindowLaunched() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_WINDOW_LAUNCHED_TILESEARCH, fields); LogTelemetryEvent(EVENT_NAME_WINDOW_LAUNCHED_TILESEARCH, fields);
@ -840,7 +871,8 @@ namespace CalculatorApp
void TraceLogger::LogFunctionUsage(int windowId) void TraceLogger::LogFunctionUsage(int windowId)
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
for (int i = 0; i < functionCount; i++) for (int i = 0; i < functionCount; i++)
{ {
@ -897,8 +929,7 @@ namespace CalculatorApp
// Ignore first 3 calls during the initialization of the combo box selected items for Add mode // Ignore first 3 calls during the initialization of the combo box selected items for Add mode
int firstChangeEventCount = isAddMode ? 4 : 1; int firstChangeEventCount = isAddMode ? 4 : 1;
if (((*usageMap)[windowId] == firstChangeEventCount) if (((*usageMap)[windowId] == firstChangeEventCount) && (!(*isLoggedInSession)))
&& (!(*isLoggedInSession)))
{ {
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"AddSubtractMode", isAddMode ? L"Add" : L"Subtract"); fields.AddString(L"AddSubtractMode", isAddMode ? L"Add" : L"Subtract");
@ -910,16 +941,12 @@ namespace CalculatorApp
void TraceLogger::LogDateClippedTimeDifferenceFound(Calendar const& today, DateTime const& clippedTime) const void TraceLogger::LogDateClippedTimeDifferenceFound(Calendar const& today, DateTime const& clippedTime) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
auto calendarSystem = today.GetCalendarSystem(); auto calendarSystem = today.GetCalendarSystem();
auto clock = today.GetClock(); auto clock = today.GetClock();
DateTimeFormatter dtFormatter{ DateTimeFormatter dtFormatter{ L"longdate shorttime", { L"en-US" }, GlobalizationPreferences::HomeGeographicRegion(), calendarSystem, clock };
L"longdate shorttime",
{ L"en-US" },
GlobalizationPreferences::HomeGeographicRegion(),
calendarSystem,
clock };
LoggingFields fields{}; LoggingFields fields{};
fields.AddString(L"ResolvedCalendarLanguage", today.ResolvedLanguage()); fields.AddString(L"ResolvedCalendarLanguage", today.ResolvedLanguage());
@ -934,7 +961,8 @@ namespace CalculatorApp
void TraceLogger::LogUserRequestedRefreshFailed() const void TraceLogger::LogUserRequestedRefreshFailed() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(L"UserRequestedRefreshFailed", fields); LogTelemetryEvent(L"UserRequestedRefreshFailed", fields);
@ -942,7 +970,8 @@ namespace CalculatorApp
void TraceLogger::LogConversionResult(wstring_view fromValue, wstring_view fromUnit, wstring_view toValue, wstring_view toUnit) const void TraceLogger::LogConversionResult(wstring_view fromValue, wstring_view fromUnit, wstring_view toValue, wstring_view toUnit) const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
wstring behaviorString{}; wstring behaviorString{};
NetworkAccessBehavior behavior = NetworkManager::GetNetworkAccessBehavior(); NetworkAccessBehavior behavior = NetworkManager::GetNetworkAccessBehavior();
@ -979,10 +1008,10 @@ namespace CalculatorApp
void TraceLogger::LogCoreWindowWasNull() const void TraceLogger::LogCoreWindowWasNull() const
{ {
if (!GetTraceLoggingProviderEnabled()) return; if (!GetTraceLoggingProviderEnabled())
return;
LoggingFields fields{}; LoggingFields fields{};
LogTelemetryEvent(EVENT_NAME_CORE_WINDOW_WAS_NULL, fields); LogTelemetryEvent(EVENT_NAME_CORE_WINDOW_WAS_NULL, fields);
} }
} }

View file

@ -18,7 +18,10 @@ namespace CalculatorApp
public: public:
int count; int count;
std::wstring funcName; std::wstring funcName;
FuncLog() { count = 0; } FuncLog()
{
count = 0;
}
FuncLog(std::wstring fName) FuncLog(std::wstring fName)
{ {
funcName = fName; funcName = fName;
@ -93,7 +96,8 @@ namespace CalculatorApp
// Trace methods for Date Calculator usage // Trace methods for Date Calculator usage
void LogDateDifferenceModeUsed(int windowId); void LogDateDifferenceModeUsed(int windowId);
void LogDateAddSubtractModeUsed(int windowId, bool isAddMode); void LogDateAddSubtractModeUsed(int windowId, bool isAddMode);
void LogDateClippedTimeDifferenceFound(winrt::Windows::Globalization::Calendar const& today, winrt::Windows::Foundation::DateTime const& clippedTime) const; void LogDateClippedTimeDifferenceFound(winrt::Windows::Globalization::Calendar const& today,
winrt::Windows::Foundation::DateTime const& clippedTime) const;
void LogStandardException(std::wstring_view functionName, _In_ const std::exception& e) const; void LogStandardException(std::wstring_view functionName, _In_ const std::exception& e) const;
void LogWinRTException(std::wstring_view functionName, _In_ winrt::hresult_error const& e) const; void LogWinRTException(std::wstring_view functionName, _In_ winrt::hresult_error const& e) const;
@ -104,10 +108,10 @@ namespace CalculatorApp
TraceLogger(); TraceLogger();
// Any new Log method should // Any new Log method should
// a) decide the level of logging. This will help us in limiting recording of events only up to a certain level. See this link for guidance https://msdn.microsoft.com/en-us/library/windows/desktop/aa363742(v=vs.85).aspx // a) decide the level of logging. This will help us in limiting recording of events only up to a certain level. See this link for guidance
// We're using Verbose level for events that are called frequently and needed only for debugging or capturing perf for specific scenarios // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363742(v=vs.85).aspx We're using Verbose level for events that are called frequently and
// b) should decide whether or not to log to telemetry and pass TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY) accordingly // needed only for debugging or capturing perf for specific scenarios b) should decide whether or not to log to telemetry and pass
// c) Should accept a variable number of additional data arguments if needed // TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY) accordingly c) Should accept a variable number of additional data arguments if needed
void LogTelemetryEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const; void LogTelemetryEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const;
void LogMeasureEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const; void LogMeasureEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const;
void LogCriticalDataEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const; void LogCriticalDataEvent(std::wstring_view eventName, winrt::Windows::Foundation::Diagnostics::LoggingFields fields) const;

View file

@ -72,11 +72,7 @@ void Utils::RunOnUIThreadNonblocking(std::function<void()>&& function, _In_ Core
{ {
if (currentDispatcher != nullptr) if (currentDispatcher != nullptr)
{ {
auto task = create_task(currentDispatcher->RunAsync(CoreDispatcherPriority::Normal, auto task = create_task(currentDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([function]() { function(); })));
ref new DispatchedHandler([function]()
{
function();
})));
} }
} }
@ -97,8 +93,7 @@ wstring Utils::RemoveUnwantedCharsFromWstring(wstring input, wchar_t* unwantedCh
} }
void Utils::SerializeCommandsAndTokens(_In_ shared_ptr<CalculatorVector<pair<wstring, int>>> const& tokens, void Utils::SerializeCommandsAndTokens(_In_ shared_ptr<CalculatorVector<pair<wstring, int>>> const& tokens,
_In_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const &commands, _In_ shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> const& commands, DataWriter ^ writer)
DataWriter^ writer)
{ {
unsigned int commandsSize; unsigned int commandsSize;
IFTPlatformException(commands->GetSize(&commandsSize)); IFTPlatformException(commands->GetSize(&commandsSize));

View file

@ -10,91 +10,170 @@
// Utility macros to make Models easier to write // Utility macros to make Models easier to write
// generates a member variable called m_<n> // generates a member variable called m_<n>
#define PROPERTY_R(t, n) \ #define PROPERTY_R(t, n) \
property t n {\ property t n \
t get() { return m_##n; }\ { \
private: void set(t value) { m_##n = value; }\ t get() \
} private: t m_##n; public: { \
return m_##n; \
} \
\
private: \
void set(t value) \
{ \
m_##n = value; \
} \
} \
private: \
t m_##n; \
public:
#define PROPERTY_RW(t, n) \ #define PROPERTY_RW(t, n) \
property t n {\ property t n \
t get() { return m_##n; }\ { \
void set(t value) { m_##n = value; }\ t get() \
} private: t m_##n; public: { \
return m_##n; \
} \
void set(t value) \
{ \
m_##n = value; \
} \
} \
private: \
t m_##n; \
public:
#define OBSERVABLE_PROPERTY_R(t, n) \ #define OBSERVABLE_PROPERTY_R(t, n) \
property t n {\ property t n \
t get() { return m_##n; }\ { \
private: void set(t value) {\ t get() \
if (m_##n != value) {\ { \
return m_##n; \
} \
\
private: \
void set(t value) \
{ \
if (m_##n != value) \
{ \
m_##n = value; \ m_##n = value; \
RaisePropertyChanged(L#n); \ RaisePropertyChanged(L#n); \
}}\ } \
} private: t m_##n; public: } \
} \
private: \
t m_##n; \
public:
#define OBSERVABLE_PROPERTY_RW(t, n) \ #define OBSERVABLE_PROPERTY_RW(t, n) \
property t n {\ property t n \
t get() { return m_##n; }\ { \
void set(t value) {\ t get() \
if (m_##n != value) {\ { \
return m_##n; \
} \
void set(t value) \
{ \
if (m_##n != value) \
{ \
m_##n = value; \ m_##n = value; \
RaisePropertyChanged(L#n); \ RaisePropertyChanged(L#n); \
} \ } \
} \ } \
} private: t m_##n; public: } \
private: \
t m_##n; \
public:
#define OBSERVABLE_NAMED_PROPERTY_R(t, n) \ #define OBSERVABLE_NAMED_PROPERTY_R(t, n) \
OBSERVABLE_PROPERTY_R(t, n) \ OBSERVABLE_PROPERTY_R(t, n) \
internal: static property Platform::String^ n##PropertyName {\ internal: \
static property Platform::String ^ n##PropertyName \
{ \
Platform::String ^ get() { return Platform::StringReference(L#n); } \ Platform::String ^ get() { return Platform::StringReference(L#n); } \
} public: } \
public:
#define OBSERVABLE_NAMED_PROPERTY_RW(t, n) \ #define OBSERVABLE_NAMED_PROPERTY_RW(t, n) \
OBSERVABLE_PROPERTY_RW(t, n) \ OBSERVABLE_PROPERTY_RW(t, n) \
internal: static property Platform::String^ n##PropertyName {\ internal: \
static property Platform::String ^ n##PropertyName \
{ \
Platform::String ^ get() { return Platform::StringReference(L#n); } \ Platform::String ^ get() { return Platform::StringReference(L#n); } \
} public: } \
public:
#define OBSERVABLE_PROPERTY_FIELD(n) m_##n #define OBSERVABLE_PROPERTY_FIELD(n) m_##n
// This variant of the observable object is for objects that don't want to react to property changes // This variant of the observable object is for objects that don't want to react to property changes
#ifndef UNIT_TESTS #ifndef UNIT_TESTS
#define OBSERVABLE_OBJECT() virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;\ #define OBSERVABLE_OBJECT() \
internal: void RaisePropertyChanged(Platform::String^ p) {\ virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged; \
PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(p)); } public: internal: \
void RaisePropertyChanged(Platform::String ^ p) \
{ \
PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(p)); \
} \
public:
#else #else
#define OBSERVABLE_OBJECT() virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;\ #define OBSERVABLE_OBJECT() \
internal: void RaisePropertyChanged(Platform::String^ p) {\ virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged; \
} public: internal: \
void RaisePropertyChanged(Platform::String ^ p) \
{ \
} \
public:
#endif #endif
// The callback specified in the macro is a method in the class that will be called every time the object changes // The callback specified in the macro is a method in the class that will be called every time the object changes
// the callback is supposed to be have a single parameter of type Platform::String^ // the callback is supposed to be have a single parameter of type Platform::String^
#ifndef UNIT_TESTS #ifndef UNIT_TESTS
#define OBSERVABLE_OBJECT_CALLBACK(c) virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;\ #define OBSERVABLE_OBJECT_CALLBACK(c) \
internal: void RaisePropertyChanged(Platform::String^ p) {\ virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged; \
internal: \
void RaisePropertyChanged(Platform::String ^ p) \
{ \
PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(p)); \ PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(p)); \
c(p); \ c(p); \
} public: } \
public:
#else #else
#define OBSERVABLE_OBJECT_CALLBACK(c) virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;\ #define OBSERVABLE_OBJECT_CALLBACK(c) \
internal: void RaisePropertyChanged(Platform::String^ p) {\ virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged; \
internal: \
void RaisePropertyChanged(Platform::String ^ p) \
{ \
c(p); \ c(p); \
} public: } \
public:
#endif #endif
// The variable member generated by this macro should not be used in the class code, use the // The variable member generated by this macro should not be used in the class code, use the
// property getter instead. // property getter instead.
#define COMMAND_FOR_METHOD(p, m) property Windows::UI::Xaml::Input::ICommand^ p {\ #define COMMAND_FOR_METHOD(p, m) \
property Windows::UI::Xaml::Input::ICommand^ p {\
Windows::UI::Xaml::Input::ICommand^ get() {\ Windows::UI::Xaml::Input::ICommand^ get() {\
if (!donotuse_##p) {\ if (!donotuse_##p) {\
donotuse_##p = CalculatorApp::Common::MakeDelegate(this, &m);\ donotuse_##p = CalculatorApp::Common::MakeDelegate(this, &m);\
} return donotuse_##p; }} private: Windows::UI::Xaml::Input::ICommand^ donotuse_##p; public: } return donotuse_##p; }} private: Windows::UI::Xaml::Input::ICommand^ donotuse_##p; \
public:
#define DEPENDENCY_PROPERTY_DECLARATION(t, n) \ #define DEPENDENCY_PROPERTY_DECLARATION(t, n) \
property t n {\ property t n \
t get() { return safe_cast<t>(GetValue(s_##n##Property)); }\ { \
void set(t value) { SetValue(s_##n##Property, value); } }\ t get() \
private: static Windows::UI::Xaml::DependencyProperty^ s_##n##Property; public: { \
return safe_cast<t>(GetValue(s_##n##Property)); \
} \
void set(t value) \
{ \
SetValue(s_##n##Property, value); \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##n##Property; \
public:
// Utilities for DependencyProperties // Utilities for DependencyProperties
namespace Utils namespace Utils
@ -299,114 +378,279 @@ namespace Utils
Windows::Foundation::DateTime GetUniversalSystemTime(); Windows::Foundation::DateTime GetUniversalSystemTime();
bool IsDateTimeOlderThan(Windows::Foundation::DateTime dateTime, const long long duration); bool IsDateTimeOlderThan(Windows::Foundation::DateTime dateTime, const long long duration);
concurrency::task<void> WriteFileToFolder(Windows::Storage::IStorageFolder^ folder, Platform::String^ fileName, Platform::String^ contents, Windows::Storage::CreationCollisionOption collisionOption); concurrency::task<void> WriteFileToFolder(Windows::Storage::IStorageFolder ^ folder, Platform::String ^ fileName, Platform::String ^ contents,
Windows::Storage::CreationCollisionOption collisionOption);
concurrency::task<Platform::String ^> ReadFileFromFolder(Windows::Storage::IStorageFolder ^ folder, Platform::String ^ fileName); concurrency::task<Platform::String ^> ReadFileFromFolder(Windows::Storage::IStorageFolder ^ folder, Platform::String ^ fileName);
} }
// This goes into the header to define the property, in the public: section of the class // This goes into the header to define the property, in the public: section of the class
#define DEPENDENCY_PROPERTY_OWNER(owner) \ #define DEPENDENCY_PROPERTY_OWNER(owner) \
private: typedef owner DependencyPropertiesOwner; public: private: \
typedef owner DependencyPropertiesOwner; \
public:
// Normal DependencyProperty // Normal DependencyProperty
#define DEPENDENCY_PROPERTY(type, name) \ #define DEPENDENCY_PROPERTY(type, name) \
property type name {\ property type name \
type get() { return safe_cast<type>(GetValue(s_##name##Property)); }\ { \
void set(type value) { SetValue(s_##name##Property, value); }\ type get() \
} private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ { \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\ return safe_cast<type>(GetValue(s_##name##Property)); \
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ void set(type value) \
return Utils::RegisterDependencyProperty<DependencyPropertiesOwner, type>(L#name); } public: { \
SetValue(s_##name##Property, value); \
} \
} \
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyProperty<DependencyPropertiesOwner, type>(L#name); \
} \
public:
#define DEPENDENCY_PROPERTY_WITH_DEFAULT(type, name, defaultValue) \ #define DEPENDENCY_PROPERTY_WITH_DEFAULT(type, name, defaultValue) \
property type name {\ property type name \
type get() { return safe_cast<type>(GetValue(s_##name##Property)); }\ { \
void set(type value) { SetValue(s_##name##Property, value); }\ type get() \
} private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ { \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\ return safe_cast<type>(GetValue(s_##name##Property)); \
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ void set(type value) \
return Utils::RegisterDependencyProperty<DependencyPropertiesOwner, type>(L#name, defaultValue); } public: { \
SetValue(s_##name##Property, value); \
} \
} \
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyProperty<DependencyPropertiesOwner, type>(L#name, defaultValue); \
} \
public:
#define DEPENDENCY_PROPERTY_WITH_CALLBACK(type, name) \ #define DEPENDENCY_PROPERTY_WITH_CALLBACK(type, name) \
property type name {\ property type name \
type get() { return safe_cast<type>(GetValue(s_##name##Property)); }\ { \
void set(type value) { SetValue(s_##name##Property, value); }\ type get() \
} private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ { \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\ return safe_cast<type>(GetValue(s_##name##Property)); \
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ void set(type value) \
return Utils::RegisterDependencyPropertyWithCallback<DependencyPropertiesOwner, type>(L#name, &On##name##PropertyChangedImpl); }\ { \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ args) {\ SetValue(s_##name##Property, value); \
} \
} \
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyWithCallback<DependencyPropertiesOwner, type>(L#name, &On##name##PropertyChangedImpl); \
} \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject ^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ args) \
{ \
auto self = safe_cast<DependencyPropertiesOwner ^>(sender); \ auto self = safe_cast<DependencyPropertiesOwner ^>(sender); \
self->On##name##PropertyChanged(safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); } public: self->On##name##PropertyChanged(safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); \
} \
public:
#define DEPENDENCY_PROPERTY_WITH_DEFAULT_AND_CALLBACK(type, name, defaultValue) \ #define DEPENDENCY_PROPERTY_WITH_DEFAULT_AND_CALLBACK(type, name, defaultValue) \
property type name {\ property type name \
type get() { return safe_cast<type>(GetValue(s_##name##Property)); }\ { \
void set(type value) { SetValue(s_##name##Property, value); }\ type get() \
} private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ { \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\ return safe_cast<type>(GetValue(s_##name##Property)); \
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ void set(type value) \
return Utils::RegisterDependencyPropertyWithCallback<DependencyPropertiesOwner, type>(L#name, defaultValue, &On##name##PropertyChangedImpl); }\ { \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ args) {\ SetValue(s_##name##Property, value); \
} \
} \
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyWithCallback<DependencyPropertiesOwner, type>(L#name, defaultValue, &On##name##PropertyChangedImpl); \
} \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject ^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ args) \
{ \
auto self = safe_cast<DependencyPropertiesOwner ^>(sender); \ auto self = safe_cast<DependencyPropertiesOwner ^>(sender); \
self->On##name##PropertyChanged(safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); } public: self->On##name##PropertyChanged(safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); \
} \
public:
// Attached DependencyProperty // Attached DependencyProperty
#define DEPENDENCY_PROPERTY_ATTACHED(type, name) \ #define DEPENDENCY_PROPERTY_ATTACHED(type, name) \
static type Get##name(Windows::UI::Xaml::DependencyObject^ target) { return safe_cast<type>(target->GetValue(s_##name##Property)); }\ static type Get##name(Windows::UI::Xaml::DependencyObject ^ target) \
static void Set##name(Windows::UI::Xaml::DependencyObject^ target, type value) { target->SetValue(s_##name##Property, value); }\ { \
private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ return safe_cast<type>(target->GetValue(s_##name##Property)); \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ static void Set##name(Windows::UI::Xaml::DependencyObject ^ target, type value) \
return Utils::RegisterDependencyPropertyAttached<DependencyPropertiesOwner, type>(L#name); } public: { \
target->SetValue(s_##name##Property, value); \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyAttached<DependencyPropertiesOwner, type>(L#name); \
} \
public:
#define DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT(type, name, defaultValue) \ #define DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT(type, name, defaultValue) \
static type Get##name(Windows::UI::Xaml::DependencyObject^ target) { return safe_cast<type>(target->GetValue(s_##name##Property)); }\ static type Get##name(Windows::UI::Xaml::DependencyObject ^ target) \
static void Set##name(Windows::UI::Xaml::DependencyObject^ target, type value) { target->SetValue(s_##name##Property, value); }\ { \
private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ return safe_cast<type>(target->GetValue(s_##name##Property)); \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ static void Set##name(Windows::UI::Xaml::DependencyObject ^ target, type value) \
return Utils::RegisterDependencyPropertyAttached<DependencyPropertiesOwner, type>(L#name, defaultValue); } public: { \
target->SetValue(s_##name##Property, value); \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyAttached<DependencyPropertiesOwner, type>(L#name, defaultValue); \
} \
public:
#define DEPENDENCY_PROPERTY_ATTACHED_WITH_CALLBACK(type, name) \ #define DEPENDENCY_PROPERTY_ATTACHED_WITH_CALLBACK(type, name) \
static type Get##name(Windows::UI::Xaml::DependencyObject^ target) { return safe_cast<type>(target->GetValue(s_##name##Property)); }\ static type Get##name(Windows::UI::Xaml::DependencyObject ^ target) \
static void Set##name(Windows::UI::Xaml::DependencyObject^ target, type value) { target->SetValue(s_##name##Property, value); }\ { \
private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ return safe_cast<type>(target->GetValue(s_##name##Property)); \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ static void Set##name(Windows::UI::Xaml::DependencyObject ^ target, type value) \
return Utils::RegisterDependencyPropertyAttachedWithCallback<DependencyPropertiesOwner, type>(L#name, &On##name##PropertyChangedImpl); }\ { \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ args) {\ target->SetValue(s_##name##Property, value); \
On##name##PropertyChanged(sender, safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); } public: } \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyAttachedWithCallback<DependencyPropertiesOwner, type>(L#name, &On##name##PropertyChangedImpl); \
} \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject ^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ args) \
{ \
On##name##PropertyChanged(sender, safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); \
} \
public:
#define DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT_AND_CALLBACK(type, name, defaultValue) \ #define DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT_AND_CALLBACK(type, name, defaultValue) \
static type Get##name(Windows::UI::Xaml::DependencyObject^ target) { return safe_cast<type>(target->GetValue(s_##name##Property)); }\ static type Get##name(Windows::UI::Xaml::DependencyObject ^ target) \
static void Set##name(Windows::UI::Xaml::DependencyObject^ target, type value) { target->SetValue(s_##name##Property, value); }\ { \
private: static Windows::UI::Xaml::DependencyProperty^ s_##name##Property;\ return safe_cast<type>(target->GetValue(s_##name##Property)); \
public: static property Windows::UI::Xaml::DependencyProperty^ name##Property {\
Windows::UI::Xaml::DependencyProperty^ get() { assert(s_##name##Property); return s_##name##Property; }\
} \ } \
private: static Windows::UI::Xaml::DependencyProperty^ Initialize##name##Property() {\ static void Set##name(Windows::UI::Xaml::DependencyObject ^ target, type value) \
return Utils::RegisterDependencyPropertyAttachedWithCallback<DependencyPropertiesOwner, type>(L#name, defaultValue, &On##name##PropertyChangedImpl); }\ { \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ args) {\ target->SetValue(s_##name##Property, value); \
On##name##PropertyChanged(sender, safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); } public: } \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ s_##name##Property; \
\
public: \
static property Windows::UI::Xaml::DependencyProperty ^ name##Property \
{ \
Windows::UI::Xaml::DependencyProperty ^ get() { \
assert(s_##name##Property); \
return s_##name##Property; \
} \
} \
\
private: \
static Windows::UI::Xaml::DependencyProperty ^ Initialize##name##Property() \
{ \
return Utils::RegisterDependencyPropertyAttachedWithCallback<DependencyPropertiesOwner, type>(L#name, defaultValue, &On##name##PropertyChangedImpl); \
} \
static void On##name##PropertyChangedImpl(Windows::UI::Xaml::DependencyObject ^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ args) \
{ \
On##name##PropertyChanged(sender, safe_cast<type>(args->OldValue), safe_cast<type>(args->NewValue)); \
} \
public:
// This goes into the cpp to initialize the static variable // This goes into the cpp to initialize the static variable
#define DEPENDENCY_PROPERTY_INITIALIZATION(owner, name)\ #define DEPENDENCY_PROPERTY_INITIALIZATION(owner, name) Windows::UI::Xaml::DependencyProperty ^ owner::s_##name##Property = owner::Initialize##name##Property();
Windows::UI::Xaml::DependencyProperty^ owner::s_##name##Property =\
owner::Initialize##name##Property();
namespace CalculatorApp namespace CalculatorApp
{ {
@ -415,8 +659,7 @@ namespace CalculatorApp
{ {
T to{ nullptr }; T to{ nullptr };
winrt::check_hresult(reinterpret_cast<::IUnknown*>(from)->QueryInterface(winrt::guid_of<T>(), winrt::check_hresult(reinterpret_cast<::IUnknown*>(from)->QueryInterface(winrt::guid_of<T>(), reinterpret_cast<void**>(winrt::put_abi(to))));
reinterpret_cast<void**>(winrt::put_abi(to))));
return to; return to;
} }

View file

@ -3,30 +3,29 @@
#pragma once #pragma once
namespace CalculatorApp { namespace Common namespace CalculatorApp
{ {
public ref class ValidSelectedItemConverter sealed: public Windows::UI::Xaml::Data::IValueConverter namespace Common
{
public
ref class ValidSelectedItemConverter sealed : public Windows::UI::Xaml::Data::IValueConverter
{ {
public: public:
ValidSelectedItemConverter() ValidSelectedItemConverter()
{ } {
}
private: private:
virtual Platform::Object
virtual Platform::Object^ Convert( ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Platform::Object^ value,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert
{ {
// Pass through as we don't want to change the value from the source // Pass through as we don't want to change the value from the source
return value; return value;
} }
virtual Platform::Object^ ConvertBack( virtual Platform::Object
Platform::Object^ value, ^ ConvertBack(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack
{ {
if (value) if (value)
@ -38,28 +37,25 @@ namespace CalculatorApp { namespace Common
} }
}; };
public ref class ValidSelectedIndexConverter sealed: public Windows::UI::Xaml::Data::IValueConverter public
ref class ValidSelectedIndexConverter sealed : public Windows::UI::Xaml::Data::IValueConverter
{ {
public: public:
ValidSelectedIndexConverter() ValidSelectedIndexConverter()
{ } {
}
private: private:
virtual Platform::Object
virtual Platform::Object^ Convert( ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Platform::Object^ value,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert
{ {
// Pass through as we don't want to change the value from the source // Pass through as we don't want to change the value from the source
return value; return value;
} }
virtual Platform::Object^ ConvertBack( virtual Platform::Object
Platform::Object^ value, ^ ConvertBack(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/,
Windows::UI::Xaml::Interop::TypeName /*targetType*/,
Platform::Object^ /*parameter*/,
Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack
{ {
// The value to be valid has to be a boxed int32 value // The value to be valid has to be a boxed int32 value
@ -80,4 +76,5 @@ namespace CalculatorApp { namespace Common
return Windows::UI::Xaml::DependencyProperty::UnsetValue; return Windows::UI::Xaml::DependencyProperty::UnsetValue;
} }
}; };
}} }
}

View file

@ -46,21 +46,14 @@ static constexpr auto CACHE_LANGCODE_KEY = L"CURRENCY_CONVERTER_LANGCODE";
static constexpr auto CACHE_DELIMITER = L"%"; static constexpr auto CACHE_DELIMITER = L"%";
static constexpr auto STATIC_DATA_FILENAME = L"CURRENCY_CONVERTER_STATIC_DATA.txt"; static constexpr auto STATIC_DATA_FILENAME = L"CURRENCY_CONVERTER_STATIC_DATA.txt";
static constexpr array<wstring_view, 5> STATIC_DATA_PROPERTIES = { static constexpr array<wstring_view, 5> STATIC_DATA_PROPERTIES = { wstring_view{ L"CountryCode", 11 }, wstring_view{ L"CountryName", 11 },
wstring_view{ L"CountryCode", 11 }, wstring_view{ L"CurrencyCode", 12 }, wstring_view{ L"CurrencyName", 12 },
wstring_view{ L"CountryName", 11 }, wstring_view{ L"CurrencySymbol", 14 } };
wstring_view{ L"CurrencyCode", 12 },
wstring_view{ L"CurrencyName", 12 },
wstring_view{ L"CurrencySymbol", 14 }
};
static constexpr auto ALL_RATIOS_DATA_FILENAME = L"CURRENCY_CONVERTER_ALL_RATIOS_DATA.txt"; static constexpr auto ALL_RATIOS_DATA_FILENAME = L"CURRENCY_CONVERTER_ALL_RATIOS_DATA.txt";
static constexpr auto RATIO_KEY = L"Rt"; static constexpr auto RATIO_KEY = L"Rt";
static constexpr auto CURRENCY_CODE_KEY = L"An"; static constexpr auto CURRENCY_CODE_KEY = L"An";
static constexpr array<wstring_view, 2> ALL_RATIOS_DATA_PROPERTIES = { static constexpr array<wstring_view, 2> ALL_RATIOS_DATA_PROPERTIES = { wstring_view{ RATIO_KEY, 2 }, wstring_view{ CURRENCY_CODE_KEY, 2 } };
wstring_view{ RATIO_KEY, 2 },
wstring_view{ CURRENCY_CODE_KEY, 2 }
};
static constexpr auto DEFAULT_FROM_TO_CURRENCY_FILE_URI = L"ms-appx:///DataLoaders/DefaultFromToCurrency.json"; static constexpr auto DEFAULT_FROM_TO_CURRENCY_FILE_URI = L"ms-appx:///DataLoaders/DefaultFromToCurrency.json";
static constexpr auto FROM_KEY = L"from"; static constexpr auto FROM_KEY = L"from";
@ -92,14 +85,14 @@ namespace CalculatorApp
} }
} }
CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr<ICurrencyHttpClient> client) : CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr<ICurrencyHttpClient> client)
m_client(move(client)), : m_client(move(client))
m_loadStatus(CurrencyLoadStatus::NotLoaded), , m_loadStatus(CurrencyLoadStatus::NotLoaded)
m_responseLanguage(L"en-US"), , m_responseLanguage(L"en-US")
m_ratioFormat(L""), , m_ratioFormat(L"")
m_timestampFormat(L""), , m_timestampFormat(L"")
m_networkManager(ref new NetworkManager()), , m_networkManager(ref new NetworkManager())
m_meteredOverrideSet(false) , m_meteredOverrideSet(false)
{ {
if (GlobalizationPreferences::Languages->Size > 0) if (GlobalizationPreferences::Languages->Size > 0)
{ {
@ -141,11 +134,8 @@ void CurrencyDataLoader::RegisterForNetworkBehaviorChanges()
{ {
UnregisterForNetworkBehaviorChanges(); UnregisterForNetworkBehaviorChanges();
m_networkBehaviorToken = m_networkBehaviorToken = m_networkManager->NetworkBehaviorChanged +=
m_networkManager->NetworkBehaviorChanged += ref new NetworkBehaviorChangedHandler([this](NetworkAccessBehavior newBehavior) ref new NetworkBehaviorChangedHandler([this](NetworkAccessBehavior newBehavior) { this->OnNetworkBehaviorChanged(newBehavior); });
{
this->OnNetworkBehaviorChanged(newBehavior);
});
OnNetworkBehaviorChanged(NetworkManager::GetNetworkAccessBehavior()); OnNetworkBehaviorChanged(NetworkManager::GetNetworkAccessBehavior());
} }
@ -186,8 +176,7 @@ void CurrencyDataLoader::LoadData()
if (!LoadFinished()) if (!LoadFinished())
{ {
create_task([this]() -> task<bool> create_task([this]() -> task<bool> {
{
vector<function<task<bool>()>> loadFunctions = { vector<function<task<bool>()>> loadFunctions = {
[this]() { return TryLoadDataFromCacheAsync(); }, [this]() { return TryLoadDataFromCacheAsync(); },
[this]() { return TryLoadDataFromWebAsync(); }, [this]() { return TryLoadDataFromWebAsync(); },
@ -204,11 +193,13 @@ void CurrencyDataLoader::LoadData()
} }
co_return didLoad; co_return didLoad;
}).then([this](bool didLoad) })
{ .then(
[this](bool didLoad) {
UpdateDisplayedTimestamp(); UpdateDisplayedTimestamp();
NotifyDataLoadFinished(didLoad); NotifyDataLoadFinished(didLoad);
}, task_continuation_context::use_current()); },
task_continuation_context::use_current());
} }
}; };
#pragma optimize("", on) #pragma optimize("", on)
@ -284,27 +275,19 @@ pair<wstring, wstring> CurrencyDataLoader::GetCurrencyRatioEquality(_In_ const U
wstring digitSymbol = wstring{ LocalizationSettings::GetInstance().GetDigitSymbolFromEnUsDigit(L'1') }; wstring digitSymbol = wstring{ LocalizationSettings::GetInstance().GetDigitSymbolFromEnUsDigit(L'1') };
wstring roundedFormat = m_ratioFormatter->Format(rounded)->Data(); wstring roundedFormat = m_ratioFormatter->Format(rounded)->Data();
wstring ratioString = LocalizationStringUtil::GetLocalizedString( wstring ratioString = LocalizationStringUtil::GetLocalizedString(m_ratioFormat.c_str(), digitSymbol.c_str(), unit1.abbreviation.c_str(),
m_ratioFormat.c_str(), roundedFormat.c_str(), unit2.abbreviation.c_str());
digitSymbol.c_str(),
unit1.abbreviation.c_str(),
roundedFormat.c_str(),
unit2.abbreviation.c_str()
);
wstring accessibleRatioString = LocalizationStringUtil::GetLocalizedString( wstring accessibleRatioString = LocalizationStringUtil::GetLocalizedString(
m_ratioFormat.c_str(), m_ratioFormat.c_str(), digitSymbol.c_str(), unit1.accessibleName.c_str(), roundedFormat.c_str(), unit2.accessibleName.c_str());
digitSymbol.c_str(),
unit1.accessibleName.c_str(),
roundedFormat.c_str(),
unit2.accessibleName.c_str()
);
return make_pair(ratioString, accessibleRatioString); return make_pair(ratioString, accessibleRatioString);
} }
} }
} }
catch (...) {} catch (...)
{
}
return make_pair(L"", L""); return make_pair(L"", L"");
} }
@ -324,8 +307,7 @@ task<bool> CurrencyDataLoader::TryLoadDataFromCacheAsync()
bool loadComplete = false; bool loadComplete = false;
m_cacheTimestamp = static_cast<DateTime>(localSettings->Values->Lookup(CacheTimestampKey)); m_cacheTimestamp = static_cast<DateTime>(localSettings->Values->Lookup(CacheTimestampKey));
if (Utils::IsDateTimeOlderThan(m_cacheTimestamp, DAY_DURATION) if (Utils::IsDateTimeOlderThan(m_cacheTimestamp, DAY_DURATION) && m_networkAccessBehavior == NetworkAccessBehavior::Normal)
&& m_networkAccessBehavior == NetworkAccessBehavior::Normal)
{ {
loadComplete = co_await TryLoadDataFromWebAsync(); loadComplete = co_await TryLoadDataFromWebAsync();
} }
@ -361,8 +343,7 @@ task<bool> CurrencyDataLoader::TryFinishLoadFromCacheAsync()
co_return false; co_return false;
} }
if (!localSettings->Values->HasKey(CacheLangcodeKey) if (!localSettings->Values->HasKey(CacheLangcodeKey) || !static_cast<String ^>(localSettings->Values->Lookup(CacheLangcodeKey))->Equals(m_responseLanguage))
|| !static_cast<String^>(localSettings->Values->Lookup(CacheLangcodeKey))->Equals(m_responseLanguage))
{ {
co_return false; co_return false;
} }
@ -379,11 +360,7 @@ task<bool> CurrencyDataLoader::TryFinishLoadFromCacheAsync()
vector<UCM::CurrencyStaticData> staticData{}; vector<UCM::CurrencyStaticData> staticData{};
CurrencyRatioMap ratioMap{}; CurrencyRatioMap ratioMap{};
bool didParse = TryParseWebResponses( bool didParse = TryParseWebResponses(staticDataResponse, allRatiosResponse, staticData, ratioMap);
staticDataResponse,
allRatiosResponse,
staticData,
ratioMap);
if (!didParse) if (!didParse)
{ {
co_return false; co_return false;
@ -406,8 +383,7 @@ task<bool> CurrencyDataLoader::TryLoadDataFromWebAsync()
co_return false; co_return false;
} }
if (m_networkAccessBehavior == NetworkAccessBehavior::Offline || if (m_networkAccessBehavior == NetworkAccessBehavior::Offline || (m_networkAccessBehavior == NetworkAccessBehavior::OptIn && !m_meteredOverrideSet))
(m_networkAccessBehavior == NetworkAccessBehavior::OptIn && !m_meteredOverrideSet))
{ {
co_return false; co_return false;
} }
@ -422,11 +398,7 @@ task<bool> CurrencyDataLoader::TryLoadDataFromWebAsync()
vector<UCM::CurrencyStaticData> staticData{}; vector<UCM::CurrencyStaticData> staticData{};
CurrencyRatioMap ratioMap{}; CurrencyRatioMap ratioMap{};
bool didParse = TryParseWebResponses( bool didParse = TryParseWebResponses(staticDataResponse, allRatiosResponse, staticData, ratioMap);
staticDataResponse,
allRatiosResponse,
staticData,
ratioMap);
if (!didParse) if (!didParse)
{ {
co_return false; co_return false;
@ -437,19 +409,12 @@ task<bool> CurrencyDataLoader::TryLoadDataFromWebAsync()
try try
{ {
const vector<pair<String^, String^>> cachedFiles = { const vector<pair<String ^, String ^>> cachedFiles = { { StaticDataFilename, staticDataResponse }, { AllRatiosDataFilename, allRatiosResponse } };
{ StaticDataFilename, staticDataResponse },
{ AllRatiosDataFilename, allRatiosResponse }
};
StorageFolder ^ localCacheFolder = ApplicationData::Current->LocalCacheFolder; StorageFolder ^ localCacheFolder = ApplicationData::Current->LocalCacheFolder;
for (const auto& fileInfo : cachedFiles) for (const auto& fileInfo : cachedFiles)
{ {
co_await Utils::WriteFileToFolder( co_await Utils::WriteFileToFolder(localCacheFolder, fileInfo.first, fileInfo.second, CreationCollisionOption::ReplaceExisting);
localCacheFolder,
fileInfo.first,
fileInfo.second,
CreationCollisionOption::ReplaceExisting);
} }
SaveLangCodeAndTimestamp(); SaveLangCodeAndTimestamp();
@ -494,14 +459,10 @@ task<bool> CurrencyDataLoader::TryLoadDataFromWebOverrideAsync()
}; };
#pragma optimize("", on) #pragma optimize("", on)
bool CurrencyDataLoader::TryParseWebResponses( bool CurrencyDataLoader::TryParseWebResponses(_In_ String ^ staticDataJson, _In_ String ^ allRatiosJson, _Inout_ vector<UCM::CurrencyStaticData>& staticData,
_In_ String^ staticDataJson,
_In_ String^ allRatiosJson,
_Inout_ vector<UCM::CurrencyStaticData>& staticData,
_Inout_ CurrencyRatioMap& allRatiosData) _Inout_ CurrencyRatioMap& allRatiosData)
{ {
return TryParseStaticData(staticDataJson, staticData) return TryParseStaticData(staticDataJson, staticData) && TryParseAllRatiosData(allRatiosJson, allRatiosData);
&& TryParseAllRatiosData(allRatiosJson, allRatiosData);
} }
bool CurrencyDataLoader::TryParseStaticData(_In_ String ^ rawJson, _Inout_ vector<UCM::CurrencyStaticData>& staticData) bool CurrencyDataLoader::TryParseStaticData(_In_ String ^ rawJson, _Inout_ vector<UCM::CurrencyStaticData>& staticData)
@ -518,13 +479,7 @@ bool CurrencyDataLoader::TryParseStaticData(_In_ String^ rawJson, _Inout_ vector
wstring currencyName{ L"" }; wstring currencyName{ L"" };
wstring currencySymbol{ L"" }; wstring currencySymbol{ L"" };
vector<wstring*> values = { vector<wstring*> values = { &countryCode, &countryName, &currencyCode, &currencyName, &currencySymbol };
&countryCode,
&countryName,
&currencyCode,
&currencyName,
&currencySymbol
};
assert(values.size() == STATIC_DATA_PROPERTIES.size()); assert(values.size() == STATIC_DATA_PROPERTIES.size());
staticData.resize(size_t{ data->Size }); staticData.resize(size_t{ data->Size });
@ -537,20 +492,11 @@ bool CurrencyDataLoader::TryParseStaticData(_In_ String^ rawJson, _Inout_ vector
(*values[j]) = obj->GetNamedString(StringReference(STATIC_DATA_PROPERTIES[j].data()))->Data(); (*values[j]) = obj->GetNamedString(StringReference(STATIC_DATA_PROPERTIES[j].data()))->Data();
} }
staticData[i] = CurrencyStaticData{ staticData[i] = CurrencyStaticData{ countryCode, countryName, currencyCode, currencyName, currencySymbol };
countryCode,
countryName,
currencyCode,
currencyName,
currencySymbol
};
} }
// TODO - MSFT 8533667: this sort will be replaced by a WinRT call to sort localized strings // TODO - MSFT 8533667: this sort will be replaced by a WinRT call to sort localized strings
sort(begin(staticData), end(staticData), [](CurrencyStaticData unit1, CurrencyStaticData unit2) sort(begin(staticData), end(staticData), [](CurrencyStaticData unit1, CurrencyStaticData unit2) { return unit1.countryName < unit2.countryName; });
{
return unit1.countryName < unit2.countryName;
});
return true; return true;
} }
@ -574,11 +520,7 @@ bool CurrencyDataLoader::TryParseAllRatiosData(_In_ String^ rawJson, _Inout_ Cur
double relativeRatio = obj->GetNamedNumber(StringReference(RATIO_KEY)); double relativeRatio = obj->GetNamedNumber(StringReference(RATIO_KEY));
wstring targetCurrencyCode = obj->GetNamedString(StringReference(CURRENCY_CODE_KEY))->Data(); wstring targetCurrencyCode = obj->GetNamedString(StringReference(CURRENCY_CODE_KEY))->Data();
allRatios.emplace(targetCurrencyCode, CurrencyRatio{ allRatios.emplace(targetCurrencyCode, CurrencyRatio{ relativeRatio, sourceCurrencyCode, targetCurrencyCode });
relativeRatio,
sourceCurrencyCode,
targetCurrencyCode
});
} }
return true; return true;
@ -735,11 +677,7 @@ wstring CurrencyDataLoader::GetCurrencyTimestamp()
DateTimeFormatter ^ timeFormatter = ref new DateTimeFormatter(L"shorttime"); DateTimeFormatter ^ timeFormatter = ref new DateTimeFormatter(L"shorttime");
wstring time = timeFormatter->Format(m_cacheTimestamp)->Data(); wstring time = timeFormatter->Format(m_cacheTimestamp)->Data();
timestamp = LocalizationStringUtil::GetLocalizedString( timestamp = LocalizationStringUtil::GetLocalizedString(m_timestampFormat.c_str(), date.c_str(), time.c_str());
m_timestampFormat.c_str(),
date.c_str(),
time.c_str()
);
} }
return timestamp; return timestamp;
@ -774,7 +712,9 @@ task<SelectedUnits> CurrencyDataLoader::GetDefaultFromToCurrency()
toCurrency = selectedTo->Data(); toCurrency = selectedTo->Data();
} }
} }
catch (...) {} catch (...)
{
}
} }
co_return make_pair(fromCurrency, toCurrency); co_return make_pair(fromCurrency, toCurrency);

View file

@ -11,7 +11,8 @@ namespace CalculatorApp
{ {
namespace ViewModel namespace ViewModel
{ {
public enum class CurrencyLoadStatus public
enum class CurrencyLoadStatus
{ {
NotLoaded = 0, NotLoaded = 0,
FailedToLoad = 1, FailedToLoad = 1,
@ -42,13 +43,14 @@ namespace CalculatorApp
struct CurrencyUnitMetadata struct CurrencyUnitMetadata
{ {
CurrencyUnitMetadata(const std::wstring& s) : symbol(s) {} CurrencyUnitMetadata(const std::wstring& s) : symbol(s)
{
}
const std::wstring symbol; const std::wstring symbol;
}; };
class CurrencyDataLoader : public UCM::IConverterDataLoader, class CurrencyDataLoader : public UCM::IConverterDataLoader, public UCM::ICurrencyConverterDataLoader
public UCM::ICurrencyConverterDataLoader
{ {
public: public:
CurrencyDataLoader(_In_ std::unique_ptr<CalculatorApp::DataLoaders::ICurrencyHttpClient> client); CurrencyDataLoader(_In_ std::unique_ptr<CalculatorApp::DataLoaders::ICurrencyHttpClient> client);
@ -69,7 +71,8 @@ namespace CalculatorApp
// ICurrencyConverterDataLoader // ICurrencyConverterDataLoader
void SetViewModelCallback(const std::shared_ptr<UCM::IViewModelCurrencyCallback>& callback) override; void SetViewModelCallback(const std::shared_ptr<UCM::IViewModelCurrencyCallback>& callback) override;
std::pair<std::wstring, std::wstring> GetCurrencySymbols(const UCM::Unit& unit1, const UCM::Unit& unit2) override; std::pair<std::wstring, std::wstring> GetCurrencySymbols(const UCM::Unit& unit1, const UCM::Unit& unit2) override;
std::pair<std::wstring, std::wstring> GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) override; std::pair<std::wstring, std::wstring> GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1,
_In_ const UnitConversionManager::Unit& unit2) override;
std::wstring GetCurrencyTimestamp() override; std::wstring GetCurrencyTimestamp() override;
concurrency::task<bool> TryLoadDataFromCacheAsync() override; concurrency::task<bool> TryLoadDataFromCacheAsync() override;
@ -85,11 +88,8 @@ namespace CalculatorApp
concurrency::task<bool> TryFinishLoadFromCacheAsync(); concurrency::task<bool> TryFinishLoadFromCacheAsync();
bool TryParseWebResponses( bool TryParseWebResponses(_In_ Platform::String ^ staticDataJson, _In_ Platform::String ^ allRatiosJson,
_In_ Platform::String^ staticDataJson, _Inout_ std::vector<UCM::CurrencyStaticData>& staticData, _Inout_ CurrencyRatioMap& allRatiosData);
_In_ Platform::String^ allRatiosJson,
_Inout_ std::vector<UCM::CurrencyStaticData>& staticData,
_Inout_ CurrencyRatioMap& allRatiosData);
bool TryParseStaticData(_In_ Platform::String ^ rawJson, _Inout_ std::vector<UCM::CurrencyStaticData>& staticData); bool TryParseStaticData(_In_ Platform::String ^ rawJson, _Inout_ std::vector<UCM::CurrencyStaticData>& staticData);
bool TryParseAllRatiosData(_In_ Platform::String ^ rawJson, _Inout_ CurrencyRatioMap& allRatiosData); bool TryParseAllRatiosData(_In_ Platform::String ^ rawJson, _Inout_ CurrencyRatioMap& allRatiosData);
concurrency::task<void> FinalizeUnits(_In_ const std::vector<UCM::CurrencyStaticData>& staticData, _In_ const CurrencyRatioMap& ratioMap); concurrency::task<void> FinalizeUnits(_In_ const std::vector<UCM::CurrencyStaticData>& staticData, _In_ const CurrencyRatioMap& ratioMap);

View file

@ -13,9 +13,7 @@ using namespace Windows::Web::Http;
static constexpr auto sc_MetadataUriLocalizeFor = L"https://go.microsoft.com/fwlink/?linkid=2041093&localizeFor="; static constexpr auto sc_MetadataUriLocalizeFor = L"https://go.microsoft.com/fwlink/?linkid=2041093&localizeFor=";
static constexpr auto sc_RatiosUriRelativeTo = L"https://go.microsoft.com/fwlink/?linkid=2041339&localCurrency="; static constexpr auto sc_RatiosUriRelativeTo = L"https://go.microsoft.com/fwlink/?linkid=2041339&localCurrency=";
CurrencyHttpClient::CurrencyHttpClient() : CurrencyHttpClient::CurrencyHttpClient() : m_client(ref new HttpClient()), m_responseLanguage(L"en-US")
m_client(ref new HttpClient()),
m_responseLanguage(L"en-US")
{ {
} }

View file

@ -10,7 +10,9 @@ namespace CalculatorApp
class ICurrencyHttpClient class ICurrencyHttpClient
{ {
public: public:
virtual ~ICurrencyHttpClient() {} virtual ~ICurrencyHttpClient()
{
}
virtual void SetSourceCurrencyCode(Platform::String ^ sourceCurrencyCode) = 0; virtual void SetSourceCurrencyCode(Platform::String ^ sourceCurrencyCode) = 0;
virtual void SetResponseLanguage(Platform::String ^ responseLanguage) = 0; virtual void SetResponseLanguage(Platform::String ^ responseLanguage) = 0;

View file

@ -5,7 +5,8 @@ namespace CalculatorApp
{ {
namespace ViewModel namespace ViewModel
{ {
private enum UnitConverterUnits private
enum UnitConverterUnits
{ {
UnitStart = 0, UnitStart = 0,
Area_Acre = UnitStart + 1, Area_Acre = UnitStart + 1,

View file

@ -18,8 +18,7 @@ using namespace Windows::Globalization;
static constexpr bool CONVERT_WITH_OFFSET_FIRST = true; static constexpr bool CONVERT_WITH_OFFSET_FIRST = true;
UnitConverterDataLoader::UnitConverterDataLoader(GeographicRegion^ region) : UnitConverterDataLoader::UnitConverterDataLoader(GeographicRegion ^ region) : m_currentRegionCode(region->CodeTwoLetter)
m_currentRegionCode(region->CodeTwoLetter)
{ {
m_categoryList = make_shared<vector<UCM::Category>>(); m_categoryList = make_shared<vector<UCM::Category>>();
m_categoryToUnits = make_shared<UCM::CategoryToUnitVectorMap>(); m_categoryToUnits = make_shared<UCM::CategoryToUnitVectorMap>();
@ -55,10 +54,7 @@ bool UnitConverterDataLoader::SupportsCategory(const UCM::Category& target)
static int currencyId = NavCategory::Serialize(ViewMode::Currency); static int currencyId = NavCategory::Serialize(ViewMode::Currency);
auto itr = find_if(supportedCategories->begin(), supportedCategories->end(), auto itr = find_if(supportedCategories->begin(), supportedCategories->end(),
[&](const UCM::Category& category) [&](const UCM::Category& category) { return currencyId != category.id && target.id == category.id; });
{
return currencyId != category.id && target.id == category.id;
});
return itr != supportedCategories->end(); return itr != supportedCategories->end();
} }
@ -154,20 +150,15 @@ void UnitConverterDataLoader::GetCategories(_In_ shared_ptr<vector<UCM::Category
for (auto const& category : converterCategory->Categories) for (auto const& category : converterCategory->Categories)
{ {
/* Id, CategoryName, SupportsNegative */ /* Id, CategoryName, SupportsNegative */
categoriesList->emplace_back( categoriesList->emplace_back(NavCategory::Serialize(category->Mode), category->Name->Data(), category->SupportsNegative);
NavCategory::Serialize(category->Mode),
category->Name->Data(),
category->SupportsNegative);
} }
} }
void UnitConverterDataLoader::GetUnits(_In_ unordered_map<ViewMode, vector<OrderedUnit>>& unitMap) void UnitConverterDataLoader::GetUnits(_In_ unordered_map<ViewMode, vector<OrderedUnit>>& unitMap)
{ {
// US + Federated States of Micronesia, Marshall Islands, Palau // US + Federated States of Micronesia, Marshall Islands, Palau
bool useUSCustomaryAndFahrenheit = m_currentRegionCode == L"US" || bool useUSCustomaryAndFahrenheit =
m_currentRegionCode == L"FM" || m_currentRegionCode == L"US" || m_currentRegionCode == L"FM" || m_currentRegionCode == L"MH" || m_currentRegionCode == L"PW";
m_currentRegionCode == L"MH" ||
m_currentRegionCode == L"PW";
// useUSCustomaryAndFahrenheit + Liberia // useUSCustomaryAndFahrenheit + Liberia
// Source: https://en.wikipedia.org/wiki/Metrication // Source: https://en.wikipedia.org/wiki/Metrication
@ -187,205 +178,359 @@ void UnitConverterDataLoader::GetUnits(_In_ unordered_map<ViewMode, vector<Order
bool usePyeong = m_currentRegionCode == L"KP" || m_currentRegionCode == L"KR"; bool usePyeong = m_currentRegionCode == L"KP" || m_currentRegionCode == L"KR";
vector<OrderedUnit> areaUnits; vector<OrderedUnit> areaUnits;
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Acre, GetLocalizedStringName(L"UnitName_Acre"), GetLocalizedStringName(L"UnitAbbreviation_Acre"), 9 }); areaUnits.push_back(
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Hectare, GetLocalizedStringName(L"UnitName_Hectare"), GetLocalizedStringName(L"UnitAbbreviation_Hectare"), 4 }); OrderedUnit{ UnitConverterUnits::Area_Acre, GetLocalizedStringName(L"UnitName_Acre"), GetLocalizedStringName(L"UnitAbbreviation_Acre"), 9 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareCentimeter, GetLocalizedStringName(L"UnitName_SquareCentimeter"), GetLocalizedStringName(L"UnitAbbreviation_SquareCentimeter"), 2 }); areaUnits.push_back(
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareFoot, GetLocalizedStringName(L"UnitName_SquareFoot"), GetLocalizedStringName(L"UnitAbbreviation_SquareFoot"), 7, useSI, useUSCustomary, false }); OrderedUnit{ UnitConverterUnits::Area_Hectare, GetLocalizedStringName(L"UnitName_Hectare"), GetLocalizedStringName(L"UnitAbbreviation_Hectare"), 4 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareInch, GetLocalizedStringName(L"UnitName_SquareInch"), GetLocalizedStringName(L"UnitAbbreviation_SquareInch"), 6 }); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareCentimeter, GetLocalizedStringName(L"UnitName_SquareCentimeter"),
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareKilometer, GetLocalizedStringName(L"UnitName_SquareKilometer"), GetLocalizedStringName(L"UnitAbbreviation_SquareKilometer"), 5 }); GetLocalizedStringName(L"UnitAbbreviation_SquareCentimeter"), 2 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMeter, GetLocalizedStringName(L"UnitName_SquareMeter"), GetLocalizedStringName(L"UnitAbbreviation_SquareMeter"), 3, useUSCustomary, useSI, false}); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareFoot, GetLocalizedStringName(L"UnitName_SquareFoot"),
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMile, GetLocalizedStringName(L"UnitName_SquareMile"), GetLocalizedStringName(L"UnitAbbreviation_SquareMile"), 10 }); GetLocalizedStringName(L"UnitAbbreviation_SquareFoot"), 7, useSI, useUSCustomary, false });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMillimeter, GetLocalizedStringName(L"UnitName_SquareMillimeter"), GetLocalizedStringName(L"UnitAbbreviation_SquareMillimeter"), 1 }); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareInch, GetLocalizedStringName(L"UnitName_SquareInch"),
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareYard, GetLocalizedStringName(L"UnitName_SquareYard"), GetLocalizedStringName(L"UnitAbbreviation_SquareYard"), 8 }); GetLocalizedStringName(L"UnitAbbreviation_SquareInch"), 6 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Hand, GetLocalizedStringName(L"UnitName_Hand"), GetLocalizedStringName(L"UnitAbbreviation_Hand"), 11, false, false, true}); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareKilometer, GetLocalizedStringName(L"UnitName_SquareKilometer"),
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Paper, GetLocalizedStringName(L"UnitName_Paper"), GetLocalizedStringName(L"UnitAbbreviation_Paper"), 12, false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_SquareKilometer"), 5 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SoccerField, GetLocalizedStringName(L"UnitName_SoccerField"), GetLocalizedStringName(L"UnitAbbreviation_SoccerField"),13, false, false, true }); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMeter, GetLocalizedStringName(L"UnitName_SquareMeter"),
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Castle, GetLocalizedStringName(L"UnitName_Castle"), GetLocalizedStringName(L"UnitAbbreviation_Castle"), 14, false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_SquareMeter"), 3, useUSCustomary, useSI, false });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMile, GetLocalizedStringName(L"UnitName_SquareMile"),
GetLocalizedStringName(L"UnitAbbreviation_SquareMile"), 10 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareMillimeter, GetLocalizedStringName(L"UnitName_SquareMillimeter"),
GetLocalizedStringName(L"UnitAbbreviation_SquareMillimeter"), 1 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SquareYard, GetLocalizedStringName(L"UnitName_SquareYard"),
GetLocalizedStringName(L"UnitAbbreviation_SquareYard"), 8 });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Hand, GetLocalizedStringName(L"UnitName_Hand"), GetLocalizedStringName(L"UnitAbbreviation_Hand"),
11, false, false, true });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Paper, GetLocalizedStringName(L"UnitName_Paper"),
GetLocalizedStringName(L"UnitAbbreviation_Paper"), 12, false, false, true });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_SoccerField, GetLocalizedStringName(L"UnitName_SoccerField"),
GetLocalizedStringName(L"UnitAbbreviation_SoccerField"), 13, false, false, true });
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Castle, GetLocalizedStringName(L"UnitName_Castle"),
GetLocalizedStringName(L"UnitAbbreviation_Castle"), 14, false, false, true });
if (usePyeong) if (usePyeong)
{ {
areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Pyeong, GetLocalizedStringName(L"UnitName_Pyeong"), GetLocalizedStringName(L"UnitAbbreviation_Pyeong"), 15, false, false, false }); areaUnits.push_back(OrderedUnit{ UnitConverterUnits::Area_Pyeong, GetLocalizedStringName(L"UnitName_Pyeong"),
GetLocalizedStringName(L"UnitAbbreviation_Pyeong"), 15, false, false, false });
} }
unitMap.emplace(ViewMode::Area, areaUnits); unitMap.emplace(ViewMode::Area, areaUnits);
vector<OrderedUnit> dataUnits; vector<OrderedUnit> dataUnits;
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Bit, GetLocalizedStringName(L"UnitName_Bit"), GetLocalizedStringName(L"UnitAbbreviation_Bit"), 1 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Byte, GetLocalizedStringName(L"UnitName_Byte"), GetLocalizedStringName(L"UnitAbbreviation_Byte"), 2 }); OrderedUnit{ UnitConverterUnits::Data_Bit, GetLocalizedStringName(L"UnitName_Bit"), GetLocalizedStringName(L"UnitAbbreviation_Bit"), 1 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exabits, GetLocalizedStringName(L"UnitName_Exabits"), GetLocalizedStringName(L"UnitAbbreviation_Exabits"), 23 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exabytes, GetLocalizedStringName(L"UnitName_Exabytes"), GetLocalizedStringName(L"UnitAbbreviation_Exabytes"), 25 }); OrderedUnit{ UnitConverterUnits::Data_Byte, GetLocalizedStringName(L"UnitName_Byte"), GetLocalizedStringName(L"UnitAbbreviation_Byte"), 2 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exbibits, GetLocalizedStringName(L"UnitName_Exbibits"), GetLocalizedStringName(L"UnitAbbreviation_Exbibits"), 24 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exbibytes, GetLocalizedStringName(L"UnitName_Exbibytes"), GetLocalizedStringName(L"UnitAbbreviation_Exbibytes"), 26 }); OrderedUnit{ UnitConverterUnits::Data_Exabits, GetLocalizedStringName(L"UnitName_Exabits"), GetLocalizedStringName(L"UnitAbbreviation_Exabits"), 23 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gibibits, GetLocalizedStringName(L"UnitName_Gibibits"), GetLocalizedStringName(L"UnitAbbreviation_Gibibits"), 12 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exabytes, GetLocalizedStringName(L"UnitName_Exabytes"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gibibytes, GetLocalizedStringName(L"UnitName_Gibibytes"), GetLocalizedStringName(L"UnitAbbreviation_Gibibytes"), 14 }); GetLocalizedStringName(L"UnitAbbreviation_Exabytes"), 25 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gigabit, GetLocalizedStringName(L"UnitName_Gigabit"), GetLocalizedStringName(L"UnitAbbreviation_Gigabit"), 11 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exbibits, GetLocalizedStringName(L"UnitName_Exbibits"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gigabyte, GetLocalizedStringName(L"UnitName_Gigabyte"), GetLocalizedStringName(L"UnitAbbreviation_Gigabyte"),13, true, false, false}); GetLocalizedStringName(L"UnitAbbreviation_Exbibits"), 24 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kibibits, GetLocalizedStringName(L"UnitName_Kibibits"), GetLocalizedStringName(L"UnitAbbreviation_Kibibits"), 4 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Exbibytes, GetLocalizedStringName(L"UnitName_Exbibytes"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kibibytes, GetLocalizedStringName(L"UnitName_Kibibytes"), GetLocalizedStringName(L"UnitAbbreviation_Kibibytes"),6 }); GetLocalizedStringName(L"UnitAbbreviation_Exbibytes"), 26 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kilobit, GetLocalizedStringName(L"UnitName_Kilobit"), GetLocalizedStringName(L"UnitAbbreviation_Kilobit"), 3 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gibibits, GetLocalizedStringName(L"UnitName_Gibibits"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kilobyte, GetLocalizedStringName(L"UnitName_Kilobyte"), GetLocalizedStringName(L"UnitAbbreviation_Kilobyte"), 5 }); GetLocalizedStringName(L"UnitAbbreviation_Gibibits"), 12 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Mebibits, GetLocalizedStringName(L"UnitName_Mebibits"), GetLocalizedStringName(L"UnitAbbreviation_Mebibits"), 8 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gibibytes, GetLocalizedStringName(L"UnitName_Gibibytes"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Mebibytes, GetLocalizedStringName(L"UnitName_Mebibytes"), GetLocalizedStringName(L"UnitAbbreviation_Mebibytes"), 10 }); GetLocalizedStringName(L"UnitAbbreviation_Gibibytes"), 14 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Megabit, GetLocalizedStringName(L"UnitName_Megabit"), GetLocalizedStringName(L"UnitAbbreviation_Megabit"), 7 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Megabyte, GetLocalizedStringName(L"UnitName_Megabyte"), GetLocalizedStringName(L"UnitAbbreviation_Megabyte"), 9, false, true, false}); OrderedUnit{ UnitConverterUnits::Data_Gigabit, GetLocalizedStringName(L"UnitName_Gigabit"), GetLocalizedStringName(L"UnitAbbreviation_Gigabit"), 11 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Pebibits, GetLocalizedStringName(L"UnitName_Pebibits"), GetLocalizedStringName(L"UnitAbbreviation_Pebibits"), 20 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Gigabyte, GetLocalizedStringName(L"UnitName_Gigabyte"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Pebibytes, GetLocalizedStringName(L"UnitName_Pebibytes"), GetLocalizedStringName(L"UnitAbbreviation_Pebibytes"), 22 }); GetLocalizedStringName(L"UnitAbbreviation_Gigabyte"), 13, true, false, false });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Petabit, GetLocalizedStringName(L"UnitName_Petabit"), GetLocalizedStringName(L"UnitAbbreviation_Petabit"), 19 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kibibits, GetLocalizedStringName(L"UnitName_Kibibits"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Petabyte, GetLocalizedStringName(L"UnitName_Petabyte"), GetLocalizedStringName(L"UnitAbbreviation_Petabyte"), 21 }); GetLocalizedStringName(L"UnitAbbreviation_Kibibits"), 4 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Tebibits, GetLocalizedStringName(L"UnitName_Tebibits"), GetLocalizedStringName(L"UnitAbbreviation_Tebibits"), 16 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kibibytes, GetLocalizedStringName(L"UnitName_Kibibytes"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Tebibytes, GetLocalizedStringName(L"UnitName_Tebibytes"), GetLocalizedStringName(L"UnitAbbreviation_Tebibytes"), 18 }); GetLocalizedStringName(L"UnitAbbreviation_Kibibytes"), 6 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Terabit, GetLocalizedStringName(L"UnitName_Terabit"), GetLocalizedStringName(L"UnitAbbreviation_Terabit"), 15 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Terabyte, GetLocalizedStringName(L"UnitName_Terabyte"), GetLocalizedStringName(L"UnitAbbreviation_Terabyte"), 17 }); OrderedUnit{ UnitConverterUnits::Data_Kilobit, GetLocalizedStringName(L"UnitName_Kilobit"), GetLocalizedStringName(L"UnitAbbreviation_Kilobit"), 3 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yobibits, GetLocalizedStringName(L"UnitName_Yobibits"), GetLocalizedStringName(L"UnitAbbreviation_Yobibits"), 32 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Kilobyte, GetLocalizedStringName(L"UnitName_Kilobyte"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yobibytes, GetLocalizedStringName(L"UnitName_Yobibytes"), GetLocalizedStringName(L"UnitAbbreviation_Yobibytes"), 34 }); GetLocalizedStringName(L"UnitAbbreviation_Kilobyte"), 5 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yottabit, GetLocalizedStringName(L"UnitName_Yottabit"), GetLocalizedStringName(L"UnitAbbreviation_Yottabit"), 31 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Mebibits, GetLocalizedStringName(L"UnitName_Mebibits"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yottabyte, GetLocalizedStringName(L"UnitName_Yottabyte"), GetLocalizedStringName(L"UnitAbbreviation_Yottabyte"), 33 }); GetLocalizedStringName(L"UnitAbbreviation_Mebibits"), 8 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zebibits, GetLocalizedStringName(L"UnitName_Zebibits"), GetLocalizedStringName(L"UnitAbbreviation_Zebibits"), 28 }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Mebibytes, GetLocalizedStringName(L"UnitName_Mebibytes"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zebibytes, GetLocalizedStringName(L"UnitName_Zebibytes"), GetLocalizedStringName(L"UnitAbbreviation_Zebibytes"), 30 }); GetLocalizedStringName(L"UnitAbbreviation_Mebibytes"), 10 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zetabits, GetLocalizedStringName(L"UnitName_Zetabits"), GetLocalizedStringName(L"UnitAbbreviation_Zetabits"), 27 }); dataUnits.push_back(
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zetabytes, GetLocalizedStringName(L"UnitName_Zetabytes"), GetLocalizedStringName(L"UnitAbbreviation_Zetabytes"),29 }); OrderedUnit{ UnitConverterUnits::Data_Megabit, GetLocalizedStringName(L"UnitName_Megabit"), GetLocalizedStringName(L"UnitAbbreviation_Megabit"), 7 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_FloppyDisk, GetLocalizedStringName(L"UnitName_FloppyDisk"), GetLocalizedStringName(L"UnitAbbreviation_FloppyDisk"), 13, false, false, true }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Megabyte, GetLocalizedStringName(L"UnitName_Megabyte"),
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_CD, GetLocalizedStringName(L"UnitName_CD"), GetLocalizedStringName(L"UnitAbbreviation_CD"), 14, false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_Megabyte"), 9, false, true, false });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_DVD, GetLocalizedStringName(L"UnitName_DVD"), GetLocalizedStringName(L"UnitAbbreviation_DVD"), 15, false, false, true }); dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Pebibits, GetLocalizedStringName(L"UnitName_Pebibits"),
GetLocalizedStringName(L"UnitAbbreviation_Pebibits"), 20 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Pebibytes, GetLocalizedStringName(L"UnitName_Pebibytes"),
GetLocalizedStringName(L"UnitAbbreviation_Pebibytes"), 22 });
dataUnits.push_back(
OrderedUnit{ UnitConverterUnits::Data_Petabit, GetLocalizedStringName(L"UnitName_Petabit"), GetLocalizedStringName(L"UnitAbbreviation_Petabit"), 19 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Petabyte, GetLocalizedStringName(L"UnitName_Petabyte"),
GetLocalizedStringName(L"UnitAbbreviation_Petabyte"), 21 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Tebibits, GetLocalizedStringName(L"UnitName_Tebibits"),
GetLocalizedStringName(L"UnitAbbreviation_Tebibits"), 16 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Tebibytes, GetLocalizedStringName(L"UnitName_Tebibytes"),
GetLocalizedStringName(L"UnitAbbreviation_Tebibytes"), 18 });
dataUnits.push_back(
OrderedUnit{ UnitConverterUnits::Data_Terabit, GetLocalizedStringName(L"UnitName_Terabit"), GetLocalizedStringName(L"UnitAbbreviation_Terabit"), 15 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Terabyte, GetLocalizedStringName(L"UnitName_Terabyte"),
GetLocalizedStringName(L"UnitAbbreviation_Terabyte"), 17 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yobibits, GetLocalizedStringName(L"UnitName_Yobibits"),
GetLocalizedStringName(L"UnitAbbreviation_Yobibits"), 32 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yobibytes, GetLocalizedStringName(L"UnitName_Yobibytes"),
GetLocalizedStringName(L"UnitAbbreviation_Yobibytes"), 34 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yottabit, GetLocalizedStringName(L"UnitName_Yottabit"),
GetLocalizedStringName(L"UnitAbbreviation_Yottabit"), 31 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Yottabyte, GetLocalizedStringName(L"UnitName_Yottabyte"),
GetLocalizedStringName(L"UnitAbbreviation_Yottabyte"), 33 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zebibits, GetLocalizedStringName(L"UnitName_Zebibits"),
GetLocalizedStringName(L"UnitAbbreviation_Zebibits"), 28 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zebibytes, GetLocalizedStringName(L"UnitName_Zebibytes"),
GetLocalizedStringName(L"UnitAbbreviation_Zebibytes"), 30 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zetabits, GetLocalizedStringName(L"UnitName_Zetabits"),
GetLocalizedStringName(L"UnitAbbreviation_Zetabits"), 27 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_Zetabytes, GetLocalizedStringName(L"UnitName_Zetabytes"),
GetLocalizedStringName(L"UnitAbbreviation_Zetabytes"), 29 });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_FloppyDisk, GetLocalizedStringName(L"UnitName_FloppyDisk"),
GetLocalizedStringName(L"UnitAbbreviation_FloppyDisk"), 13, false, false, true });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_CD, GetLocalizedStringName(L"UnitName_CD"), GetLocalizedStringName(L"UnitAbbreviation_CD"), 14,
false, false, true });
dataUnits.push_back(OrderedUnit{ UnitConverterUnits::Data_DVD, GetLocalizedStringName(L"UnitName_DVD"), GetLocalizedStringName(L"UnitAbbreviation_DVD"), 15,
false, false, true });
unitMap.emplace(ViewMode::Data, dataUnits); unitMap.emplace(ViewMode::Data, dataUnits);
vector<OrderedUnit> energyUnits; vector<OrderedUnit> energyUnits;
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_BritishThermalUnit, GetLocalizedStringName(L"UnitName_BritishThermalUnit"), GetLocalizedStringName(L"UnitAbbreviation_BritishThermalUnit"), 7 }); energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_BritishThermalUnit, GetLocalizedStringName(L"UnitName_BritishThermalUnit"),
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Calorie, GetLocalizedStringName(L"UnitName_Calorie"), GetLocalizedStringName(L"UnitAbbreviation_Calorie"), 4 }); GetLocalizedStringName(L"UnitAbbreviation_BritishThermalUnit"), 7 });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_ElectronVolt, GetLocalizedStringName(L"UnitName_Electron-Volt"), GetLocalizedStringName(L"UnitAbbreviation_Electron-Volt"), 1 }); energyUnits.push_back(
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_FootPound, GetLocalizedStringName(L"UnitName_Foot-Pound"), GetLocalizedStringName(L"UnitAbbreviation_Foot-Pound"), 6 }); OrderedUnit{ UnitConverterUnits::Energy_Calorie, GetLocalizedStringName(L"UnitName_Calorie"), GetLocalizedStringName(L"UnitAbbreviation_Calorie"), 4 });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Joule, GetLocalizedStringName(L"UnitName_Joule"), GetLocalizedStringName(L"UnitAbbreviation_Joule"), 2, true, false, false}); energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_ElectronVolt, GetLocalizedStringName(L"UnitName_Electron-Volt"),
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Kilocalorie, GetLocalizedStringName(L"UnitName_Kilocalorie"), GetLocalizedStringName(L"UnitAbbreviation_Kilocalorie"), 5, false, true, false }); GetLocalizedStringName(L"UnitAbbreviation_Electron-Volt"), 1 });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Kilojoule, GetLocalizedStringName(L"UnitName_Kilojoule"), GetLocalizedStringName(L"UnitAbbreviation_Kilojoule"), 3 }); energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_FootPound, GetLocalizedStringName(L"UnitName_Foot-Pound"),
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Battery, GetLocalizedStringName(L"UnitName_Battery"), GetLocalizedStringName(L"UnitAbbreviation_Battery"), 8, false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_Foot-Pound"), 6 });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Banana, GetLocalizedStringName(L"UnitName_Banana"), GetLocalizedStringName(L"UnitAbbreviation_Banana"), 9, false, false, true }); energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Joule, GetLocalizedStringName(L"UnitName_Joule"),
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_SliceOfCake, GetLocalizedStringName(L"UnitName_SliceOfCake"), GetLocalizedStringName(L"UnitAbbreviation_SliceOfCake"),10, false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_Joule"), 2, true, false, false });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Kilocalorie, GetLocalizedStringName(L"UnitName_Kilocalorie"),
GetLocalizedStringName(L"UnitAbbreviation_Kilocalorie"), 5, false, true, false });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Kilojoule, GetLocalizedStringName(L"UnitName_Kilojoule"),
GetLocalizedStringName(L"UnitAbbreviation_Kilojoule"), 3 });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Battery, GetLocalizedStringName(L"UnitName_Battery"),
GetLocalizedStringName(L"UnitAbbreviation_Battery"), 8, false, false, true });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_Banana, GetLocalizedStringName(L"UnitName_Banana"),
GetLocalizedStringName(L"UnitAbbreviation_Banana"), 9, false, false, true });
energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_SliceOfCake, GetLocalizedStringName(L"UnitName_SliceOfCake"),
GetLocalizedStringName(L"UnitAbbreviation_SliceOfCake"), 10, false, false, true });
unitMap.emplace(ViewMode::Energy, energyUnits); unitMap.emplace(ViewMode::Energy, energyUnits);
vector<OrderedUnit> lengthUnits; vector<OrderedUnit> lengthUnits;
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Centimeter, GetLocalizedStringName(L"UnitName_Centimeter"), GetLocalizedStringName(L"UnitAbbreviation_Centimeter"), 4, useUSCustomary, useSI, false}); lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Centimeter, GetLocalizedStringName(L"UnitName_Centimeter"),
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Foot, GetLocalizedStringName(L"UnitName_Foot"), GetLocalizedStringName(L"UnitAbbreviation_Foot"), 8 }); GetLocalizedStringName(L"UnitAbbreviation_Centimeter"), 4, useUSCustomary, useSI, false });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Inch, GetLocalizedStringName(L"UnitName_Inch"), GetLocalizedStringName(L"UnitAbbreviation_Inch"), 7 , useSI, useUSCustomary, false }); lengthUnits.push_back(
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Kilometer, GetLocalizedStringName(L"UnitName_Kilometer"), GetLocalizedStringName(L"UnitAbbreviation_Kilometer"), 6 }); OrderedUnit{ UnitConverterUnits::Length_Foot, GetLocalizedStringName(L"UnitName_Foot"), GetLocalizedStringName(L"UnitAbbreviation_Foot"), 8 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Meter, GetLocalizedStringName(L"UnitName_Meter"), GetLocalizedStringName(L"UnitAbbreviation_Meter"), 5 }); lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Inch, GetLocalizedStringName(L"UnitName_Inch"),
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Micron, GetLocalizedStringName(L"UnitName_Micron"), GetLocalizedStringName(L"UnitAbbreviation_Micron"), 2 }); GetLocalizedStringName(L"UnitAbbreviation_Inch"), 7, useSI, useUSCustomary, false });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Mile, GetLocalizedStringName(L"UnitName_Mile"), GetLocalizedStringName(L"UnitAbbreviation_Mile"), 10 }); lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Kilometer, GetLocalizedStringName(L"UnitName_Kilometer"),
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Millimeter, GetLocalizedStringName(L"UnitName_Millimeter"), GetLocalizedStringName(L"UnitAbbreviation_Millimeter"), 3 }); GetLocalizedStringName(L"UnitAbbreviation_Kilometer"), 6 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Nanometer, GetLocalizedStringName(L"UnitName_Nanometer"), GetLocalizedStringName(L"UnitAbbreviation_Nanometer"), 1 }); lengthUnits.push_back(
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_NauticalMile, GetLocalizedStringName(L"UnitName_NauticalMile"), GetLocalizedStringName(L"UnitAbbreviation_NauticalMile"), 11 }); OrderedUnit{ UnitConverterUnits::Length_Meter, GetLocalizedStringName(L"UnitName_Meter"), GetLocalizedStringName(L"UnitAbbreviation_Meter"), 5 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Yard, GetLocalizedStringName(L"UnitName_Yard"), GetLocalizedStringName(L"UnitAbbreviation_Yard"), 9 }); lengthUnits.push_back(
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Paperclip, GetLocalizedStringName(L"UnitName_Paperclip"), GetLocalizedStringName(L"UnitAbbreviation_Paperclip"), 12 ,false, false, true }); OrderedUnit{ UnitConverterUnits::Length_Micron, GetLocalizedStringName(L"UnitName_Micron"), GetLocalizedStringName(L"UnitAbbreviation_Micron"), 2 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Hand, GetLocalizedStringName(L"UnitName_Hand"), GetLocalizedStringName(L"UnitAbbreviation_Hand"), 13 ,false, false, true }); lengthUnits.push_back(
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_JumboJet, GetLocalizedStringName(L"UnitName_JumboJet"), GetLocalizedStringName(L"UnitAbbreviation_JumboJet"), 14 , false, false, true }); OrderedUnit{ UnitConverterUnits::Length_Mile, GetLocalizedStringName(L"UnitName_Mile"), GetLocalizedStringName(L"UnitAbbreviation_Mile"), 10 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Millimeter, GetLocalizedStringName(L"UnitName_Millimeter"),
GetLocalizedStringName(L"UnitAbbreviation_Millimeter"), 3 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Nanometer, GetLocalizedStringName(L"UnitName_Nanometer"),
GetLocalizedStringName(L"UnitAbbreviation_Nanometer"), 1 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_NauticalMile, GetLocalizedStringName(L"UnitName_NauticalMile"),
GetLocalizedStringName(L"UnitAbbreviation_NauticalMile"), 11 });
lengthUnits.push_back(
OrderedUnit{ UnitConverterUnits::Length_Yard, GetLocalizedStringName(L"UnitName_Yard"), GetLocalizedStringName(L"UnitAbbreviation_Yard"), 9 });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Paperclip, GetLocalizedStringName(L"UnitName_Paperclip"),
GetLocalizedStringName(L"UnitAbbreviation_Paperclip"), 12, false, false, true });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Hand, GetLocalizedStringName(L"UnitName_Hand"),
GetLocalizedStringName(L"UnitAbbreviation_Hand"), 13, false, false, true });
lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_JumboJet, GetLocalizedStringName(L"UnitName_JumboJet"),
GetLocalizedStringName(L"UnitAbbreviation_JumboJet"), 14, false, false, true });
unitMap.emplace(ViewMode::Length, lengthUnits); unitMap.emplace(ViewMode::Length, lengthUnits);
vector<OrderedUnit> powerUnits; vector<OrderedUnit> powerUnits;
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_BritishThermalUnitPerMinute, GetLocalizedStringName(L"UnitName_BTUPerMinute"), GetLocalizedStringName(L"UnitAbbreviation_BTUPerMinute"), 5 }); powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_BritishThermalUnitPerMinute, GetLocalizedStringName(L"UnitName_BTUPerMinute"),
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_FootPoundPerMinute, GetLocalizedStringName(L"UnitName_Foot-PoundPerMinute"), GetLocalizedStringName(L"UnitAbbreviation_Foot-PoundPerMinute"), 4 }); GetLocalizedStringName(L"UnitAbbreviation_BTUPerMinute"), 5 });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Horsepower, GetLocalizedStringName(L"UnitName_Horsepower"), GetLocalizedStringName(L"UnitAbbreviation_Horsepower") , 3 , false, true, false }); powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_FootPoundPerMinute, GetLocalizedStringName(L"UnitName_Foot-PoundPerMinute"),
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Kilowatt, GetLocalizedStringName(L"UnitName_Kilowatt"), GetLocalizedStringName(L"UnitAbbreviation_Kilowatt"), 2 , !useWattInsteadOfKilowatt}); GetLocalizedStringName(L"UnitAbbreviation_Foot-PoundPerMinute"), 4 });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Watt, GetLocalizedStringName(L"UnitName_Watt"), GetLocalizedStringName(L"UnitAbbreviation_Watt"), 1, useWattInsteadOfKilowatt}); powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Horsepower, GetLocalizedStringName(L"UnitName_Horsepower"),
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_LightBulb, GetLocalizedStringName(L"UnitName_LightBulb"), GetLocalizedStringName(L"UnitAbbreviation_LightBulb"), 6 ,false, false, true}); GetLocalizedStringName(L"UnitAbbreviation_Horsepower"), 3, false, true, false });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Horse, GetLocalizedStringName(L"UnitName_Horse"), GetLocalizedStringName(L"UnitAbbreviation_Horse"), 7 ,false, false, true}); powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Kilowatt, GetLocalizedStringName(L"UnitName_Kilowatt"),
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_TrainEngine, GetLocalizedStringName(L"UnitName_TrainEngine"), GetLocalizedStringName(L"UnitAbbreviation_TrainEngine"), 8 ,false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_Kilowatt"), 2, !useWattInsteadOfKilowatt });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Watt, GetLocalizedStringName(L"UnitName_Watt"),
GetLocalizedStringName(L"UnitAbbreviation_Watt"), 1, useWattInsteadOfKilowatt });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_LightBulb, GetLocalizedStringName(L"UnitName_LightBulb"),
GetLocalizedStringName(L"UnitAbbreviation_LightBulb"), 6, false, false, true });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_Horse, GetLocalizedStringName(L"UnitName_Horse"),
GetLocalizedStringName(L"UnitAbbreviation_Horse"), 7, false, false, true });
powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_TrainEngine, GetLocalizedStringName(L"UnitName_TrainEngine"),
GetLocalizedStringName(L"UnitAbbreviation_TrainEngine"), 8, false, false, true });
unitMap.emplace(ViewMode::Power, powerUnits); unitMap.emplace(ViewMode::Power, powerUnits);
vector<OrderedUnit> tempUnits; vector<OrderedUnit> tempUnits;
tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_DegreesCelsius, GetLocalizedStringName(L"UnitName_DegreesCelsius"), GetLocalizedStringName(L"UnitAbbreviation_DegreesCelsius"), 1, useFahrenheit, !useFahrenheit, false }); tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_DegreesCelsius, GetLocalizedStringName(L"UnitName_DegreesCelsius"),
tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_DegreesFahrenheit, GetLocalizedStringName(L"UnitName_DegreesFahrenheit"), GetLocalizedStringName(L"UnitAbbreviation_DegreesFahrenheit"), 2 , !useFahrenheit, useFahrenheit, false }); GetLocalizedStringName(L"UnitAbbreviation_DegreesCelsius"), 1, useFahrenheit, !useFahrenheit, false });
tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_Kelvin, GetLocalizedStringName(L"UnitName_Kelvin"), GetLocalizedStringName(L"UnitAbbreviation_Kelvin"), 3 }); tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_DegreesFahrenheit, GetLocalizedStringName(L"UnitName_DegreesFahrenheit"),
GetLocalizedStringName(L"UnitAbbreviation_DegreesFahrenheit"), 2, !useFahrenheit, useFahrenheit, false });
tempUnits.push_back(OrderedUnit{ UnitConverterUnits::Temperature_Kelvin, GetLocalizedStringName(L"UnitName_Kelvin"),
GetLocalizedStringName(L"UnitAbbreviation_Kelvin"), 3 });
unitMap.emplace(ViewMode::Temperature, tempUnits); unitMap.emplace(ViewMode::Temperature, tempUnits);
vector<OrderedUnit> timeUnits; vector<OrderedUnit> timeUnits;
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Day, GetLocalizedStringName(L"UnitName_Day"), GetLocalizedStringName(L"UnitAbbreviation_Day"), 6 }); timeUnits.push_back(
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Hour, GetLocalizedStringName(L"UnitName_Hour"), GetLocalizedStringName(L"UnitAbbreviation_Hour"), 5 ,true, false, false }); OrderedUnit{ UnitConverterUnits::Time_Day, GetLocalizedStringName(L"UnitName_Day"), GetLocalizedStringName(L"UnitAbbreviation_Day"), 6 });
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Microsecond, GetLocalizedStringName(L"UnitName_Microsecond"), GetLocalizedStringName(L"UnitAbbreviation_Microsecond"), 1 }); timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Hour, GetLocalizedStringName(L"UnitName_Hour"), GetLocalizedStringName(L"UnitAbbreviation_Hour"),
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Millisecond, GetLocalizedStringName(L"UnitName_Millisecond"), GetLocalizedStringName(L"UnitAbbreviation_Millisecond"), 2 }); 5, true, false, false });
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Minute, GetLocalizedStringName(L"UnitName_Minute"), GetLocalizedStringName(L"UnitAbbreviation_Minute"), 4 ,false, true, false }); timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Microsecond, GetLocalizedStringName(L"UnitName_Microsecond"),
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Second, GetLocalizedStringName(L"UnitName_Second"), GetLocalizedStringName(L"UnitAbbreviation_Second"), 3 }); GetLocalizedStringName(L"UnitAbbreviation_Microsecond"), 1 });
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Week, GetLocalizedStringName(L"UnitName_Week"), GetLocalizedStringName(L"UnitAbbreviation_Week"), 7 }); timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Millisecond, GetLocalizedStringName(L"UnitName_Millisecond"),
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Year, GetLocalizedStringName(L"UnitName_Year"), GetLocalizedStringName(L"UnitAbbreviation_Year"), 8 }); GetLocalizedStringName(L"UnitAbbreviation_Millisecond"), 2 });
timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Minute, GetLocalizedStringName(L"UnitName_Minute"),
GetLocalizedStringName(L"UnitAbbreviation_Minute"), 4, false, true, false });
timeUnits.push_back(
OrderedUnit{ UnitConverterUnits::Time_Second, GetLocalizedStringName(L"UnitName_Second"), GetLocalizedStringName(L"UnitAbbreviation_Second"), 3 });
timeUnits.push_back(
OrderedUnit{ UnitConverterUnits::Time_Week, GetLocalizedStringName(L"UnitName_Week"), GetLocalizedStringName(L"UnitAbbreviation_Week"), 7 });
timeUnits.push_back(
OrderedUnit{ UnitConverterUnits::Time_Year, GetLocalizedStringName(L"UnitName_Year"), GetLocalizedStringName(L"UnitAbbreviation_Year"), 8 });
unitMap.emplace(ViewMode::Time, timeUnits); unitMap.emplace(ViewMode::Time, timeUnits);
vector<OrderedUnit> speedUnits; vector<OrderedUnit> speedUnits;
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_CentimetersPerSecond, GetLocalizedStringName(L"UnitName_CentimetersPerSecond"), GetLocalizedStringName(L"UnitAbbreviation_CentimetersPerSecond"), 1 }); speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_CentimetersPerSecond, GetLocalizedStringName(L"UnitName_CentimetersPerSecond"),
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_FeetPerSecond, GetLocalizedStringName(L"UnitName_FeetPerSecond"), GetLocalizedStringName(L"UnitAbbreviation_FeetPerSecond"), 4 }); GetLocalizedStringName(L"UnitAbbreviation_CentimetersPerSecond"), 1 });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_KilometersPerHour, GetLocalizedStringName(L"UnitName_KilometersPerHour"), GetLocalizedStringName(L"UnitAbbreviation_KilometersPerHour"), 3 , useUSCustomary, useSI, false }); speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_FeetPerSecond, GetLocalizedStringName(L"UnitName_FeetPerSecond"),
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Knot, GetLocalizedStringName(L"UnitName_Knot"), GetLocalizedStringName(L"UnitAbbreviation_Knot"), 6 }); GetLocalizedStringName(L"UnitAbbreviation_FeetPerSecond"), 4 });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Mach, GetLocalizedStringName(L"UnitName_Mach"), GetLocalizedStringName(L"UnitAbbreviation_Mach"), 7 }); speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_KilometersPerHour, GetLocalizedStringName(L"UnitName_KilometersPerHour"),
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_MetersPerSecond, GetLocalizedStringName(L"UnitName_MetersPerSecond"), GetLocalizedStringName(L"UnitAbbreviation_MetersPerSecond"), 2 }); GetLocalizedStringName(L"UnitAbbreviation_KilometersPerHour"), 3, useUSCustomary, useSI, false });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_MilesPerHour, GetLocalizedStringName(L"UnitName_MilesPerHour"), GetLocalizedStringName(L"UnitAbbreviation_MilesPerHour"), 5, useSI, useUSCustomary, false }); speedUnits.push_back(
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Turtle, GetLocalizedStringName(L"UnitName_Turtle"), GetLocalizedStringName(L"UnitAbbreviation_Turtle"), 8 ,false, false, true }); OrderedUnit{ UnitConverterUnits::Speed_Knot, GetLocalizedStringName(L"UnitName_Knot"), GetLocalizedStringName(L"UnitAbbreviation_Knot"), 6 });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Horse, GetLocalizedStringName(L"UnitName_Horse"), GetLocalizedStringName(L"UnitAbbreviation_Horse"),9 , false, false, true }); speedUnits.push_back(
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Jet, GetLocalizedStringName(L"UnitName_Jet"), GetLocalizedStringName(L"UnitAbbreviation_Jet"), 10, false, false, true }); OrderedUnit{ UnitConverterUnits::Speed_Mach, GetLocalizedStringName(L"UnitName_Mach"), GetLocalizedStringName(L"UnitAbbreviation_Mach"), 7 });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_MetersPerSecond, GetLocalizedStringName(L"UnitName_MetersPerSecond"),
GetLocalizedStringName(L"UnitAbbreviation_MetersPerSecond"), 2 });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_MilesPerHour, GetLocalizedStringName(L"UnitName_MilesPerHour"),
GetLocalizedStringName(L"UnitAbbreviation_MilesPerHour"), 5, useSI, useUSCustomary, false });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Turtle, GetLocalizedStringName(L"UnitName_Turtle"),
GetLocalizedStringName(L"UnitAbbreviation_Turtle"), 8, false, false, true });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Horse, GetLocalizedStringName(L"UnitName_Horse"),
GetLocalizedStringName(L"UnitAbbreviation_Horse"), 9, false, false, true });
speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_Jet, GetLocalizedStringName(L"UnitName_Jet"), GetLocalizedStringName(L"UnitAbbreviation_Jet"),
10, false, false, true });
unitMap.emplace(ViewMode::Speed, speedUnits); unitMap.emplace(ViewMode::Speed, speedUnits);
vector<OrderedUnit> volumeUnits; vector<OrderedUnit> volumeUnits;
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicCentimeter, GetLocalizedStringName(L"UnitName_CubicCentimeter"), GetLocalizedStringName(L"UnitAbbreviation_CubicCentimeter"), 2 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicCentimeter, GetLocalizedStringName(L"UnitName_CubicCentimeter"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicFoot, GetLocalizedStringName(L"UnitName_CubicFoot"), GetLocalizedStringName(L"UnitAbbreviation_CubicFoot"), 13 }); GetLocalizedStringName(L"UnitAbbreviation_CubicCentimeter"), 2 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicInch, GetLocalizedStringName(L"UnitName_CubicInch"), GetLocalizedStringName(L"UnitAbbreviation_CubicInch"), 12 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicFoot, GetLocalizedStringName(L"UnitName_CubicFoot"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicMeter, GetLocalizedStringName(L"UnitName_CubicMeter"), GetLocalizedStringName(L"UnitAbbreviation_CubicMeter"), 4 }); GetLocalizedStringName(L"UnitAbbreviation_CubicFoot"), 13 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicYard, GetLocalizedStringName(L"UnitName_CubicYard"), GetLocalizedStringName(L"UnitAbbreviation_CubicYard"), 14 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicInch, GetLocalizedStringName(L"UnitName_CubicInch"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CupUS, GetLocalizedStringName(L"UnitName_CupUS"), GetLocalizedStringName(L"UnitAbbreviation_CupUS"), 8 }); GetLocalizedStringName(L"UnitAbbreviation_CubicInch"), 12 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUK, GetLocalizedStringName(L"UnitName_FluidOunceUK"), GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUK"), 17 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicMeter, GetLocalizedStringName(L"UnitName_CubicMeter"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUS, GetLocalizedStringName(L"UnitName_FluidOunceUS"), GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUS"), 7 }); GetLocalizedStringName(L"UnitAbbreviation_CubicMeter"), 4 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUK, GetLocalizedStringName(L"UnitName_GallonUK"), GetLocalizedStringName(L"UnitAbbreviation_GallonUK"), 20 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicYard, GetLocalizedStringName(L"UnitName_CubicYard"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUS, GetLocalizedStringName(L"UnitName_GallonUS"), GetLocalizedStringName(L"UnitAbbreviation_GallonUS"), 11 }); GetLocalizedStringName(L"UnitAbbreviation_CubicYard"), 14 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Liter, GetLocalizedStringName(L"UnitName_Liter"), GetLocalizedStringName(L"UnitAbbreviation_Liter"), 3 }); volumeUnits.push_back(
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Milliliter, GetLocalizedStringName(L"UnitName_Milliliter"), GetLocalizedStringName(L"UnitAbbreviation_Milliliter"), 1, useUSCustomary, useSI}); OrderedUnit{ UnitConverterUnits::Volume_CupUS, GetLocalizedStringName(L"UnitName_CupUS"), GetLocalizedStringName(L"UnitAbbreviation_CupUS"), 8 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_PintUK, GetLocalizedStringName(L"UnitName_PintUK"), GetLocalizedStringName(L"UnitAbbreviation_PintUK"), 18 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUK, GetLocalizedStringName(L"UnitName_FluidOunceUK"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_PintUS, GetLocalizedStringName(L"UnitName_PintUS"), GetLocalizedStringName(L"UnitAbbreviation_PintUS"), 9 }); GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUK"), 17 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TablespoonUS, GetLocalizedStringName(L"UnitName_TablespoonUS"), GetLocalizedStringName(L"UnitAbbreviation_TablespoonUS"), 6 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUS, GetLocalizedStringName(L"UnitName_FluidOunceUS"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TeaspoonUS, GetLocalizedStringName(L"UnitName_TeaspoonUS"), GetLocalizedStringName(L"UnitAbbreviation_TeaspoonUS"), 5, useSI, useUSCustomary && m_currentRegionCode != "GB" }); GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUS"), 7 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_QuartUK, GetLocalizedStringName(L"UnitName_QuartUK"), GetLocalizedStringName(L"UnitAbbreviation_QuartUK"), 19 }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUK, GetLocalizedStringName(L"UnitName_GallonUK"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_QuartUS, GetLocalizedStringName(L"UnitName_QuartUS"), GetLocalizedStringName(L"UnitAbbreviation_QuartUS"), 10 }); GetLocalizedStringName(L"UnitAbbreviation_GallonUK"), 20 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TeaspoonUK, GetLocalizedStringName(L"UnitName_TeaspoonUK"), GetLocalizedStringName(L"UnitAbbreviation_TeaspoonUK"), 15, false, useUSCustomary && m_currentRegionCode == "GB"}); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUS, GetLocalizedStringName(L"UnitName_GallonUS"),
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TablespoonUK, GetLocalizedStringName(L"UnitName_TablespoonUK"), GetLocalizedStringName(L"UnitAbbreviation_TablespoonUK"), 16 }); GetLocalizedStringName(L"UnitAbbreviation_GallonUS"), 11 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CoffeeCup, GetLocalizedStringName(L"UnitName_CoffeeCup"), GetLocalizedStringName(L"UnitAbbreviation_CoffeeCup"), 22 ,false, false, true }); volumeUnits.push_back(
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Bathtub, GetLocalizedStringName(L"UnitName_Bathtub"), GetLocalizedStringName(L"UnitAbbreviation_Bathtub"), 23 ,false, false, true}); OrderedUnit{ UnitConverterUnits::Volume_Liter, GetLocalizedStringName(L"UnitName_Liter"), GetLocalizedStringName(L"UnitAbbreviation_Liter"), 3 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_SwimmingPool, GetLocalizedStringName(L"UnitName_SwimmingPool"), GetLocalizedStringName(L"UnitAbbreviation_SwimmingPool"), 24 ,false, false, true }); volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Milliliter, GetLocalizedStringName(L"UnitName_Milliliter"),
GetLocalizedStringName(L"UnitAbbreviation_Milliliter"), 1, useUSCustomary, useSI });
volumeUnits.push_back(
OrderedUnit{ UnitConverterUnits::Volume_PintUK, GetLocalizedStringName(L"UnitName_PintUK"), GetLocalizedStringName(L"UnitAbbreviation_PintUK"), 18 });
volumeUnits.push_back(
OrderedUnit{ UnitConverterUnits::Volume_PintUS, GetLocalizedStringName(L"UnitName_PintUS"), GetLocalizedStringName(L"UnitAbbreviation_PintUS"), 9 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TablespoonUS, GetLocalizedStringName(L"UnitName_TablespoonUS"),
GetLocalizedStringName(L"UnitAbbreviation_TablespoonUS"), 6 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TeaspoonUS, GetLocalizedStringName(L"UnitName_TeaspoonUS"),
GetLocalizedStringName(L"UnitAbbreviation_TeaspoonUS"), 5, useSI, useUSCustomary && m_currentRegionCode != "GB" });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_QuartUK, GetLocalizedStringName(L"UnitName_QuartUK"),
GetLocalizedStringName(L"UnitAbbreviation_QuartUK"), 19 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_QuartUS, GetLocalizedStringName(L"UnitName_QuartUS"),
GetLocalizedStringName(L"UnitAbbreviation_QuartUS"), 10 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TeaspoonUK, GetLocalizedStringName(L"UnitName_TeaspoonUK"),
GetLocalizedStringName(L"UnitAbbreviation_TeaspoonUK"), 15, false, useUSCustomary && m_currentRegionCode == "GB" });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_TablespoonUK, GetLocalizedStringName(L"UnitName_TablespoonUK"),
GetLocalizedStringName(L"UnitAbbreviation_TablespoonUK"), 16 });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CoffeeCup, GetLocalizedStringName(L"UnitName_CoffeeCup"),
GetLocalizedStringName(L"UnitAbbreviation_CoffeeCup"), 22, false, false, true });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Bathtub, GetLocalizedStringName(L"UnitName_Bathtub"),
GetLocalizedStringName(L"UnitAbbreviation_Bathtub"), 23, false, false, true });
volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_SwimmingPool, GetLocalizedStringName(L"UnitName_SwimmingPool"),
GetLocalizedStringName(L"UnitAbbreviation_SwimmingPool"), 24, false, false, true });
unitMap.emplace(ViewMode::Volume, volumeUnits); unitMap.emplace(ViewMode::Volume, volumeUnits);
vector<OrderedUnit> weightUnits; vector<OrderedUnit> weightUnits;
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Carat, GetLocalizedStringName(L"UnitName_Carat"), GetLocalizedStringName(L"UnitAbbreviation_Carat"), 1 }); weightUnits.push_back(
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Centigram, GetLocalizedStringName(L"UnitName_Centigram"), GetLocalizedStringName(L"UnitAbbreviation_Centigram"), 3 }); OrderedUnit{ UnitConverterUnits::Weight_Carat, GetLocalizedStringName(L"UnitName_Carat"), GetLocalizedStringName(L"UnitAbbreviation_Carat"), 1 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decigram, GetLocalizedStringName(L"UnitName_Decigram"), GetLocalizedStringName(L"UnitAbbreviation_Decigram"), 4 }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Centigram, GetLocalizedStringName(L"UnitName_Centigram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decagram, GetLocalizedStringName(L"UnitName_Decagram"), GetLocalizedStringName(L"UnitAbbreviation_Decagram"), 6 }); GetLocalizedStringName(L"UnitAbbreviation_Centigram"), 3 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Gram, GetLocalizedStringName(L"UnitName_Gram"), GetLocalizedStringName(L"UnitAbbreviation_Gram"), 5 }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decigram, GetLocalizedStringName(L"UnitName_Decigram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Hectogram, GetLocalizedStringName(L"UnitName_Hectogram"), GetLocalizedStringName(L"UnitAbbreviation_Hectogram"), 7 }); GetLocalizedStringName(L"UnitAbbreviation_Decigram"), 4 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Kilogram, GetLocalizedStringName(L"UnitName_Kilogram"), GetLocalizedStringName(L"UnitAbbreviation_Kilogram"), 8 , useUSCustomary, useSI}); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decagram, GetLocalizedStringName(L"UnitName_Decagram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_LongTon, GetLocalizedStringName(L"UnitName_LongTon"), GetLocalizedStringName(L"UnitAbbreviation_LongTon"), 14 }); GetLocalizedStringName(L"UnitAbbreviation_Decagram"), 6 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Milligram, GetLocalizedStringName(L"UnitName_Milligram"), GetLocalizedStringName(L"UnitAbbreviation_Milligram"), 2 }); weightUnits.push_back(
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Ounce, GetLocalizedStringName(L"UnitName_Ounce"), GetLocalizedStringName(L"UnitAbbreviation_Ounce"), 10 }); OrderedUnit{ UnitConverterUnits::Weight_Gram, GetLocalizedStringName(L"UnitName_Gram"), GetLocalizedStringName(L"UnitAbbreviation_Gram"), 5 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Pound, GetLocalizedStringName(L"UnitName_Pound"), GetLocalizedStringName(L"UnitAbbreviation_Pound"), 11 , useSI, useUSCustomary }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Hectogram, GetLocalizedStringName(L"UnitName_Hectogram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_ShortTon, GetLocalizedStringName(L"UnitName_ShortTon"), GetLocalizedStringName(L"UnitAbbreviation_ShortTon"), 13 }); GetLocalizedStringName(L"UnitAbbreviation_Hectogram"), 7 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Stone, GetLocalizedStringName(L"UnitName_Stone"), GetLocalizedStringName(L"UnitAbbreviation_Stone"), 12 }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Kilogram, GetLocalizedStringName(L"UnitName_Kilogram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Tonne, GetLocalizedStringName(L"UnitName_Tonne"), GetLocalizedStringName(L"UnitAbbreviation_Tonne"), 9 }); GetLocalizedStringName(L"UnitAbbreviation_Kilogram"), 8, useUSCustomary, useSI });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Snowflake, GetLocalizedStringName(L"UnitName_Snowflake"), GetLocalizedStringName(L"UnitAbbreviation_Snowflake"), 15 ,false, false, true }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_LongTon, GetLocalizedStringName(L"UnitName_LongTon"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_SoccerBall, GetLocalizedStringName(L"UnitName_SoccerBall"), GetLocalizedStringName(L"UnitAbbreviation_SoccerBall"), 16 , false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_LongTon"), 14 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Elephant, GetLocalizedStringName(L"UnitName_Elephant"), GetLocalizedStringName(L"UnitAbbreviation_Elephant"), 17 ,false, false, true }); weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Milligram, GetLocalizedStringName(L"UnitName_Milligram"),
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Whale, GetLocalizedStringName(L"UnitName_Whale"), GetLocalizedStringName(L"UnitAbbreviation_Whale"), 18 ,false, false, true }); GetLocalizedStringName(L"UnitAbbreviation_Milligram"), 2 });
weightUnits.push_back(
OrderedUnit{ UnitConverterUnits::Weight_Ounce, GetLocalizedStringName(L"UnitName_Ounce"), GetLocalizedStringName(L"UnitAbbreviation_Ounce"), 10 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Pound, GetLocalizedStringName(L"UnitName_Pound"),
GetLocalizedStringName(L"UnitAbbreviation_Pound"), 11, useSI, useUSCustomary });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_ShortTon, GetLocalizedStringName(L"UnitName_ShortTon"),
GetLocalizedStringName(L"UnitAbbreviation_ShortTon"), 13 });
weightUnits.push_back(
OrderedUnit{ UnitConverterUnits::Weight_Stone, GetLocalizedStringName(L"UnitName_Stone"), GetLocalizedStringName(L"UnitAbbreviation_Stone"), 12 });
weightUnits.push_back(
OrderedUnit{ UnitConverterUnits::Weight_Tonne, GetLocalizedStringName(L"UnitName_Tonne"), GetLocalizedStringName(L"UnitAbbreviation_Tonne"), 9 });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Snowflake, GetLocalizedStringName(L"UnitName_Snowflake"),
GetLocalizedStringName(L"UnitAbbreviation_Snowflake"), 15, false, false, true });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_SoccerBall, GetLocalizedStringName(L"UnitName_SoccerBall"),
GetLocalizedStringName(L"UnitAbbreviation_SoccerBall"), 16, false, false, true });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Elephant, GetLocalizedStringName(L"UnitName_Elephant"),
GetLocalizedStringName(L"UnitAbbreviation_Elephant"), 17, false, false, true });
weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Whale, GetLocalizedStringName(L"UnitName_Whale"),
GetLocalizedStringName(L"UnitAbbreviation_Whale"), 18, false, false, true });
unitMap.emplace(ViewMode::Weight, weightUnits); unitMap.emplace(ViewMode::Weight, weightUnits);
vector<OrderedUnit> pressureUnits; vector<OrderedUnit> pressureUnits;
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_Atmosphere, GetLocalizedStringName(L"UnitName_Atmosphere"), GetLocalizedStringName(L"UnitAbbreviation_Atmosphere"), 1 , true, false, false }); pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_Atmosphere, GetLocalizedStringName(L"UnitName_Atmosphere"),
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_Bar, GetLocalizedStringName(L"UnitName_Bar"), GetLocalizedStringName(L"UnitAbbreviation_Bar"), 2, false, true, false}); GetLocalizedStringName(L"UnitAbbreviation_Atmosphere"), 1, true, false, false });
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_KiloPascal, GetLocalizedStringName(L"UnitName_KiloPascal"), GetLocalizedStringName(L"UnitAbbreviation_KiloPascal"), 3 }); pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_Bar, GetLocalizedStringName(L"UnitName_Bar"),
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_MillimeterOfMercury, GetLocalizedStringName(L"UnitName_MillimeterOfMercury "), GetLocalizedStringName(L"UnitAbbreviation_MillimeterOfMercury "), 4 }); GetLocalizedStringName(L"UnitAbbreviation_Bar"), 2, false, true, false });
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_Pascal, GetLocalizedStringName(L"UnitName_Pascal"), GetLocalizedStringName(L"UnitAbbreviation_Pascal"), 5 }); pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_KiloPascal, GetLocalizedStringName(L"UnitName_KiloPascal"),
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_PSI, GetLocalizedStringName(L"UnitName_PSI"), GetLocalizedStringName(L"UnitAbbreviation_PSI"), 6, false, false, false }); GetLocalizedStringName(L"UnitAbbreviation_KiloPascal"), 3 });
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_MillimeterOfMercury, GetLocalizedStringName(L"UnitName_MillimeterOfMercury "),
GetLocalizedStringName(L"UnitAbbreviation_MillimeterOfMercury "), 4 });
pressureUnits.push_back(
OrderedUnit{ UnitConverterUnits::Pressure_Pascal, GetLocalizedStringName(L"UnitName_Pascal"), GetLocalizedStringName(L"UnitAbbreviation_Pascal"), 5 });
pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_PSI, GetLocalizedStringName(L"UnitName_PSI"),
GetLocalizedStringName(L"UnitAbbreviation_PSI"), 6, false, false, false });
unitMap.emplace(ViewMode::Pressure, pressureUnits); unitMap.emplace(ViewMode::Pressure, pressureUnits);
vector<OrderedUnit> angleUnits; vector<OrderedUnit> angleUnits;
angleUnits.push_back(OrderedUnit{ UnitConverterUnits::Angle_Degree, GetLocalizedStringName(L"UnitName_Degree"), GetLocalizedStringName(L"UnitAbbreviation_Degree"), 1, true, false, false }); angleUnits.push_back(OrderedUnit{ UnitConverterUnits::Angle_Degree, GetLocalizedStringName(L"UnitName_Degree"),
angleUnits.push_back(OrderedUnit{ UnitConverterUnits::Angle_Radian, GetLocalizedStringName(L"UnitName_Radian"), GetLocalizedStringName(L"UnitAbbreviation_Radian"), 2, false, true, false }); GetLocalizedStringName(L"UnitAbbreviation_Degree"), 1, true, false, false });
angleUnits.push_back(OrderedUnit{ UnitConverterUnits::Angle_Gradian, GetLocalizedStringName(L"UnitName_Gradian"), GetLocalizedStringName(L"UnitAbbreviation_Gradian"), 3}); angleUnits.push_back(OrderedUnit{ UnitConverterUnits::Angle_Radian, GetLocalizedStringName(L"UnitName_Radian"),
GetLocalizedStringName(L"UnitAbbreviation_Radian"), 2, false, true, false });
angleUnits.push_back(
OrderedUnit{ UnitConverterUnits::Angle_Gradian, GetLocalizedStringName(L"UnitName_Gradian"), GetLocalizedStringName(L"UnitAbbreviation_Gradian"), 3 });
unitMap.emplace(ViewMode::Angle, angleUnits); unitMap.emplace(ViewMode::Angle, angleUnits);
} }
void UnitConverterDataLoader::GetConversionData(_In_ unordered_map<ViewMode, unordered_map<int, double>>& categoryToUnitConversionMap) void UnitConverterDataLoader::GetConversionData(_In_ unordered_map<ViewMode, unordered_map<int, double>>& categoryToUnitConversionMap)
{ {
/*categoryId, UnitId, factor*/ /*categoryId, UnitId, factor*/
static const vector<UnitData> unitDataList = { static const vector<UnitData> unitDataList = { { ViewMode::Area, UnitConverterUnits::Area_Acre, 4046.8564224 },
{ ViewMode::Area, UnitConverterUnits::Area_Acre, 4046.8564224 },
{ ViewMode::Area, UnitConverterUnits::Area_SquareMeter, 1 }, { ViewMode::Area, UnitConverterUnits::Area_SquareMeter, 1 },
{ ViewMode::Area, UnitConverterUnits::Area_SquareFoot, 0.09290304 }, { ViewMode::Area, UnitConverterUnits::Area_SquareFoot, 0.09290304 },
{ ViewMode::Area, UnitConverterUnits::Area_SquareYard, 0.83612736 }, { ViewMode::Area, UnitConverterUnits::Area_SquareYard, 0.83612736 },
@ -546,8 +691,7 @@ void UnitConverterDataLoader::GetConversionData(_In_ unordered_map<ViewMode, uno
{ ViewMode::Pressure, UnitConverterUnits::Pressure_KiloPascal, 0.0098692326671601 }, { ViewMode::Pressure, UnitConverterUnits::Pressure_KiloPascal, 0.0098692326671601 },
{ ViewMode::Pressure, UnitConverterUnits::Pressure_MillimeterOfMercury, 0.0013155687145324 }, { ViewMode::Pressure, UnitConverterUnits::Pressure_MillimeterOfMercury, 0.0013155687145324 },
{ ViewMode::Pressure, UnitConverterUnits::Pressure_Pascal, 9.869232667160128e-6 }, { ViewMode::Pressure, UnitConverterUnits::Pressure_Pascal, 9.869232667160128e-6 },
{ ViewMode::Pressure, UnitConverterUnits::Pressure_PSI, 0.068045961016531 } { ViewMode::Pressure, UnitConverterUnits::Pressure_PSI, 0.068045961016531 } };
};
// Populate the hash map and return; // Populate the hash map and return;
for (UnitData unitdata : unitDataList) for (UnitData unitdata : unitDataList)
@ -577,10 +721,13 @@ void UnitConverterDataLoader::GetConversionData(_In_ unordered_map<ViewMode, uno
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_DegreesCelsius, 1, 0 }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_DegreesCelsius, 1, 0 },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_DegreesFahrenheit, 1.8, 32 }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_DegreesFahrenheit, 1.8, 32 },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_Kelvin, 1, 273.15 }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesCelsius, UnitConverterUnits::Temperature_Kelvin, 1, 273.15 },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_DegreesCelsius, 0.55555555555555555555555555555556, -32, CONVERT_WITH_OFFSET_FIRST }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_DegreesCelsius,
0.55555555555555555555555555555556, -32, CONVERT_WITH_OFFSET_FIRST },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_DegreesFahrenheit, 1, 0 }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_DegreesFahrenheit, 1, 0 },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_Kelvin, 0.55555555555555555555555555555556, 459.67, CONVERT_WITH_OFFSET_FIRST }, { ViewMode::Temperature, UnitConverterUnits::Temperature_DegreesFahrenheit, UnitConverterUnits::Temperature_Kelvin, 0.55555555555555555555555555555556,
{ ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_DegreesCelsius, 1, -273.15, CONVERT_WITH_OFFSET_FIRST }, 459.67, CONVERT_WITH_OFFSET_FIRST },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_DegreesCelsius, 1, -273.15,
CONVERT_WITH_OFFSET_FIRST },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_DegreesFahrenheit, 1.8, -459.67 }, { ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_DegreesFahrenheit, 1.8, -459.67 },
{ ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_Kelvin, 1, 0 } { ViewMode::Temperature, UnitConverterUnits::Temperature_Kelvin, UnitConverterUnits::Temperature_Kelvin, 1, 0 }
}; };

View file

@ -12,9 +12,12 @@ namespace CalculatorApp
{ {
struct OrderedUnit : UnitConversionManager::Unit struct OrderedUnit : UnitConversionManager::Unit
{ {
OrderedUnit(){} OrderedUnit()
{
}
OrderedUnit(int id, std::wstring name, std::wstring abbreviation, int order, bool isConversionSource = false, bool isConversionTarget = false, bool isWhimsical = false) OrderedUnit(int id, std::wstring name, std::wstring abbreviation, int order, bool isConversionSource = false, bool isConversionTarget = false,
bool isWhimsical = false)
: UnitConversionManager::Unit(id, name, abbreviation, isConversionSource, isConversionTarget, isWhimsical), order(order) : UnitConversionManager::Unit(id, name, abbreviation, isConversionSource, isConversionTarget, isWhimsical), order(order)
{ {
} }
@ -31,11 +34,13 @@ namespace CalculatorApp
struct ExplicitUnitConversionData : UnitConversionManager::ConversionData struct ExplicitUnitConversionData : UnitConversionManager::ConversionData
{ {
ExplicitUnitConversionData(){} ExplicitUnitConversionData()
ExplicitUnitConversionData(CalculatorApp::Common::ViewMode categoryId, int parentUnitId, int unitId, double ratio, double offset, bool offsetFirst = false) : {
categoryId(categoryId), parentUnitId(parentUnitId), unitId(unitId), UnitConversionManager::ConversionData(ratio, offset, offsetFirst) }
ExplicitUnitConversionData(CalculatorApp::Common::ViewMode categoryId, int parentUnitId, int unitId, double ratio, double offset,
bool offsetFirst = false)
: categoryId(categoryId), parentUnitId(parentUnitId), unitId(unitId), UnitConversionManager::ConversionData(ratio, offset, offsetFirst)
{ {
} }
CalculatorApp::Common::ViewMode categoryId; CalculatorApp::Common::ViewMode categoryId;
@ -43,8 +48,7 @@ namespace CalculatorApp
int unitId; int unitId;
}; };
class UnitConverterDataLoader : public UnitConversionManager::IConverterDataLoader, class UnitConverterDataLoader : public UnitConversionManager::IConverterDataLoader, public std::enable_shared_from_this<UnitConverterDataLoader>
public std::enable_shared_from_this<UnitConverterDataLoader>
{ {
public: public:
UnitConverterDataLoader(Windows::Globalization::GeographicRegion ^ region); UnitConverterDataLoader(Windows::Globalization::GeographicRegion ^ region);
@ -54,14 +58,16 @@ namespace CalculatorApp
void LoadData() override; void LoadData() override;
std::vector<UnitConversionManager::Category> LoadOrderedCategories() override; std::vector<UnitConversionManager::Category> LoadOrderedCategories() override;
std::vector<UnitConversionManager::Unit> LoadOrderedUnits(const UnitConversionManager::Category& c) override; std::vector<UnitConversionManager::Unit> LoadOrderedUnits(const UnitConversionManager::Category& c) override;
std::unordered_map<UnitConversionManager::Unit, UnitConversionManager::ConversionData, UnitConversionManager::UnitHash> LoadOrderedRatios(const UnitConversionManager::Unit& unit) override; std::unordered_map<UnitConversionManager::Unit, UnitConversionManager::ConversionData, UnitConversionManager::UnitHash>
LoadOrderedRatios(const UnitConversionManager::Unit& unit) override;
bool SupportsCategory(const UnitConversionManager::Category& target) override; bool SupportsCategory(const UnitConversionManager::Category& target) override;
// IConverterDataLoader // IConverterDataLoader
void GetCategories(_In_ std::shared_ptr<std::vector<UnitConversionManager::Category>> categoriesList); void GetCategories(_In_ std::shared_ptr<std::vector<UnitConversionManager::Category>> categoriesList);
void GetUnits(_In_ std::unordered_map<CalculatorApp::Common::ViewMode, std::vector<CalculatorApp::ViewModel::OrderedUnit>>& unitMap); void GetUnits(_In_ std::unordered_map<CalculatorApp::Common::ViewMode, std::vector<CalculatorApp::ViewModel::OrderedUnit>>& unitMap);
void GetConversionData(_In_ std::unordered_map<CalculatorApp::Common::ViewMode, std::unordered_map<int, double>>& categoryToUnitConversionMap); void GetConversionData(_In_ std::unordered_map<CalculatorApp::Common::ViewMode, std::unordered_map<int, double>>& categoryToUnitConversionMap);
void GetExplicitConversionData(_In_ std::unordered_map<int, std::unordered_map<int, UnitConversionManager::ConversionData>>& unitToUnitConversionList); void
GetExplicitConversionData(_In_ std::unordered_map<int, std::unordered_map<int, UnitConversionManager::ConversionData>>& unitToUnitConversionList);
std::wstring GetLocalizedStringName(_In_ Platform::String ^ stringId); std::wstring GetLocalizedStringName(_In_ Platform::String ^ stringId);

View file

@ -32,18 +32,18 @@ namespace
StringReference IsDiffInDaysPropertyName(L"IsDiffInDays"); StringReference IsDiffInDaysPropertyName(L"IsDiffInDays");
} }
DateCalculatorViewModel::DateCalculatorViewModel() : DateCalculatorViewModel::DateCalculatorViewModel()
m_IsDateDiffMode(true), : m_IsDateDiffMode(true)
m_IsAddMode(true), , m_IsAddMode(true)
m_isOutOfBound(false), , m_isOutOfBound(false)
m_DaysOffset(0), , m_DaysOffset(0)
m_MonthsOffset(0), , m_MonthsOffset(0)
m_YearsOffset(0), , m_YearsOffset(0)
m_StrDateDiffResult(L""), , m_StrDateDiffResult(L"")
m_StrDateDiffResultAutomationName(L""), , m_StrDateDiffResultAutomationName(L"")
m_StrDateDiffResultInDays(L""), , m_StrDateDiffResultInDays(L"")
m_StrDateResult(L""), , m_StrDateResult(L"")
m_StrDateResultAutomationName(L"") , m_StrDateResultAutomationName(L"")
{ {
const auto& localizationSettings = LocalizationSettings::GetInstance(); const auto& localizationSettings = LocalizationSettings::GetInstance();
@ -105,10 +105,8 @@ void DateCalculatorViewModel::OnPropertyChanged(_In_ String^ prop)
{ {
UpdateStrDateResultAutomationName(); UpdateStrDateResultAutomationName();
} }
else if (prop != StrDateDiffResultAutomationNamePropertyName else if (prop != StrDateDiffResultAutomationNamePropertyName && prop != StrDateDiffResultInDaysPropertyName
&& prop != StrDateDiffResultInDaysPropertyName && prop != StrDateResultAutomationNamePropertyName && prop != IsDiffInDaysPropertyName)
&& prop != StrDateResultAutomationNamePropertyName
&& prop != IsDiffInDaysPropertyName)
{ {
OnInputsChanged(); OnInputsChanged();
} }
@ -167,9 +165,7 @@ void DateCalculatorViewModel::UpdateDisplayResult()
StrDateDiffResultInDays = L""; StrDateDiffResultInDays = L"";
StrDateDiffResult = AppResourceProvider::GetInstance().GetResourceString(L"Date_SameDates"); StrDateDiffResult = AppResourceProvider::GetInstance().GetResourceString(L"Date_SameDates");
} }
else if ((m_dateDiffResult.year == 0) && else if ((m_dateDiffResult.year == 0) && (m_dateDiffResult.month == 0) && (m_dateDiffResult.week == 0))
(m_dateDiffResult.month == 0) &&
(m_dateDiffResult.week == 0))
{ {
IsDiffInDays = true; IsDiffInDays = true;
StrDateDiffResultInDays = L""; StrDateDiffResultInDays = L"";
@ -220,9 +216,7 @@ void DateCalculatorViewModel::UpdateStrDateResultAutomationName()
void DateCalculatorViewModel::InitializeDateOutputFormats(_In_ String ^ calendarIdentifier) void DateCalculatorViewModel::InitializeDateOutputFormats(_In_ String ^ calendarIdentifier)
{ {
// Format for Add/Subtract days // Format for Add/Subtract days
m_dateTimeFormatter = LocalizationService::GetRegionalSettingsAwareDateTimeFormatter( m_dateTimeFormatter = LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(L"longdate", calendarIdentifier,
L"longdate",
calendarIdentifier,
ClockIdentifiers::TwentyFourHour); // Clock Identifier is not used ClockIdentifiers::TwentyFourHour); // Clock Identifier is not used
// Format for Date Difference // Format for Date Difference

View file

@ -12,8 +12,7 @@ namespace CalculatorApp
{ {
namespace ViewModel namespace ViewModel
{ {
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class DateCalculatorViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class DateCalculatorViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
public: public:
DateCalculatorViewModel(); DateCalculatorViewModel();
@ -39,7 +38,10 @@ namespace CalculatorApp
// From date for Date Diff // From date for Date Diff
property Windows::Foundation::DateTime FromDate property Windows::Foundation::DateTime FromDate
{ {
Windows::Foundation::DateTime get() { return m_fromDate; } Windows::Foundation::DateTime get()
{
return m_fromDate;
}
void set(Windows::Foundation::DateTime value) void set(Windows::Foundation::DateTime value)
{ {
@ -54,7 +56,10 @@ namespace CalculatorApp
// To date for Date Diff // To date for Date Diff
property Windows::Foundation::DateTime ToDate property Windows::Foundation::DateTime ToDate
{ {
Windows::Foundation::DateTime get() { return m_toDate; } Windows::Foundation::DateTime get()
{
return m_toDate;
}
void set(Windows::Foundation::DateTime value) void set(Windows::Foundation::DateTime value)
{ {
@ -69,7 +74,10 @@ namespace CalculatorApp
// Start date for Add/Subtract date // Start date for Add/Subtract date
property Windows::Foundation::DateTime StartDate property Windows::Foundation::DateTime StartDate
{ {
Windows::Foundation::DateTime get() { return m_startDate; } Windows::Foundation::DateTime get()
{
return m_startDate;
}
void set(Windows::Foundation::DateTime value) void set(Windows::Foundation::DateTime value)
{ {
@ -106,26 +114,54 @@ namespace CalculatorApp
property bool IsOutOfBound property bool IsOutOfBound
{ {
bool get() { return m_isOutOfBound; } bool get()
void set(bool value) { m_isOutOfBound = value; UpdateDisplayResult(); } {
return m_isOutOfBound;
}
void set(bool value)
{
m_isOutOfBound = value;
UpdateDisplayResult();
}
} }
property CalculatorApp::Common::DateCalculation::DateDifference DateDiffResult property CalculatorApp::Common::DateCalculation::DateDifference DateDiffResult
{ {
CalculatorApp::Common::DateCalculation::DateDifference get() { return m_dateDiffResult; } CalculatorApp::Common::DateCalculation::DateDifference get()
void set(CalculatorApp::Common::DateCalculation::DateDifference value) { m_dateDiffResult = value; UpdateDisplayResult(); } {
return m_dateDiffResult;
}
void set(CalculatorApp::Common::DateCalculation::DateDifference value)
{
m_dateDiffResult = value;
UpdateDisplayResult();
}
} }
property CalculatorApp::Common::DateCalculation::DateDifference DateDiffResultInDays property CalculatorApp::Common::DateCalculation::DateDifference DateDiffResultInDays
{ {
CalculatorApp::Common::DateCalculation::DateDifference get() { return m_dateDiffResultInDays; } CalculatorApp::Common::DateCalculation::DateDifference get()
void set(CalculatorApp::Common::DateCalculation::DateDifference value) { m_dateDiffResultInDays = value; UpdateDisplayResult(); } {
return m_dateDiffResultInDays;
}
void set(CalculatorApp::Common::DateCalculation::DateDifference value)
{
m_dateDiffResultInDays = value;
UpdateDisplayResult();
}
} }
property Windows::Foundation::DateTime DateResult property Windows::Foundation::DateTime DateResult
{ {
Windows::Foundation::DateTime get() { return m_dateResult; } Windows::Foundation::DateTime get()
void set(Windows::Foundation::DateTime value) { m_dateResult = value; UpdateDisplayResult();} {
return m_dateResult;
}
void set(Windows::Foundation::DateTime value)
{
m_dateResult = value;
UpdateDisplayResult();
}
} }
private: private:

View file

@ -10,17 +10,18 @@ using namespace CalculatorApp::ViewModel;
using namespace std; using namespace std;
using namespace Platform; using namespace Platform;
HistoryItemViewModel::HistoryItemViewModel(String ^ expression, String ^ result, _In_ const shared_ptr<CalculatorVector<pair<wstring, int>>>& spTokens,
HistoryItemViewModel::HistoryItemViewModel(String^ expression, String^ result, _In_ const shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>>& spCommands)
_In_ const shared_ptr<CalculatorVector <pair<wstring, int>>> &spTokens, : m_expression(expression), m_result(result), m_spTokens(spTokens), m_spCommands(spCommands)
_In_ const shared_ptr<CalculatorVector<shared_ptr<IExpressionCommand>>> &spCommands) :m_expression(expression), m_result(result), m_spTokens(spTokens), m_spCommands(spCommands)
{ {
// updating accessibility names for expression and result // updating accessibility names for expression and result
m_accExpression = HistoryItemViewModel::GetAccessibleExpressionFromTokens(spTokens, m_expression); m_accExpression = HistoryItemViewModel::GetAccessibleExpressionFromTokens(spTokens, m_expression);
m_accResult = LocalizationService::GetNarratorReadableString(m_result); m_accResult = LocalizationService::GetNarratorReadableString(m_result);
} }
String^ HistoryItemViewModel::GetAccessibleExpressionFromTokens(_In_ shared_ptr< CalculatorVector< pair< wstring, int > > > const &spTokens, _In_ String^ fallbackExpression) String
^ HistoryItemViewModel::GetAccessibleExpressionFromTokens(_In_ shared_ptr<CalculatorVector<pair<wstring, int>>> const& spTokens,
_In_ String ^ fallbackExpression)
{ {
// updating accessibility names for expression and result // updating accessibility names for expression and result
wstringstream accExpression{}; wstringstream accExpression{};

View file

@ -10,14 +10,11 @@ namespace CalculatorApp
{ {
namespace ViewModel namespace ViewModel
{ {
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class HistoryItemViewModel sealed : Windows::UI::Xaml::Data::ICustomPropertyProvider
public ref class HistoryItemViewModel sealed : Windows::UI::Xaml::Data::ICustomPropertyProvider
{ {
internal : internal :
HistoryItemViewModel(Platform::String^ expression, HistoryItemViewModel(Platform::String ^ expression, Platform::String ^ result,
Platform::String^ result,
_In_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& spTokens, _In_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& spTokens,
_In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& spCommands); _In_ std::shared_ptr<CalculatorVector<std::shared_ptr<IExpressionCommand>>> const& spCommands);
@ -32,36 +29,23 @@ namespace CalculatorApp
} }
public: public:
property Platform::String
^ Expression { Platform::String ^ get() { return m_expression; } }
property Platform::String^ Expression property Platform::String
{ ^ AccExpression { Platform::String ^ get() { return m_accExpression; } }
Platform::String^ get() { return m_expression; }
}
property Platform::String^ AccExpression property Platform::String
{ ^ Result { Platform::String ^ get() { return m_result; } }
Platform::String^ get() { return m_accExpression; }
}
property Platform::String^ Result property Platform::String
{ ^ AccResult { Platform::String ^ get() { return m_accResult; } }
Platform::String^ get() { return m_result; }
}
property Platform::String^ AccResult virtual Windows::UI::Xaml::Data::ICustomProperty
{ ^ GetCustomProperty(Platform::String ^ name) { return nullptr; }
Platform::String^ get() { return m_accResult; }
}
virtual Windows::UI::Xaml::Data::ICustomProperty^ GetCustomProperty(Platform::String^ name) virtual Windows::UI::Xaml::Data::ICustomProperty
{ ^ GetIndexedProperty(Platform::String ^ name, Windows::UI::Xaml::Interop::TypeName type) { return nullptr; }
return nullptr;
}
virtual Windows::UI::Xaml::Data::ICustomProperty^ GetIndexedProperty(Platform::String^ name, Windows::UI::Xaml::Interop::TypeName type)
{
return nullptr;
}
virtual property Windows::UI::Xaml::Interop::TypeName Type virtual property Windows::UI::Xaml::Interop::TypeName Type
{ {
@ -71,14 +55,11 @@ namespace CalculatorApp
} }
} }
virtual Platform::String^ GetStringRepresentation() virtual Platform::String
{ ^ GetStringRepresentation() { return m_accExpression + " " + m_accResult; }
return m_accExpression + " " + m_accResult;
}
private: private : static Platform::String
static Platform::String^ GetAccessibleExpressionFromTokens( ^ GetAccessibleExpressionFromTokens(_In_ std::shared_ptr<CalculatorVector<std::pair<std::wstring, int>>> const& spTokens,
_In_ std::shared_ptr<CalculatorVector <std::pair<std::wstring, int>>> const &spTokens,
_In_ Platform::String ^ fallbackExpression); _In_ Platform::String ^ fallbackExpression);
private: private:

View file

@ -26,9 +26,8 @@ namespace CalculatorApp::ViewModel::HistoryResourceKeys
StringReference HistoryCleared(L"HistoryList_Cleared"); StringReference HistoryCleared(L"HistoryList_Cleared");
} }
HistoryViewModel::HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager) : HistoryViewModel::HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager)
m_calculatorManager(calculatorManager), : m_calculatorManager(calculatorManager), m_localizedHistoryCleared(nullptr)
m_localizedHistoryCleared(nullptr)
{ {
AreHistoryShortcutsEnabled = true; AreHistoryShortcutsEnabled = true;
@ -70,8 +69,7 @@ void HistoryViewModel::ReloadHistory(_In_ ViewMode currentMode)
localizer.LocalizeDisplayValue(&expression); localizer.LocalizeDisplayValue(&expression);
localizer.LocalizeDisplayValue(&result); localizer.LocalizeDisplayValue(&result);
auto item = ref new HistoryItemViewModel(ref new Platform::String( expression.c_str()), auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()), ref new Platform::String(result.c_str()),
ref new Platform::String(result.c_str()),
(*ritr)->historyItemVector.spTokens, (*ritr)->historyItemVector.spCommands); (*ritr)->historyItemVector.spTokens, (*ritr)->historyItemVector.spCommands);
historyListVM->Append(item); historyListVM->Append(item);
} }
@ -89,8 +87,7 @@ void HistoryViewModel::OnHistoryItemAdded(_In_ unsigned int addedItemIndex)
wstring result = newItem->historyItemVector.result; wstring result = newItem->historyItemVector.result;
localizer.LocalizeDisplayValue(&expression); localizer.LocalizeDisplayValue(&expression);
localizer.LocalizeDisplayValue(&result); localizer.LocalizeDisplayValue(&result);
auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()), auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()), ref new Platform::String(result.c_str()),
ref new Platform::String(result.c_str()),
newItem->historyItemVector.spTokens, newItem->historyItemVector.spCommands); newItem->historyItemVector.spTokens, newItem->historyItemVector.spCommands);
// check if we have not hit the max items // check if we have not hit the max items
@ -166,7 +163,8 @@ void HistoryViewModel::OnClearCommand(_In_ Platform::Object^ e)
void HistoryViewModel::RestoreHistory(_In_ CalculationManager::CALCULATOR_MODE cMode) void HistoryViewModel::RestoreHistory(_In_ CalculationManager::CALCULATOR_MODE cMode)
{ {
ApplicationDataContainer ^ historyContainer = GetHistoryContainer(cMode); ApplicationDataContainer ^ historyContainer = GetHistoryContainer(cMode);
std::shared_ptr<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>> historyVector = std::make_shared<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>>(); std::shared_ptr<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>> historyVector =
std::make_shared<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>>();
auto historyVectorLength = static_cast<int>(historyContainer->Values->Lookup(HistoryVectorLengthKey)); auto historyVectorLength = static_cast<int>(historyContainer->Values->Lookup(HistoryVectorLengthKey));
bool failure = false; bool failure = false;
@ -312,7 +310,8 @@ Platform::String^ HistoryViewModel::SerializeHistoryItem(_In_ std::shared_ptr<Ca
return CryptographicBuffer::EncodeToBase64String(buffer); return CryptographicBuffer::EncodeToBase64String(buffer);
} }
CalculationManager::HISTORYITEM HistoryViewModel::DeserializeHistoryItem(_In_ Platform::String^ historyItemKey, _In_ ApplicationDataContainer^ historyContainer) CalculationManager::HISTORYITEM HistoryViewModel::DeserializeHistoryItem(_In_ Platform::String ^ historyItemKey,
_In_ ApplicationDataContainer ^ historyContainer)
{ {
CalculationManager::HISTORYITEM historyItem; CalculationManager::HISTORYITEM historyItem;
if (historyContainer->Values->HasKey(historyItemKey)) if (historyContainer->Values->HasKey(historyItemKey))
@ -353,10 +352,8 @@ CalculationManager::HISTORYITEM HistoryViewModel::DeserializeHistoryItem(_In_ Pl
bool HistoryViewModel::IsValid(_In_ CalculationManager::HISTORYITEM item) bool HistoryViewModel::IsValid(_In_ CalculationManager::HISTORYITEM item)
{ {
return (!item.historyItemVector.expression.empty() && return (!item.historyItemVector.expression.empty() && !item.historyItemVector.result.empty() && (bool)item.historyItemVector.spCommands
!item.historyItemVector.result.empty() && && (bool)item.historyItemVector.spTokens);
(bool)item.historyItemVector.spCommands &&
(bool)item.historyItemVector.spTokens);
} }
void HistoryViewModel::UpdateItemSize() void HistoryViewModel::UpdateItemSize()

View file

@ -15,13 +15,13 @@ namespace CalculatorApp
namespace ViewModel namespace ViewModel
{ {
public delegate void HideHistoryClickedHandler(); public
public delegate void HistoryItemClickedHandler(CalculatorApp::ViewModel::HistoryItemViewModel^ e); delegate void HideHistoryClickedHandler();
public
delegate void HistoryItemClickedHandler(CalculatorApp::ViewModel::HistoryItemViewModel ^ e);
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class HistoryViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
public ref class HistoryViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
{ {
public: public:
OBSERVABLE_OBJECT(); OBSERVABLE_OBJECT();
OBSERVABLE_PROPERTY_RW(int, ItemSize); OBSERVABLE_PROPERTY_RW(int, ItemSize);
@ -43,8 +43,7 @@ namespace CalculatorApp
void ClearHistory(); void ClearHistory();
void RestoreCompleteHistory(); void RestoreCompleteHistory();
internal: internal : HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager);
HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager);
void SetCalculatorDisplay(CalculatorDisplay& calculatorDisplay); void SetCalculatorDisplay(CalculatorDisplay& calculatorDisplay);
void ReloadHistory(_In_ CalculatorApp::Common::ViewMode currentMode); void ReloadHistory(_In_ CalculatorApp::Common::ViewMode currentMode);
@ -61,7 +60,8 @@ namespace CalculatorApp
Platform::String ^ m_localizedHistoryCleared; Platform::String ^ m_localizedHistoryCleared;
void RestoreHistory(_In_ CalculationManager::CALCULATOR_MODE cMode); void RestoreHistory(_In_ CalculationManager::CALCULATOR_MODE cMode);
CalculationManager::HISTORYITEM DeserializeHistoryItem(_In_ Platform::String^ historyItemKey, _In_ Windows::Storage::ApplicationDataContainer^ historyContainer); CalculationManager::HISTORYITEM DeserializeHistoryItem(_In_ Platform::String ^ historyItemKey,
_In_ Windows::Storage::ApplicationDataContainer ^ historyContainer);
Windows::Storage::ApplicationDataContainer ^ GetHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode); Windows::Storage::ApplicationDataContainer ^ GetHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode);
Platform::String ^ GetHistoryContainerKey(_In_ CalculationManager::CALCULATOR_MODE cMode); Platform::String ^ GetHistoryContainerKey(_In_ CalculationManager::CALCULATOR_MODE cMode);
void ClearHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode); void ClearHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode);

View file

@ -14,26 +14,22 @@ namespace CalculatorApp
/// <summary> /// <summary>
/// Model representation of a single item in the Memory list /// Model representation of a single item in the Memory list
/// </summary> /// </summary>
[Windows::UI::Xaml::Data::Bindable] [Windows::UI::Xaml::Data::Bindable] public ref class MemoryItemViewModel sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged,
public ref class MemoryItemViewModel sealed :
public Windows::UI::Xaml::Data::INotifyPropertyChanged,
Windows::UI::Xaml::Data::ICustomPropertyProvider Windows::UI::Xaml::Data::ICustomPropertyProvider
{ {
public: public:
MemoryItemViewModel(StandardCalculatorViewModel^ calcVM) : m_Position(-1), m_calcVM(calcVM) {} MemoryItemViewModel(StandardCalculatorViewModel ^ calcVM) : m_Position(-1), m_calcVM(calcVM)
{
}
OBSERVABLE_OBJECT(); OBSERVABLE_OBJECT();
OBSERVABLE_PROPERTY_RW(int, Position); OBSERVABLE_PROPERTY_RW(int, Position);
OBSERVABLE_PROPERTY_RW(Platform::String ^, Value); OBSERVABLE_PROPERTY_RW(Platform::String ^, Value);
virtual Windows::UI::Xaml::Data::ICustomProperty^ GetCustomProperty(Platform::String^ name) virtual Windows::UI::Xaml::Data::ICustomProperty
{ ^ GetCustomProperty(Platform::String ^ name) { return nullptr; }
return nullptr;
}
virtual Windows::UI::Xaml::Data::ICustomProperty^ GetIndexedProperty(Platform::String^ name, Windows::UI::Xaml::Interop::TypeName type) virtual Windows::UI::Xaml::Data::ICustomProperty
{ ^ GetIndexedProperty(Platform::String ^ name, Windows::UI::Xaml::Interop::TypeName type) { return nullptr; }
return nullptr;
}
virtual property Windows::UI::Xaml::Interop::TypeName Type virtual property Windows::UI::Xaml::Interop::TypeName Type
{ {
@ -43,10 +39,8 @@ namespace CalculatorApp
} }
} }
virtual Platform::String^ GetStringRepresentation() virtual Platform::String
{ ^ GetStringRepresentation() { return Value; }
return Value;
}
void Clear(); void Clear();
void MemoryAdd(); void MemoryAdd();

Some files were not shown because too many files have changed in this diff Show more