diff --git a/.clang-format b/.clang-format index 6f60f7bf..16412e51 100644 --- a/.clang-format +++ b/.clang-format @@ -1,11 +1,11 @@ AccessModifierOffset: -4 -AlignAfterOpenBracket: Align +AlignAfterOpenBracket: AlwaysBreak AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Right AlignOperands: true AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None @@ -15,8 +15,8 @@ AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true +BinPackArguments: false +BinPackParameters: false BreakBeforeBinaryOperators: NonAssignment BreakBeforeBraces: Allman BreakBeforeInheritanceComma: false @@ -28,7 +28,7 @@ BreakStringLiterals: true ColumnLimit: 160 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: true -ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: false diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index db98fc73..efff3e1d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -34,9 +34,9 @@ Steps to reproduce the behavior: - OS Build: - Architecture: - Application Version: - - Region: - - Dev Version Installed: - + - Region: + - Dev Version Installed: + + +**Requested Assignment** + +If possible, I would like to fix this. +I'm just reporting this problem. I don't want to fix it. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 0032d0b7..908a643e 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -13,7 +13,7 @@ See https://github.com/Microsoft/calculator/blob/master/docs/NewFeatureProcess.m **Problem Statement** **Evidence or User Insights** @@ -41,3 +41,14 @@ Things we are explicitly not doing or supporting or that are out of scope, inclu + +**Requested Assignment** + +If possible, I would like to implement this. +I'm just suggesting this idea. I don't want to implement it. diff --git a/Tools/Scripts/clang-format/clang-format-all.ps1 b/Tools/Scripts/clang-format/clang-format-all.ps1 new file mode 100644 index 00000000..107f3f2c --- /dev/null +++ b/Tools/Scripts/clang-format/clang-format-all.ps1 @@ -0,0 +1,91 @@ +<# + .DESCRIPTION + Helper script to format all header and source files in the repository. + + By default, the script will recursively search under the repo root for + files to format. Users can give explicit parameters indicating how the + search should include and exclude filetypes. + + If users don't want the search functionality, they can instead provide + an explicit list of files to format. + + .PARAMETER RepoRoot + Full path to the root of the repository which is the target of the search. + Will default to the root of the current working directory. + + .PARAMETER Include + Array of filetype extensions to target for formatting. + By default, targets standard extensions for header and source files. + Follows the same rules as the -Include parameter for Get-ChildItem. + + .PARAMETER Exclude + Array of filetype extensions to exclude from formatting. + By default, excludes generated XAML files. + Follows the same rules as the -Exclude paramter for Get-ChildItem. + + .PARAMETER Files + Array of files to format. The script will exit if one of the provided + filepaths does not exist. + + .EXAMPLE + .\clang-format-all.ps1 + + Formats all header and source files under the repository root. + + .EXAMPLE + .\clang-format-all.ps1 -RepoRoot 'S:\repos\calculator' -Include '*.h', '*.cpp' -Exclude '*.g.*' + + Formats all *.h and *.cpp files under 'S:\repos\calculator', excluding files with an extension + like *.g.* + + .EXAMPLE + .\clang-format-all.ps1 -File 'S:\repos\calculator\src\CalcViewModel\UnitConverterViewModel.h', 'S:\repos\calculator\src\CalcViewModel\MemoryItemViewModel.cpp' + + Formats the specified files. +#> +[CmdletBinding( DefaultParameterSetName = 'Search' )] +param( + [Parameter( ParameterSetName = 'Search' )] + [ValidateScript({ Test-Path -PathType Container -Path $_ })] + [string] $RepoRoot = "$( git rev-parse --show-toplevel )", + + [Parameter( ParameterSetName = 'Search' )] + [string[]] $Include = ( '*.h', '*.hh', '*.hpp', '*.c', '*.cc', '*.cpp' ), + + [Parameter( ParameterSetName = 'Search' )] + [string[]] $Exclude = '*.g.*', + + [Parameter( + ParameterSetName = 'Explicit', + Mandatory)] + [ValidateScript({ + $_ | Where-Object { -not (Test-Path -PathType Leaf -Path $_) } | + ForEach-Object { throw "Could not find file: [$_]" } + + return $true + })] + [string[]] $Files +) + +if ($PSCmdlet.ParameterSetName -eq 'Explicit') +{ + # Use the file paths we were given. + $targetFiles = @($Files) +} +else +{ + # Gather the files to be formatted. + $targetFiles = @( + Get-ChildItem -Recurse -Path $RepoRoot -Include $Include -Exclude $Exclude | + Select-Object -ExpandProperty FullName + ) +} + +# Format the files. +$formatParams = @( + '-i' # In-place + '-style=file' # Search for a .clang-format file in the parent directory of the source file. + '-verbose' +) + +clang-format $formatParams $targetFiles \ No newline at end of file diff --git a/build/pipelines/azure-pipelines.release.yaml b/build/pipelines/azure-pipelines.release.yaml index f687ec4a..6647e907 100644 --- a/build/pipelines/azure-pipelines.release.yaml +++ b/build/pipelines/azure-pipelines.release.yaml @@ -9,8 +9,8 @@ pr: none variables: versionMajor: 10 - versionMinor: 1904 - versionBuild: $[counter('10.1904.*', 0)] + versionMinor: 1905 + versionBuild: $[counter('10.1905.*', 0)] versionPatch: 0 name: '$(versionMajor).$(versionMinor).$(versionBuild).$(versionPatch)' diff --git a/docs/ApplicationArchitecture.md b/docs/ApplicationArchitecture.md index dff02965..235af889 100644 --- a/docs/ApplicationArchitecture.md +++ b/docs/ApplicationArchitecture.md @@ -201,4 +201,5 @@ instead of regular floating point arithmetic). The interface to this layer is de [CalcManager folder]: ../src/CalcManager [CalculatorManager.h]: ../src/CalcManager/CalculatorManager.h [CalcEngine.h]: ../src/CalcManager/Header Files/CalcEngine.h +[Infinite Precision]: https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic [ratpak.h]: ../src/CalcManager/Ratpack/ratpak.h diff --git a/docs/NewFeatureProcess.md b/docs/NewFeatureProcess.md index 2a84aa27..6f514d00 100644 --- a/docs/NewFeatureProcess.md +++ b/docs/NewFeatureProcess.md @@ -29,26 +29,26 @@ idea until it is ready for review. We review pitches regularly, and will approve or close issues based on whether they broadly align with the [Calculator roadmap](https://github.com/Microsoft/calculator/blob/master/docs/Roadmap.md). Approved pitches are moved -into [pre-production](https://github.com/Microsoft/calculator/projects/1) on the feature tracking board. +into [planning](https://github.com/Microsoft/calculator/projects/1) on the feature tracking board. -## Step 2: Pre-production +## Step 2: Planning For most features, the output of this phase is a specification which describes how the feature will work, supported by design renderings and code prototypes as needed. The original issue will continue to track the overall progress of the feature, but we will create and iterate on spec documentation in the [Calculator Spec repo](https://github.com/Microsoft/calculator-specs). Sometimes we'll learn new things about a feature -proposal during pre-production, and we'll edit or close the original pitch. +proposal during planning, and we'll edit or close the original pitch. -We welcome community participation throughout pre-production. The best ideas often come from trying many ideas during -the pre-production phase. To enable rapid +We welcome community participation throughout planning. The best ideas often come from trying many ideas during +the planning phase. To enable rapid experimentation, we encourage developing and sharing rough ideas—maybe even with pencil and paper—before making designs pixel-perfect or making code robust and maintainable. After the [spec review](https://github.com/Microsoft/calculator-specs#spec-review) is completed, we will move the issue -into [production](https://github.com/Microsoft/calculator/projects/1) on the feature tracking board. In _some_ cases, +into [implementation](https://github.com/Microsoft/calculator/projects/1) on the feature tracking board. In _some_ cases, all of the details of an idea can be captured concisely in original feature pitch. When that happens, we may move ideas -directly into production. +directly into implementation. -## Step 3: Production +## Step 3: Implementation A feature can be implemented by the original submitter, a Microsoft team member, or by other community members. Code contributions and testing help are greatly appreciated. Please let everyone know if you're actively working on a feature to help avoid duplicated efforts from others. diff --git a/src/CalcManager/CEngine/History.cpp b/src/CalcManager/CEngine/History.cpp index a7ea93ed..37add769 100644 --- a/src/CalcManager/CEngine/History.cpp +++ b/src/CalcManager/CEngine/History.cpp @@ -40,7 +40,10 @@ void CHistoryCollector::ReinitHistory() // Constructor // Can throw Out of memory error CHistoryCollector::CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr pHistoryDisplay, wchar_t decimalSymbol) - : m_pHistoryDisplay(pHistoryDisplay), m_pCalcDisplay(pCalcDisplay), m_iCurLineHistStart(-1), m_decimalSymbol(decimalSymbol) + : m_pHistoryDisplay(pHistoryDisplay) + , m_pCalcDisplay(pCalcDisplay) + , m_iCurLineHistStart(-1) + , m_decimalSymbol(decimalSymbol) { ReinitHistory(); } @@ -300,8 +303,8 @@ void CHistoryCollector::CompleteHistoryLine(wstring_view numStr) { if (nullptr != m_pCalcDisplay) { - m_pCalcDisplay->SetExpressionDisplay(std::make_shared>>(), - std::make_shared>>()); + m_pCalcDisplay->SetExpressionDisplay( + std::make_shared>>(), std::make_shared>>()); } if (nullptr != m_pHistoryDisplay) @@ -322,8 +325,8 @@ void CHistoryCollector::ClearHistoryLine(wstring_view errStr) { if (nullptr != m_pCalcDisplay) { - m_pCalcDisplay->SetExpressionDisplay(std::make_shared>>(), - std::make_shared>>()); + m_pCalcDisplay->SetExpressionDisplay( + std::make_shared>>(), std::make_shared>>()); } m_iCurLineHistStart = -1; // It will get recomputed at the first Opnd ReinitHistory(); diff --git a/src/CalcManager/CEngine/Number.cpp b/src/CalcManager/CEngine/Number.cpp index 685974a7..7b3be21b 100644 --- a/src/CalcManager/CEngine/Number.cpp +++ b/src/CalcManager/CEngine/Number.cpp @@ -7,15 +7,22 @@ using namespace std; namespace CalcEngine { - Number::Number() noexcept : Number(1, 0, { 0 }) + Number::Number() noexcept + : Number(1, 0, { 0 }) { } - Number::Number(int32_t sign, int32_t exp, vector const& mantissa) noexcept : m_sign{ sign }, m_exp{ exp }, m_mantissa{ mantissa } + Number::Number(int32_t sign, int32_t exp, vector const& mantissa) noexcept + : m_sign{ sign } + , m_exp{ exp } + , m_mantissa{ mantissa } { } - Number::Number(PNUMBER p) noexcept : m_sign{ p->sign }, m_exp{ p->exp }, m_mantissa{} + Number::Number(PNUMBER p) noexcept + : m_sign{ p->sign } + , m_exp{ p->exp } + , m_mantissa{} { m_mantissa.reserve(p->cdigit); copy(p->mant, p->mant + p->cdigit, back_inserter(m_mantissa)); diff --git a/src/CalcManager/CEngine/Rational.cpp b/src/CalcManager/CEngine/Rational.cpp index be2fcb7e..a0bcd97d 100644 --- a/src/CalcManager/CEngine/Rational.cpp +++ b/src/CalcManager/CEngine/Rational.cpp @@ -7,7 +7,9 @@ using namespace std; namespace CalcEngine { - Rational::Rational() noexcept : m_p{}, m_q{ 1, 0, { 1 } } + Rational::Rational() noexcept + : m_p{} + , m_q{ 1, 0, { 1 } } { } @@ -23,7 +25,9 @@ namespace CalcEngine m_q = Number(1, qExp, { 1 }); } - Rational::Rational(Number const& p, Number const& q) noexcept : m_p{ p }, m_q{ q } + Rational::Rational(Number const& p, Number const& q) noexcept + : m_p{ p } + , m_q{ q } { } @@ -58,7 +62,9 @@ namespace CalcEngine m_q = Number{ temp.Q() }; } - Rational::Rational(PRAT prat) noexcept : m_p{ Number{ prat->pp } }, m_q{ Number{ prat->pq } } + Rational::Rational(PRAT prat) noexcept + : m_p{ Number{ prat->pp } } + , m_q{ Number{ prat->pq } } { } diff --git a/src/CalcManager/CEngine/calc.cpp b/src/CalcManager/CEngine/calc.cpp index 41d41c7b..c71d2927 100644 --- a/src/CalcManager/CEngine/calc.cpp +++ b/src/CalcManager/CEngine/calc.cpp @@ -58,8 +58,12 @@ void CCalcEngine::InitialOneTimeOnlySetup(CalculationManager::IResourceProvider& // CCalcEngine::CCalcEngine // ////////////////////////////////////////////////// -CCalcEngine::CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider, - __in_opt ICalcDisplay* pCalcDisplay, __in_opt shared_ptr pHistoryDisplay) +CCalcEngine::CCalcEngine( + bool fPrecedence, + bool fIntegerMode, + CalculationManager::IResourceProvider* const pResourceProvider, + __in_opt ICalcDisplay* pCalcDisplay, + __in_opt shared_ptr pHistoryDisplay) : m_fPrecedence(fPrecedence) , m_fIntegerMode(fIntegerMode) , m_pCalcDisplay(pCalcDisplay) diff --git a/src/CalcManager/CEngine/scicomm.cpp b/src/CalcManager/CEngine/scicomm.cpp index 12cde360..eabb7f94 100644 --- a/src/CalcManager/CEngine/scicomm.cpp +++ b/src/CalcManager/CEngine/scicomm.cpp @@ -382,8 +382,8 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam) if (nullptr != m_pCalcDisplay) { m_pCalcDisplay->SetParenthesisNumber(0); - m_pCalcDisplay->SetExpressionDisplay(make_shared>>(), - make_shared>>()); + m_pCalcDisplay->SetExpressionDisplay( + make_shared>>(), make_shared>>()); } m_HistoryCollector.ClearHistoryLine(wstring()); @@ -476,8 +476,8 @@ void CCalcEngine::ProcessCommandWorker(OpCode wParam) m_HistoryCollector.CompleteHistoryLine(groupedString); if (nullptr != m_pCalcDisplay) { - m_pCalcDisplay->SetExpressionDisplay(make_shared>>(), - make_shared>>()); + m_pCalcDisplay->SetExpressionDisplay( + make_shared>>(), make_shared>>()); } } diff --git a/src/CalcManager/CalculatorHistory.cpp b/src/CalcManager/CalculatorHistory.cpp index 8929cc0c..14a94a8c 100644 --- a/src/CalcManager/CalculatorHistory.cpp +++ b/src/CalcManager/CalculatorHistory.cpp @@ -7,12 +7,15 @@ using namespace std; using namespace CalculationManager; -CalculatorHistory::CalculatorHistory(size_t maxSize) : m_maxHistorySize(maxSize) +CalculatorHistory::CalculatorHistory(size_t maxSize) + : m_maxHistorySize(maxSize) { } -unsigned int CalculatorHistory::AddToHistory(_In_ shared_ptr>> const& tokens, - _In_ shared_ptr>> const& commands, _In_ wstring_view result) +unsigned int CalculatorHistory::AddToHistory( + _In_ shared_ptr>> const& tokens, + _In_ shared_ptr>> const& commands, + _In_ wstring_view result) { unsigned int addedIndex; wstring generatedExpression; diff --git a/src/CalcManager/CalculatorHistory.h b/src/CalcManager/CalculatorHistory.h index eadb04af..75b74255 100644 --- a/src/CalcManager/CalculatorHistory.h +++ b/src/CalcManager/CalculatorHistory.h @@ -30,8 +30,10 @@ namespace CalculationManager { public: CalculatorHistory(const size_t maxSize); - unsigned int AddToHistory(_In_ std::shared_ptr>> const& spTokens, - _In_ std::shared_ptr>> const& spCommands, std::wstring_view result); + unsigned int AddToHistory( + _In_ std::shared_ptr>> const& spTokens, + _In_ std::shared_ptr>> const& spCommands, + std::wstring_view result); std::vector> const& GetHistory(); std::shared_ptr const& GetHistoryItem(unsigned int uIdx); void ClearHistory(); diff --git a/src/CalcManager/CalculatorManager.cpp b/src/CalcManager/CalculatorManager.cpp index 5d542843..d054f5b1 100644 --- a/src/CalcManager/CalculatorManager.cpp +++ b/src/CalcManager/CalculatorManager.cpp @@ -85,8 +85,9 @@ namespace CalculationManager /// Used to set the expression display value on ViewModel /// /// wstring representing expression to be displayed - void CalculatorManager::SetExpressionDisplay(_Inout_ shared_ptr>> const& tokens, - _Inout_ shared_ptr>> const& commands) + void CalculatorManager::SetExpressionDisplay( + _Inout_ shared_ptr>> const& tokens, + _Inout_ shared_ptr>> const& commands) { if (!m_inHistoryItemLoadMode) { @@ -243,8 +244,6 @@ namespace CalculationManager { m_savedCommands.push_back(MapCommandForSerialize(command)); } - this->SerializePrimaryDisplay(); - this->SerializeMemory(); m_savedDegreeMode = m_currentDegreeMode; return; } @@ -329,47 +328,6 @@ namespace CalculationManager return commandToLoad; } - /// - /// Return saved degree mode which is saved when last time the expression was cleared. - /// - Command CalculatorManager::SerializeSavedDegreeMode() - { - return m_savedDegreeMode; - } - - void CalculatorManager::SerializePrimaryDisplay() - { - m_savedPrimaryValue.clear(); - m_currentCalculatorEngine->ProcessCommand(IDC_STORE); - auto memoryObject = m_currentCalculatorEngine->PersistedMemObject(); - if (memoryObject != nullptr) - { - m_savedPrimaryValue = SerializeRational(*memoryObject); - } - } - - /// - /// Return serialized primary display that is saved when the expression line was cleared. - /// - vector CalculatorManager::GetSerializedPrimaryDisplay() - { - return m_savedPrimaryValue; - } - - /// - /// DeSerialize the primary display from vector of long - /// - /// Serialized Rational of primary display - void CalculatorManager::DeSerializePrimaryDisplay(const vector& serializedPrimaryDisplay) - { - if (serializedPrimaryDisplay.empty()) - { - return; - } - m_persistedPrimaryValue = DeSerializeRational(serializedPrimaryDisplay.begin()); - this->LoadPersistedPrimaryValue(); - } - /// /// Load the persisted value that is saved in memory of CalcEngine /// @@ -379,112 +337,6 @@ namespace CalculationManager m_currentCalculatorEngine->ProcessCommand(IDC_RECALL); } - /// - /// Serialize the Memory to vector of long - /// - /// Serialized Rational of memory - void CalculatorManager::SerializeMemory() - { - m_serializedMemory.clear(); - - for (auto const& memoryItem : m_memorizedNumbers) - { - auto serialMem = SerializeRational(memoryItem); - m_serializedMemory.insert(m_serializedMemory.end(), serialMem.begin(), serialMem.end()); - } - } - - vector CalculatorManager::GetSerializedMemory() - { - return m_serializedMemory; - } - - /// - /// DeSerialize the Memory from vector of long - /// - /// Serialized Rational of memory - void CalculatorManager::DeSerializeMemory(const vector& serializedMemory) - { - vector::const_iterator itr = serializedMemory.begin(); - while (itr != serializedMemory.end()) - { - Rational memoryItem = DeSerializeRational(itr); - auto lengthMemoryItem = (2 * SERIALIZED_NUMBER_MINSIZE) + memoryItem.P().Mantissa().size() + memoryItem.Q().Mantissa().size(); - m_memorizedNumbers.push_back(memoryItem); - itr += lengthMemoryItem; - } - this->SetMemorizedNumbersString(); - } - - /// - /// Return the commands saved since the expression has been cleared. - /// - vector CalculatorManager::SerializeCommands() - { - return m_savedCommands; - } - - /// - /// Replay the serialized commands - /// - /// Serialized commands - void CalculatorManager::DeSerializeCommands(_In_ const vector& serializedData) - { - m_savedCommands.clear(); - - for (auto commandItr = serializedData.begin(); commandItr != serializedData.end(); ++commandItr) - { - if (*commandItr >= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizeNumber) - && *commandItr <= MEMORY_COMMAND_TO_UNSIGNED_CHAR(MemoryCommand::MemorizedNumberClearAll)) - { - // 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. - // Hence, a simple cast to MemoryCommand is not sufficient. - MemoryCommand memoryCommand = static_cast(*commandItr + UCHAR_MAX + 1); - unsigned int indexOfMemory = 0; - switch (memoryCommand) - { - case MemoryCommand::MemorizeNumber: - this->MemorizeNumber(); - break; - case MemoryCommand::MemorizedNumberLoad: - if (commandItr + 1 == serializedData.end()) - { - throw out_of_range("Expecting index of memory, data ended prematurely"); - } - indexOfMemory = *(++commandItr); - this->MemorizedNumberLoad(indexOfMemory); - break; - case MemoryCommand::MemorizedNumberAdd: - if (commandItr + 1 == serializedData.end()) - { - throw out_of_range("Expecting index of memory, data ended prematurely"); - } - indexOfMemory = *(++commandItr); - this->MemorizedNumberAdd(indexOfMemory); - break; - case MemoryCommand::MemorizedNumberSubtract: - if (commandItr + 1 == serializedData.end()) - { - throw out_of_range("Expecting index of memory, data ended prematurely"); - } - indexOfMemory = *(++commandItr); - this->MemorizedNumberSubtract(indexOfMemory); - break; - case MemoryCommand::MemorizedNumberClearAll: - this->MemorizedNumberClearAll(); - break; - default: - break; - } - } - else - { - this->SendCommand(static_cast(MapCommandForDeSerialize(*commandItr))); - } - } - } - /// /// Memorize the current displayed value /// Notify the client with new the new memorize value vector diff --git a/src/CalcManager/CalculatorManager.h b/src/CalcManager/CalculatorManager.h index 91a519d2..37406ed4 100644 --- a/src/CalcManager/CalculatorManager.h +++ b/src/CalcManager/CalculatorManager.h @@ -63,7 +63,6 @@ namespace CalculationManager // For persistence std::vector m_savedCommands; std::vector m_savedPrimaryValue; - std::vector m_serializedMemory; std::vector m_currentSerializedMemory; Command m_currentDegreeMode; Command m_savedDegreeMode; @@ -91,8 +90,9 @@ namespace CalculationManager // ICalcDisplay void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override; void SetIsInError(bool isError) override; - void SetExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands) override; + void SetExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands) override; void SetMemorizedNumbers(_In_ const std::vector& memorizedNumbers) override; void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override; void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override; @@ -110,15 +110,6 @@ namespace CalculationManager void SetScientificMode(); void SetProgrammerMode(); void SendCommand(_In_ Command command); - std::vector SerializeCommands(); - void DeSerializeCommands(_In_ const std::vector& serializedData); - void SerializeMemory(); - std::vector GetSerializedMemory(); - void DeSerializeMemory(const std::vector& serializedMemory); - void SerializePrimaryDisplay(); - std::vector GetSerializedPrimaryDisplay(); - void DeSerializePrimaryDisplay(const std::vector& serializedPrimaryDisplay); - Command SerializeSavedDegreeMode(); void MemorizeNumber(); void MemorizedNumberLoad(_In_ unsigned int); diff --git a/src/CalcManager/ExpressionCommand.cpp b/src/CalcManager/ExpressionCommand.cpp index c177de02..079e02aa 100644 --- a/src/CalcManager/ExpressionCommand.cpp +++ b/src/CalcManager/ExpressionCommand.cpp @@ -13,7 +13,8 @@ constexpr wchar_t chNegate = L'-'; constexpr wchar_t chExp = L'e'; constexpr wchar_t chPlus = L'+'; -CParentheses::CParentheses(_In_ int command) : m_command(command) +CParentheses::CParentheses(_In_ int command) + : m_command(command) { } @@ -73,7 +74,8 @@ void CUnaryCommand::Accept(_In_ ISerializeCommandVisitor& commandVisitor) commandVisitor.Visit(*this); } -CBinaryCommand::CBinaryCommand(int command) : m_command(command) +CBinaryCommand::CBinaryCommand(int command) + : m_command(command) { } @@ -98,7 +100,12 @@ void CBinaryCommand::Accept(_In_ ISerializeCommandVisitor& commandVisitor) } COpndCommand::COpndCommand(shared_ptr> const& commands, bool fNegative, bool fDecimal, bool fSciFmt) - : m_commands(commands), m_fNegative(fNegative), m_fSciFmt(fSciFmt), m_fDecimal(fDecimal), m_fInitialized(false), m_value{} + : m_commands(commands) + , m_fNegative(fNegative) + , m_fSciFmt(fSciFmt) + , m_fDecimal(fDecimal) + , m_fInitialized(false) + , m_value{} { } diff --git a/src/CalcManager/Header Files/CalcEngine.h b/src/CalcManager/Header Files/CalcEngine.h index ac29ba2a..03a5437e 100644 --- a/src/CalcManager/Header Files/CalcEngine.h +++ b/src/CalcManager/Header Files/CalcEngine.h @@ -54,8 +54,12 @@ namespace CalculatorEngineTests class CCalcEngine { public: - CCalcEngine(bool fPrecedence, bool fIntegerMode, CalculationManager::IResourceProvider* const pResourceProvider, __in_opt ICalcDisplay* pCalcDisplay, - __in_opt std::shared_ptr pHistoryDisplay); + CCalcEngine( + bool fPrecedence, + bool fIntegerMode, + CalculationManager::IResourceProvider* const pResourceProvider, + __in_opt ICalcDisplay* pCalcDisplay, + __in_opt std::shared_ptr pHistoryDisplay); void ProcessCommand(OpCode wID); void DisplayError(uint32_t nError); std::unique_ptr PersistedMemObject(); diff --git a/src/CalcManager/Header Files/CalcInput.h b/src/CalcManager/Header Files/CalcInput.h index 3e88f740..045cdb89 100644 --- a/src/CalcManager/Header Files/CalcInput.h +++ b/src/CalcManager/Header Files/CalcInput.h @@ -13,7 +13,9 @@ namespace CalcEngine class CalcNumSec { public: - CalcNumSec() : value(), m_isNegative(false) + CalcNumSec() + : value() + , m_isNegative(false) { } @@ -41,11 +43,18 @@ namespace CalcEngine class CalcInput { public: - CalcInput() : CalcInput(L'.') + CalcInput() + : CalcInput(L'.') { } - CalcInput(wchar_t decSymbol) : m_hasExponent(false), m_hasDecimal(false), m_decPtIndex(0), m_decSymbol(decSymbol), m_base(), m_exponent() + CalcInput(wchar_t decSymbol) + : m_hasExponent(false) + , m_hasDecimal(false) + , m_decPtIndex(0) + , m_decSymbol(decSymbol) + , m_base() + , m_exponent() { } diff --git a/src/CalcManager/Header Files/ICalcDisplay.h b/src/CalcManager/Header Files/ICalcDisplay.h index 93bb81c4..f4aebec3 100644 --- a/src/CalcManager/Header Files/ICalcDisplay.h +++ b/src/CalcManager/Header Files/ICalcDisplay.h @@ -12,8 +12,9 @@ class ICalcDisplay public: virtual void SetPrimaryDisplay(const std::wstring& pszText, bool isError) = 0; virtual void SetIsInError(bool isInError) = 0; - virtual void SetExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands) = 0; + virtual void SetExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands) = 0; virtual void SetParenthesisNumber(_In_ unsigned int count) = 0; virtual void OnNoRightParenAdded() = 0; virtual void MaxDigitsReached() = 0; // not an error but still need to inform UI layer. diff --git a/src/CalcManager/Header Files/IHistoryDisplay.h b/src/CalcManager/Header Files/IHistoryDisplay.h index c7189718..7e2a9019 100644 --- a/src/CalcManager/Header Files/IHistoryDisplay.h +++ b/src/CalcManager/Header Files/IHistoryDisplay.h @@ -8,7 +8,8 @@ class IHistoryDisplay { public: virtual ~IHistoryDisplay(){}; - virtual unsigned int AddToHistory(_In_ std::shared_ptr>> const& tokens, - _In_ std::shared_ptr>> const& commands, - _In_ std::wstring_view result) = 0; + virtual unsigned int AddToHistory( + _In_ std::shared_ptr>> const& tokens, + _In_ std::shared_ptr>> const& commands, + _In_ std::wstring_view result) = 0; }; diff --git a/src/CalcManager/Ratpack/ratpak.h b/src/CalcManager/Ratpack/ratpak.h index d98b3003..2e7c973c 100644 --- a/src/CalcManager/Ratpack/ratpak.h +++ b/src/CalcManager/Ratpack/ratpak.h @@ -356,12 +356,14 @@ 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 nRadixxtonum(_In_ PNUMBER a, uint32_t radix, int32_t precision); 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. -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 i32prodnum(int32_t start, int32_t stop, uint32_t radix); diff --git a/src/CalcManager/UnitConverter.cpp b/src/CalcManager/UnitConverter.cpp index 6c59ae97..57cd49bd 100644 --- a/src/CalcManager/UnitConverter.cpp +++ b/src/CalcManager/UnitConverter.cpp @@ -11,8 +11,6 @@ using namespace concurrency; using namespace std; using namespace UnitConversionManager; -static constexpr uint32_t EXPECTEDSERIALIZEDTOKENCOUNT = 7; -static constexpr uint32_t EXPECTEDSERIALIZEDCONVERSIONDATATOKENCOUNT = 3; static constexpr uint32_t EXPECTEDSERIALIZEDCATEGORYTOKENCOUNT = 3; static constexpr uint32_t EXPECTEDSERIALIZEDUNITTOKENCOUNT = 6; static constexpr uint32_t EXPECTEDSTATEDATATOKENCOUNT = 5; @@ -34,7 +32,8 @@ unordered_map unquoteConversions; /// Constructor, sets up all the variables and requires a configLoader /// /// An instance of the IConverterDataLoader interface which we use to read in category/unit names and conversion data -UnitConverter::UnitConverter(_In_ const shared_ptr& dataLoader) : UnitConverter::UnitConverter(dataLoader, nullptr) +UnitConverter::UnitConverter(_In_ const shared_ptr& dataLoader) + : UnitConverter::UnitConverter(dataLoader, nullptr) { } @@ -216,18 +215,6 @@ vector UnitConverter::StringToVector(const wstring& w, const wchar_t* d } return serializedTokens; } - -Category UnitConverter::StringToCategory(const wstring& w) -{ - vector tokenList = StringToVector(w, L";"); - assert(tokenList.size() == EXPECTEDSERIALIZEDCATEGORYTOKENCOUNT); - Category serializedCategory; - serializedCategory.id = _wtoi(Unquote(tokenList[0]).c_str()); - serializedCategory.supportsNegative = (tokenList[1].compare(L"1") == 0); - serializedCategory.name = Unquote(tokenList[2]); - return serializedCategory; -} - wstring UnitConverter::UnitToString(const Unit& u, const wchar_t* delimiter) { wstringstream out(wstringstream::out); @@ -252,150 +239,15 @@ Unit UnitConverter::StringToUnit(const wstring& w) return serializedUnit; } -ConversionData UnitConverter::StringToConversionData(const wstring& w) +Category UnitConverter::StringToCategory(const wstring& w) { vector tokenList = StringToVector(w, L";"); - assert(tokenList.size() == EXPECTEDSERIALIZEDCONVERSIONDATATOKENCOUNT); - ConversionData serializedConversionData; - serializedConversionData.ratio = stod(Unquote(tokenList[0]).c_str()); - serializedConversionData.offset = stod(Unquote(tokenList[1]).c_str()); - serializedConversionData.offsetFirst = (tokenList[2].compare(L"1") == 0); - return serializedConversionData; -} - -wstring UnitConverter::ConversionDataToString(ConversionData d, const wchar_t* delimiter) -{ - wstringstream out(wstringstream::out); - out.precision(32); - out << fixed << d.ratio; - wstring ratio = out.str(); - out.str(L""); - out << fixed << d.offset; - wstring offset = out.str(); - out.str(L""); - TrimString(ratio); - TrimString(offset); - out << Quote(ratio) << delimiter << Quote(offset) << delimiter << std::to_wstring(d.offsetFirst) << delimiter; - return out.str(); -} - -/// -/// Serializes the data in the converter and returns it as a string -/// -wstring UnitConverter::Serialize() -{ - if (!CheckLoad()) - { - return wstring(); - } - - wstringstream out(wstringstream::out); - const wchar_t* delimiter = L";"; - - out << UnitToString(m_fromType, delimiter) << "|"; - out << UnitToString(m_toType, 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 << m_currentDisplay << delimiter << m_returnDisplay << delimiter << "|"; - wstringstream categoryString(wstringstream::out); - wstringstream categoryToUnitString(wstringstream::out); - wstringstream unitToUnitToDoubleString(wstringstream::out); - for (const Category& c : m_categories) - { - categoryString << CategoryToString(c, delimiter) << ","; - } - - for (const auto& cur : m_categoryToUnits) - { - categoryToUnitString << CategoryToString(cur.first, delimiter) << "["; - for (const Unit& u : cur.second) - { - categoryToUnitString << UnitToString(u, delimiter) << ","; - } - categoryToUnitString << "[" - << "]"; - } - - for (const auto& cur : m_ratioMap) - { - unitToUnitToDoubleString << UnitToString(cur.first, delimiter) << "["; - for (const auto& curConversion : cur.second) - { - unitToUnitToDoubleString << UnitToString(curConversion.first, delimiter) << ":"; - unitToUnitToDoubleString << ConversionDataToString(curConversion.second, delimiter) << ":,"; - } - unitToUnitToDoubleString << "[" - << "]"; - } - - out << categoryString.str() << "|"; - out << categoryToUnitString.str() << "|"; - out << unitToUnitToDoubleString.str() << "|"; - wstring test = out.str(); - return test; -} - -/// -/// De-Serializes the data in the converter from a string -/// -/// wstring holding the serialized data. If it does not have expected number of parameters, we will ignore it -void UnitConverter::DeSerialize(const wstring& serializedData) -{ - ClearValues(); - ResetCategoriesAndRatios(); - - if (serializedData.empty()) - { - return; - } - - vector outerTokens = StringToVector(serializedData, L"|"); - assert(outerTokens.size() == EXPECTEDSERIALIZEDTOKENCOUNT); - m_fromType = StringToUnit(outerTokens[0]); - m_toType = StringToUnit(outerTokens[1]); - m_currentCategory = StringToCategory(outerTokens[2]); - vector stateDataTokens = StringToVector(outerTokens[3], L";"); - assert(stateDataTokens.size() == EXPECTEDSTATEDATATOKENCOUNT); - m_currentHasDecimal = (stateDataTokens[0].compare(L"1") == 0); - m_returnHasDecimal = (stateDataTokens[1].compare(L"1") == 0); - m_switchedActive = (stateDataTokens[2].compare(L"1") == 0); - m_currentDisplay = stateDataTokens[3]; - m_returnDisplay = stateDataTokens[4]; - vector categoryListTokens = StringToVector(outerTokens[4], L","); - for (wstring token : categoryListTokens) - { - m_categories.push_back(StringToCategory(token)); - } - vector unitVectorTokens = StringToVector(outerTokens[5], L"]"); - for (wstring unitVector : unitVectorTokens) - { - vector mapcomponents = StringToVector(unitVector, L"["); - assert(mapcomponents.size() == EXPECTEDMAPCOMPONENTTOKENCOUNT); - Category key = StringToCategory(mapcomponents[0]); - vector units = StringToVector(mapcomponents[1], L","); - for (wstring unit : units) - { - m_categoryToUnits[key].push_back(StringToUnit(unit)); - } - } - vector ratioMapTokens = StringToVector(outerTokens[6], L"]"); - for (wstring token : ratioMapTokens) - { - vector ratioMapComponentTokens = StringToVector(token, L"["); - assert(ratioMapComponentTokens.size() == EXPECTEDMAPCOMPONENTTOKENCOUNT); - Unit key = StringToUnit(ratioMapComponentTokens[0]); - vector ratioMapList = StringToVector(ratioMapComponentTokens[1], L","); - for (wstring subtoken : ratioMapList) - { - vector ratioMapSubComponentTokens = StringToVector(subtoken, L":"); - assert(ratioMapSubComponentTokens.size() == EXPECTEDMAPCOMPONENTTOKENCOUNT); - Unit subkey = StringToUnit(ratioMapSubComponentTokens[0]); - ConversionData conversion = StringToConversionData(ratioMapSubComponentTokens[1]); - m_ratioMap[key][subkey] = conversion; - } - } - UpdateViewModel(); + assert(tokenList.size() == EXPECTEDSERIALIZEDCATEGORYTOKENCOUNT); + Category serializedCategory; + serializedCategory.id = _wtoi(Unquote(tokenList[0]).c_str()); + serializedCategory.supportsNegative = (tokenList[1].compare(L"1") == 0); + serializedCategory.name = Unquote(tokenList[2]); + return serializedCategory; } /// diff --git a/src/CalcManager/UnitConverter.h b/src/CalcManager/UnitConverter.h index 87dc91dc..19582245 100644 --- a/src/CalcManager/UnitConverter.h +++ b/src/CalcManager/UnitConverter.h @@ -29,9 +29,19 @@ namespace UnitConversionManager { } - 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) + 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) { std::wstring nameValue1 = isRtlLanguage ? currencyName : countryName; std::wstring nameValue2 = isRtlLanguage ? countryName : currencyName; @@ -76,7 +86,10 @@ namespace UnitConversionManager { } - 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) { } @@ -125,7 +138,10 @@ namespace UnitConversionManager 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) { } @@ -155,9 +171,10 @@ namespace UnitConversionManager }; typedef std::tuple, UnitConversionManager::Unit, UnitConversionManager::Unit> CategorySelectionInitializer; - typedef std::unordered_map, - UnitConversionManager::UnitHash> + typedef std::unordered_map< + UnitConversionManager::Unit, + std::unordered_map, + UnitConversionManager::UnitHash> UnitToUnitToConversionDataMap; typedef std::unordered_map, UnitConversionManager::CategoryHash> CategoryToUnitVectorMap; @@ -188,10 +205,10 @@ namespace UnitConversionManager { public: virtual void SetViewModelCallback(const std::shared_ptr& callback) = 0; - virtual std::pair GetCurrencySymbols(_In_ const UnitConversionManager::Unit& unit1, - _In_ const UnitConversionManager::Unit& unit2) = 0; - virtual std::pair GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, - _In_ const UnitConversionManager::Unit& unit2) = 0; + virtual std::pair + GetCurrencySymbols(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) = 0; + virtual std::pair + GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) = 0; virtual std::wstring GetCurrencyTimestamp() = 0; virtual concurrency::task TryLoadDataFromCacheAsync() = 0; @@ -220,8 +237,6 @@ namespace UnitConversionManager virtual Category GetCurrentCategory() = 0; virtual void SetCurrentUnitTypes(const Unit& fromType, const Unit& toType) = 0; virtual void SwitchActive(const std::wstring& newValue) = 0; - virtual std::wstring Serialize() = 0; - virtual void DeSerialize(const std::wstring& serializedData) = 0; virtual std::wstring SaveUserPreferences() = 0; virtual void RestoreUserPreferences(_In_ const std::wstring& userPreferences) = 0; virtual void SendCommand(Command command) = 0; @@ -245,8 +260,6 @@ namespace UnitConversionManager Category GetCurrentCategory() override; void SetCurrentUnitTypes(const Unit& fromType, const Unit& toType) override; void SwitchActive(const std::wstring& newValue) override; - std::wstring Serialize() override; - void DeSerialize(const std::wstring& serializedData) override; std::wstring SaveUserPreferences() override; void RestoreUserPreferences(const std::wstring& userPreference) override; void SendCommand(Command command) override; @@ -273,8 +286,6 @@ namespace UnitConversionManager std::wstring CategoryToString(const Category& c, const wchar_t* delimiter); std::wstring UnitToString(const Unit& u, const wchar_t* delimiter); Unit StringToUnit(const std::wstring& w); - ConversionData StringToConversionData(const std::wstring& w); - std::wstring ConversionDataToString(ConversionData d, const wchar_t* delimiter); void UpdateCurrencySymbols(); void UpdateViewModel(); bool AnyUnitIsEmpty(); diff --git a/src/CalcViewModel/Common/AlwaysSelectedCollectionView.h b/src/CalcViewModel/Common/AlwaysSelectedCollectionView.h index 1d0c7c49..57e1d74e 100644 --- a/src/CalcViewModel/Common/AlwaysSelectedCollectionView.h +++ b/src/CalcViewModel/Common/AlwaysSelectedCollectionView.h @@ -9,7 +9,8 @@ namespace CalculatorApp { ref class AlwaysSelectedCollectionView sealed : public Windows::UI::Xaml::DependencyObject, public Windows::UI::Xaml::Data::ICollectionView { - internal : AlwaysSelectedCollectionView(Windows::UI::Xaml::Interop::IBindableVector ^ source) : m_currentPosition(-1) + internal : AlwaysSelectedCollectionView(Windows::UI::Xaml::Interop::IBindableVector ^ source) + : m_currentPosition(-1) { m_source = source; @@ -47,8 +48,8 @@ namespace CalculatorApp throw ref new Platform::NotImplementedException(); } property Windows::Foundation::Collections::IObservableVector ^ CollectionGroups { - virtual Windows::Foundation::Collections::IObservableVector ^ get() = Windows::UI::Xaml::Data::ICollectionView::CollectionGroups::get + virtual Windows::Foundation::Collections::IObservableVector< + Platform::Object ^> ^ get() = Windows::UI::Xaml::Data::ICollectionView::CollectionGroups::get { return ref new Platform::Collections::Vector(); } @@ -80,8 +81,9 @@ namespace CalculatorApp // restore the selection to the way we wanted it to begin with if (m_currentPosition >= 0 && m_currentPosition < static_cast(m_source->Size)) { - this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, - ref new Windows::UI::Core::DispatchedHandler([this]() { m_currentChanged(this, nullptr); })); + this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() { + m_currentChanged(this, nullptr); + })); } return false; } @@ -167,14 +169,14 @@ namespace CalculatorApp { throw ref new Platform::NotImplementedException(); } - virtual unsigned int - GetMany(unsigned int /*startIndex*/, - Platform::WriteOnlyArray ^ /*items*/) = Windows::Foundation::Collections::IVector::GetMany + virtual unsigned int GetMany( + unsigned int /*startIndex*/, + Platform::WriteOnlyArray ^ /*items*/) = Windows::Foundation::Collections::IVector::GetMany { throw ref new Platform::NotImplementedException(); } - virtual Windows::Foundation::Collections::IVectorView ^ GetView() = Windows::Foundation::Collections::IVector::GetView + virtual Windows::Foundation::Collections::IVectorView ^ GetView() = Windows::Foundation::Collections::IVector< + Platform::Object ^>::GetView { throw ref new Platform::NotImplementedException(); } @@ -263,8 +265,11 @@ namespace CalculatorApp private: virtual Platform::Object - ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert + ^ Convert( + Platform::Object ^ value, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert { auto result = dynamic_cast(value); if (result) @@ -275,8 +280,11 @@ namespace CalculatorApp } virtual Platform::Object - ^ ConvertBack(Platform::Object ^ /*value*/, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack + ^ ConvertBack( + Platform::Object ^ /*value*/, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack { return Windows::UI::Xaml::DependencyProperty::UnsetValue; } diff --git a/src/CalcViewModel/Common/Automation/LiveRegionHost.cpp b/src/CalcViewModel/Common/Automation/LiveRegionHost.cpp index 4fd96591..0df3a96c 100644 --- a/src/CalcViewModel/Common/Automation/LiveRegionHost.cpp +++ b/src/CalcViewModel/Common/Automation/LiveRegionHost.cpp @@ -9,7 +9,8 @@ using namespace Windows::UI::Xaml::Automation; using namespace Windows::UI::Xaml::Automation::Peers; using namespace Windows::UI::Xaml::Controls; -LiveRegionHost::LiveRegionHost() : m_host(nullptr) +LiveRegionHost::LiveRegionHost() + : m_host(nullptr) { } diff --git a/src/CalcViewModel/Common/Automation/NarratorAnnouncement.cpp b/src/CalcViewModel/Common/Automation/NarratorAnnouncement.cpp index fd5bb0a0..5b6d99bd 100644 --- a/src/CalcViewModel/Common/Automation/NarratorAnnouncement.cpp +++ b/src/CalcViewModel/Common/Automation/NarratorAnnouncement.cpp @@ -25,9 +25,15 @@ namespace CalculatorApp::Common::Automation } } -NarratorAnnouncement::NarratorAnnouncement(String ^ announcement, String ^ activityId, AutomationNotificationKind kind, - AutomationNotificationProcessing processing) - : m_announcement(announcement), m_activityId(activityId), m_kind(kind), m_processing(processing) +NarratorAnnouncement::NarratorAnnouncement( + String ^ announcement, + String ^ activityId, + AutomationNotificationKind kind, + AutomationNotificationProcessing processing) + : m_announcement(announcement) + , m_activityId(activityId) + , m_kind(kind) + , m_processing(processing) { } @@ -58,66 +64,78 @@ bool NarratorAnnouncement::IsValid(NarratorAnnouncement ^ announcement) NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayUpdatedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::DisplayUpdated, AutomationNotificationKind::Other, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::DisplayUpdated, AutomationNotificationKind::Other, AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetMaxDigitsReachedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MaxDigitsReached, AutomationNotificationKind::Other, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::MaxDigitsReached, AutomationNotificationKind::Other, AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryClearedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryCleared, AutomationNotificationKind::ItemRemoved, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::MemoryCleared, AutomationNotificationKind::ItemRemoved, AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemChangedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryItemChanged, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::MostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::MemoryItemChanged, AutomationNotificationKind::ActionCompleted, AutomationNotificationProcessing::MostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetMemoryItemAddedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::MemoryItemAdded, AutomationNotificationKind::ItemAdded, - AutomationNotificationProcessing::MostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::MemoryItemAdded, AutomationNotificationKind::ItemAdded, AutomationNotificationProcessing::MostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetHistoryClearedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::HistoryCleared, AutomationNotificationKind::ItemRemoved, - AutomationNotificationProcessing::MostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::HistoryCleared, AutomationNotificationKind::ItemRemoved, AutomationNotificationProcessing::MostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetCategoryNameChangedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::CategoryNameChanged, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, + CalculatorActivityIds::CategoryNameChanged, + AutomationNotificationKind::ActionCompleted, + AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetUpdateCurrencyRatesAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::UpdateCurrencyRates, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, + CalculatorActivityIds::UpdateCurrencyRates, + AutomationNotificationKind::ActionCompleted, + AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetDisplayCopiedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::DisplayCopied, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, CalculatorActivityIds::DisplayCopied, AutomationNotificationKind::ActionCompleted, AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetOpenParenthesisCountChangedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::OpenParenthesisCountChanged, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, + CalculatorActivityIds::OpenParenthesisCountChanged, + AutomationNotificationKind::ActionCompleted, + AutomationNotificationProcessing::ImportantMostRecent); } NarratorAnnouncement ^ CalculatorAnnouncement::GetNoRightParenthesisAddedAnnouncement(String ^ announcement) { - return ref new NarratorAnnouncement(announcement, CalculatorActivityIds::NoParenthesisAdded, AutomationNotificationKind::ActionCompleted, - AutomationNotificationProcessing::ImportantMostRecent); + return ref new NarratorAnnouncement( + announcement, + CalculatorActivityIds::NoParenthesisAdded, + AutomationNotificationKind::ActionCompleted, + AutomationNotificationProcessing::ImportantMostRecent); } diff --git a/src/CalcViewModel/Common/Automation/NarratorAnnouncement.h b/src/CalcViewModel/Common/Automation/NarratorAnnouncement.h index f3582981..c4c0c526 100644 --- a/src/CalcViewModel/Common/Automation/NarratorAnnouncement.h +++ b/src/CalcViewModel/Common/Automation/NarratorAnnouncement.h @@ -58,8 +58,11 @@ public // class that can access the private constructor. friend class CalculatorAnnouncement; - NarratorAnnouncement(Platform::String ^ announcement, Platform::String ^ activityId, AutomationNotificationKind kind, - AutomationNotificationProcessing processing); + NarratorAnnouncement( + Platform::String ^ announcement, + Platform::String ^ activityId, + AutomationNotificationKind kind, + AutomationNotificationProcessing processing); Platform::String ^ m_announcement; Platform::String ^ m_activityId; diff --git a/src/CalcViewModel/Common/Automation/NarratorNotifier.cpp b/src/CalcViewModel/Common/Automation/NarratorNotifier.cpp index 0f3fb8d5..bc146e68 100644 --- a/src/CalcViewModel/Common/Automation/NarratorNotifier.cpp +++ b/src/CalcViewModel/Common/Automation/NarratorNotifier.cpp @@ -30,11 +30,13 @@ void NarratorNotifier::Announce(NarratorAnnouncement ^ announcement) void NarratorNotifier::RegisterDependencyProperties() { - s_announcementProperty = DependencyProperty::Register(L"Announcement", // The name of the dependency property. - NarratorAnnouncement::typeid, // The type of the dependency property. - NarratorNotifier::typeid, // The owner of the dependency property. - ref new PropertyMetadata(nullptr, // Default value of the dependency property. - ref new PropertyChangedCallback(OnAnnouncementChanged))); + s_announcementProperty = DependencyProperty::Register( + L"Announcement", // The name of the dependency property. + NarratorAnnouncement::typeid, // The type of the dependency property. + NarratorNotifier::typeid, // The owner of the dependency property. + ref new PropertyMetadata( + nullptr, // Default value of the dependency property. + ref new PropertyChangedCallback(OnAnnouncementChanged))); } void NarratorNotifier::OnAnnouncementChanged(_In_ DependencyObject ^ dependencyObject, _In_ DependencyPropertyChangedEventArgs ^ e) diff --git a/src/CalcViewModel/Common/Automation/NarratorNotifier.h b/src/CalcViewModel/Common/Automation/NarratorNotifier.h index fda841ce..55bed4e7 100644 --- a/src/CalcViewModel/Common/Automation/NarratorNotifier.h +++ b/src/CalcViewModel/Common/Automation/NarratorNotifier.h @@ -31,8 +31,8 @@ public ^ AnnouncementProperty { Windows::UI::Xaml::DependencyProperty ^ get() { return s_announcementProperty; } } static NarratorAnnouncement - ^ GetAnnouncement(Windows::UI::Xaml::DependencyObject - ^ element) { return safe_cast(element->GetValue(s_announcementProperty)); } + ^ GetAnnouncement( + Windows::UI::Xaml::DependencyObject ^ element) { return safe_cast(element->GetValue(s_announcementProperty)); } static void SetAnnouncement(Windows::UI::Xaml::DependencyObject ^ element, NarratorAnnouncement ^ value) { @@ -40,8 +40,9 @@ public } private: - static void OnAnnouncementChanged(_In_ Windows::UI::Xaml::DependencyObject ^ dependencyObject, - _In_ Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ eventArgs); + static void OnAnnouncementChanged( + _In_ Windows::UI::Xaml::DependencyObject ^ dependencyObject, + _In_ Windows::UI::Xaml::DependencyPropertyChangedEventArgs ^ eventArgs); static Windows::UI::Xaml::DependencyProperty ^ s_announcementProperty; diff --git a/src/CalcViewModel/Common/Automation/NotificationHost.cpp b/src/CalcViewModel/Common/Automation/NotificationHost.cpp index d3951846..92bf846e 100644 --- a/src/CalcViewModel/Common/Automation/NotificationHost.cpp +++ b/src/CalcViewModel/Common/Automation/NotificationHost.cpp @@ -10,7 +10,8 @@ using namespace Windows::UI::Xaml::Automation; using namespace Windows::UI::Xaml::Automation::Peers; using namespace Windows::UI::Xaml::Controls; -NotificationHost::NotificationHost() : m_host(nullptr) +NotificationHost::NotificationHost() + : m_host(nullptr) { } @@ -34,8 +35,11 @@ void NotificationHost::Announce(NarratorAnnouncement ^ announcement) auto peer = FrameworkElementAutomationPeer::FromElement(m_host); if (peer != nullptr) { - peer->RaiseNotificationEvent(GetWindowsNotificationKind(announcement->Kind), GetWindowsNotificationProcessing(announcement->Processing), - announcement->Announcement, announcement->ActivityId); + peer->RaiseNotificationEvent( + GetWindowsNotificationKind(announcement->Kind), + GetWindowsNotificationProcessing(announcement->Processing), + announcement->Announcement, + announcement->ActivityId); } } diff --git a/src/CalcViewModel/Common/CalculatorButtonPressedEventArgs.h b/src/CalcViewModel/Common/CalculatorButtonPressedEventArgs.h index 2f7bc721..27624987 100644 --- a/src/CalcViewModel/Common/CalculatorButtonPressedEventArgs.h +++ b/src/CalcViewModel/Common/CalculatorButtonPressedEventArgs.h @@ -18,7 +18,8 @@ namespace CalculatorApp PROPERTY_R(CalculatorApp::NumbersAndOperatorsEnum, Operation); CalculatorButtonPressedEventArgs(Platform::String ^ feedback, CalculatorApp::NumbersAndOperatorsEnum operation) - : m_AuditoryFeedback(feedback), m_Operation(operation) + : m_AuditoryFeedback(feedback) + , m_Operation(operation) { } diff --git a/src/CalcViewModel/Common/CalculatorDisplay.cpp b/src/CalcViewModel/Common/CalculatorDisplay.cpp index 823d9bcb..91892dda 100644 --- a/src/CalcViewModel/Common/CalculatorDisplay.cpp +++ b/src/CalcViewModel/Common/CalculatorDisplay.cpp @@ -69,8 +69,9 @@ void CalculatorDisplay::SetIsInError(bool isError) } } -void CalculatorDisplay::SetExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands) +void CalculatorDisplay::SetExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands) { if (m_callbackReference != nullptr) { diff --git a/src/CalcViewModel/Common/CalculatorDisplay.h b/src/CalcViewModel/Common/CalculatorDisplay.h index 1fef3d65..93865c96 100644 --- a/src/CalcViewModel/Common/CalculatorDisplay.h +++ b/src/CalcViewModel/Common/CalculatorDisplay.h @@ -18,8 +18,9 @@ namespace CalculatorApp private: void SetPrimaryDisplay(_In_ const std::wstring& displayString, _In_ bool isError) override; void SetIsInError(bool isError) override; - void SetExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands) override; + void SetExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands) override; void SetMemorizedNumbers(_In_ const std::vector& memorizedNumbers) override; void OnHistoryItemAdded(_In_ unsigned int addedItemIndex) override; void SetParenthesisNumber(_In_ unsigned int parenthesisCount) override; diff --git a/src/CalcViewModel/Common/ConversionResultTaskHelper.cpp b/src/CalcViewModel/Common/ConversionResultTaskHelper.cpp index 3f998e6f..ec90228f 100644 --- a/src/CalcViewModel/Common/ConversionResultTaskHelper.cpp +++ b/src/CalcViewModel/Common/ConversionResultTaskHelper.cpp @@ -9,7 +9,8 @@ using namespace concurrency; using namespace std; ConversionResultTaskHelper::ConversionResultTaskHelper(unsigned int delay, const function functionToRun) - : m_delay{ delay }, m_storedFunction{ functionToRun } + : m_delay{ delay } + , m_storedFunction{ functionToRun } { auto token = m_cts.get_token(); auto delayTask = CompleteAfter(delay); diff --git a/src/CalcViewModel/Common/CopyPasteManager.cpp b/src/CalcViewModel/Common/CopyPasteManager.cpp index 4325cad4..db2439f7 100644 --- a/src/CalcViewModel/Common/CopyPasteManager.cpp +++ b/src/CalcViewModel/Common/CopyPasteManager.cpp @@ -38,9 +38,10 @@ static const wstring c_uIntSuffixes = L"[uU]?[lL]{0,2}"; // RegEx Patterns used by various modes static const array standardModePatterns = { wregex(c_wspc + c_signedDecFloat + c_wspc) }; -static const array scientificModePatterns = { wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + c_wspcRParens), - wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat - + L"[e]([+]|[-])+\\d+" + c_wspcRParens) }; +static const array scientificModePatterns = { + wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + c_wspcRParens), + wregex(L"(" + c_wspc + L"[-+]?)|(" + c_wspcLParenSigned + L")" + c_signedDecFloat + L"e[+-]?\\d+" + c_wspcRParens) +}; static const array, 4> programmerModePatterns = { { // Hex numbers like 5F, 4A0C, 0xa9, 0xFFull, 47CDh { wregex(c_wspcLParens + L"(0[xX])?" + c_hexProgrammerChars + c_uIntSuffixes + c_wspcRParens), @@ -75,9 +76,11 @@ task CopyPasteManager::GetStringToPaste(ViewMode mode, CategoryGroupTy //-- 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))) - .then([mode, modeType, programmerNumberBase, - bitLengthType](String ^ pastedText) { return ValidatePasteExpression(pastedText, mode, modeType, programmerNumberBase, bitLengthType); }, - task_continuation_context::use_arbitrary()); + .then( + [mode, modeType, programmerNumberBase, bitLengthType](String ^ pastedText) { + return ValidatePasteExpression(pastedText, mode, modeType, programmerNumberBase, bitLengthType); + }, + task_continuation_context::use_arbitrary()); } int CopyPasteManager::ClipboardTextFormat() diff --git a/src/CalcViewModel/Common/CopyPasteManager.h b/src/CalcViewModel/Common/CopyPasteManager.h index e4aa9a74..b393dab5 100644 --- a/src/CalcViewModel/Common/CopyPasteManager.h +++ b/src/CalcViewModel/Common/CopyPasteManager.h @@ -26,8 +26,11 @@ namespace CalculatorApp { public: static void CopyToClipboard(Platform::String ^ stringToCopy); - static concurrency::task GetStringToPaste(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, - int programmerNumberBase = -1, int bitLengthType = -1); + static concurrency::task GetStringToPaste( + CalculatorApp::Common::ViewMode mode, + CalculatorApp::Common::CategoryGroupType modeType, + int programmerNumberBase = -1, + int bitLengthType = -1); static bool HasStringToPaste() { return ClipboardTextFormat() >= 0; @@ -40,20 +43,34 @@ namespace CalculatorApp static Platform::String ^ ValidatePasteExpression(Platform::String ^ pastedText, CalculatorApp::Common::ViewMode mode, int programmerNumberBase, int bitLengthType); static Platform::String - ^ ValidatePasteExpression(Platform::String ^ pastedText, CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, - int programmerNumberBase, int bitLengthType); + ^ ValidatePasteExpression( + Platform::String ^ pastedText, + CalculatorApp::Common::ViewMode mode, + CalculatorApp::Common::CategoryGroupType modeType, + int programmerNumberBase, + int bitLengthType); - static std::vector ExtractOperands(const std::wstring& pasteExpression, CalculatorApp::Common::ViewMode mode, - int programmerNumberBase = -1, int bitLengthType = -1); - static bool ExpressionRegExMatch(std::vector operands, CalculatorApp::Common::ViewMode mode, - CalculatorApp::Common::CategoryGroupType modeType, int programmerNumberBase = -1, int bitLengthType = -1); + static std::vector + ExtractOperands(const std::wstring& pasteExpression, CalculatorApp::Common::ViewMode mode, int programmerNumberBase = -1, int bitLengthType = -1); + static bool ExpressionRegExMatch( + std::vector operands, + CalculatorApp::Common::ViewMode mode, + CalculatorApp::Common::CategoryGroupType modeType, + int programmerNumberBase = -1, + int bitLengthType = -1); - static std::pair GetMaxOperandLengthAndValue(CalculatorApp::Common::ViewMode mode, CalculatorApp::Common::CategoryGroupType modeType, - int programmerNumberBase = -1, int bitLengthType = -1); + static std::pair GetMaxOperandLengthAndValue( + CalculatorApp::Common::ViewMode mode, + CalculatorApp::Common::CategoryGroupType modeType, + int programmerNumberBase = -1, + int bitLengthType = -1); static std::wstring SanitizeOperand(const std::wstring& operand); 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 ProgrammerOperandLength(const std::wstring& operand, int numberBase); static std::wstring RemoveUnwantedCharsFromWstring(const std::wstring& input); diff --git a/src/CalcViewModel/Common/DateCalculator.h b/src/CalcViewModel/Common/DateCalculator.h index dbb057a7..e71f02f1 100644 --- a/src/CalcViewModel/Common/DateCalculator.h +++ b/src/CalcViewModel/Common/DateCalculator.h @@ -44,12 +44,17 @@ namespace CalculatorApp DateCalculationEngine(_In_ Platform::String ^ calendarIdentifier); // Public Methods - bool __nothrow AddDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration, - _Out_ Windows::Foundation::DateTime* endDate); - 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); + bool __nothrow + AddDuration(_In_ Windows::Foundation::DateTime startDate, _In_ const DateDifference& duration, _Out_ Windows::Foundation::DateTime* endDate); + 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 Variables diff --git a/src/CalcViewModel/Common/DelegateCommand.h b/src/CalcViewModel/Common/DelegateCommand.h index 325138f6..3a341287 100644 --- a/src/CalcViewModel/Common/DelegateCommand.h +++ b/src/CalcViewModel/Common/DelegateCommand.h @@ -14,7 +14,9 @@ namespace CalculatorApp typedef void (TTarget::*CommandHandlerFunc)(Platform::Object ^); - DelegateCommand(TTarget ^ target, CommandHandlerFunc func) : m_weakTarget(target), m_function(func) + DelegateCommand(TTarget ^ target, CommandHandlerFunc func) + : m_weakTarget(target) + , m_function(func) { } diff --git a/src/CalcViewModel/Common/DisplayExpressionToken.h b/src/CalcViewModel/Common/DisplayExpressionToken.h index c0e7d9e8..aaaaf37c 100644 --- a/src/CalcViewModel/Common/DisplayExpressionToken.h +++ b/src/CalcViewModel/Common/DisplayExpressionToken.h @@ -18,7 +18,12 @@ public [Windows::UI::Xaml::Data::Bindable] public ref class DisplayExpressionToken sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged { internal : 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) { } diff --git a/src/CalcViewModel/Common/ExpressionCommandDeserializer.cpp b/src/CalcViewModel/Common/ExpressionCommandDeserializer.cpp index 70a39f9a..e927b262 100644 --- a/src/CalcViewModel/Common/ExpressionCommandDeserializer.cpp +++ b/src/CalcViewModel/Common/ExpressionCommandDeserializer.cpp @@ -7,7 +7,8 @@ using namespace CalculatorApp::Common; using namespace Windows::Storage::Streams; -CommandDeserializer::CommandDeserializer(_In_ DataReader ^ dataReader) : m_dataReader(dataReader) +CommandDeserializer::CommandDeserializer(_In_ DataReader ^ dataReader) + : m_dataReader(dataReader) { } diff --git a/src/CalcViewModel/Common/ExpressionCommandSerializer.cpp b/src/CalcViewModel/Common/ExpressionCommandSerializer.cpp index 4dd97887..bbf9e183 100644 --- a/src/CalcViewModel/Common/ExpressionCommandSerializer.cpp +++ b/src/CalcViewModel/Common/ExpressionCommandSerializer.cpp @@ -7,7 +7,8 @@ using namespace CalculatorApp::Common; using namespace Windows::Storage::Streams; -SerializeCommandVisitor::SerializeCommandVisitor(_In_ DataWriter ^ dataWriter) : m_dataWriter(dataWriter) +SerializeCommandVisitor::SerializeCommandVisitor(_In_ DataWriter ^ dataWriter) + : m_dataWriter(dataWriter) { } diff --git a/src/CalcViewModel/Common/KeyboardShortcutManager.cpp b/src/CalcViewModel/Common/KeyboardShortcutManager.cpp index e9895147..7d9cfffa 100644 --- a/src/CalcViewModel/Common/KeyboardShortcutManager.cpp +++ b/src/CalcViewModel/Common/KeyboardShortcutManager.cpp @@ -446,8 +446,9 @@ const std::multimap& GetCurrentKeyDictionary(MyVirt { 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; } diff --git a/src/CalcViewModel/Common/KeyboardShortcutManager.h b/src/CalcViewModel/Common/KeyboardShortcutManager.h index 30b1aa24..6663f2ce 100644 --- a/src/CalcViewModel/Common/KeyboardShortcutManager.h +++ b/src/CalcViewModel/Common/KeyboardShortcutManager.h @@ -62,13 +62,13 @@ namespace CalculatorApp 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 + 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); + static void + OnVirtualKeyControlShiftChordPropertyChanged(Windows::UI::Xaml::DependencyObject ^ target, MyVirtualKey oldValue, MyVirtualKey newValue); static void OnCharacterReceivedHandler(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args); static void OnKeyDownHandler(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args); diff --git a/src/CalcViewModel/Common/LocalizationService.cpp b/src/CalcViewModel/Common/LocalizationService.cpp index 6f429651..24354e4b 100644 --- a/src/CalcViewModel/Common/LocalizationService.cpp +++ b/src/CalcViewModel/Common/LocalizationService.cpp @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" @@ -49,17 +49,34 @@ LocalizationService ^ LocalizationService::GetInstance() if (s_singletonInstance == nullptr) { - s_singletonInstance = ref new LocalizationService(); + s_singletonInstance = ref new LocalizationService(nullptr); } } return s_singletonInstance; } -LocalizationService::LocalizationService() +/// +/// Replace (or create) the single instance of this singleton class by one with the language passed as parameter +/// +/// RFC-5646 identifier of the language to use +/// +/// Should only be used for test purpose +/// +void LocalizationService::OverrideWithLanguage(_In_ const wchar_t * const language) { - m_language = ApplicationLanguages::Languages->GetAt(0); - m_flowDirection = - ResourceContext::GetForCurrentView()->QualifierValues->Lookup(L"LayoutDirection") != L"LTR" ? FlowDirection::RightToLeft : FlowDirection::LeftToRight; + s_singletonInstance = ref new LocalizationService(language); +} + +/// +/// Constructor +/// +/// RFC-5646 identifier of the language to use, if null, will use the current language of the system +LocalizationService::LocalizationService(_In_ const wchar_t * const overridedLanguage) +{ + m_isLanguageOverrided = overridedLanguage != nullptr; + m_language = m_isLanguageOverrided ? ref new Platform::String(overridedLanguage) : ApplicationLanguages::Languages->GetAt(0); + m_flowDirection = ResourceContext::GetForCurrentView()->QualifierValues->Lookup(L"LayoutDirection") + != L"LTR" ? FlowDirection::RightToLeft : FlowDirection::LeftToRight; auto resourceLoader = AppResourceProvider::GetInstance(); m_fontFamilyOverride = resourceLoader.GetResourceString(L"LocalizedFontFamilyOverride"); @@ -339,7 +356,7 @@ void LocalizationService::UpdateFontFamilyAndSize(DependencyObject ^ target) // If successful, returns a formatter that respects the user's regional format settings, // as configured by running intl.cpl. -DecimalFormatter ^ LocalizationService::GetRegionalSettingsAwareDecimalFormatter() +DecimalFormatter ^ LocalizationService::GetRegionalSettingsAwareDecimalFormatter() const { IIterable ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); if (languageIdentifiers != nullptr) @@ -354,7 +371,7 @@ DecimalFormatter ^ LocalizationService::GetRegionalSettingsAwareDecimalFormatter // as configured by running intl.cpl. // // This helper function creates a DateTimeFormatter with a TwentyFour hour clock -DateTimeFormatter ^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(_In_ String ^ format) +DateTimeFormatter ^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(_In_ String^ format) const { IIterable ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); if (languageIdentifiers == nullptr) @@ -367,8 +384,7 @@ DateTimeFormatter ^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatt // If successful, returns a formatter that respects the user's regional format settings, // as configured by running intl.cpl. -DateTimeFormatter - ^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(_In_ String ^ format, _In_ String ^ calendarIdentifier, _In_ String ^ clockIdentifier) +DateTimeFormatter^ LocalizationService::GetRegionalSettingsAwareDateTimeFormatter(_In_ String ^ format, _In_ String ^ calendarIdentifier, _In_ String ^ clockIdentifier) const { IIterable ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); if (languageIdentifiers == nullptr) @@ -379,12 +395,12 @@ DateTimeFormatter return ref new DateTimeFormatter(format, languageIdentifiers, GlobalizationPreferences::HomeGeographicRegion, calendarIdentifier, clockIdentifier); } -CurrencyFormatter ^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatter() +CurrencyFormatter ^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatter() const { String ^ userCurrency = (GlobalizationPreferences::Currencies->Size > 0) ? GlobalizationPreferences::Currencies->GetAt(0) : StringReference(DefaultCurrencyCode.data()); - IIterable ^ languageIdentifiers = LocalizationService::GetLanguageIdentifiers(); + IIterable ^ languageIdentifiers = GetLanguageIdentifiers(); if (languageIdentifiers == nullptr) { languageIdentifiers = ApplicationLanguages::Languages; @@ -398,10 +414,18 @@ CurrencyFormatter ^ LocalizationService::GetRegionalSettingsAwareCurrencyFormatt return currencyFormatter; } -IIterable ^ LocalizationService::GetLanguageIdentifiers() +IIterable ^ LocalizationService::GetLanguageIdentifiers() const { WCHAR currentLocale[LOCALE_NAME_MAX_LENGTH] = {}; int result = GetUserDefaultLocaleName(currentLocale, LOCALE_NAME_MAX_LENGTH); + + if (m_isLanguageOverrided) + { + auto overridedLanguageList = ref new Vector(); + overridedLanguageList->Append(m_language); + return overridedLanguageList; + } + if (result != 0) { // GetUserDefaultLocaleName may return an invalid bcp47 language tag with trailing non-BCP47 friendly characters, @@ -434,28 +458,41 @@ unordered_map LocalizationService::GetTokenToReadableNameMap() // change given that the engine heavily relies on perfect ordering of certain elements. // To compromise, we'll declare a map from engine resource key to automation name from the // standard project resources. - static vector> s_parenEngineKeyResourceMap = { - // Sine permutations - make_pair(L"67", L"SineDegrees"), make_pair(L"73", L"SineRadians"), - make_pair(L"79", L"SineGradians"), make_pair(L"70", L"InverseSineDegrees"), - make_pair(L"76", L"InverseSineRadians"), make_pair(L"82", L"InverseSineGradians"), - make_pair(L"25", L"HyperbolicSine"), make_pair(L"85", L"InverseHyperbolicSine"), + static vector> s_parenEngineKeyResourceMap = { // Sine permutations + make_pair(L"67", L"SineDegrees"), + make_pair(L"73", L"SineRadians"), + make_pair(L"79", L"SineGradians"), + make_pair(L"70", L"InverseSineDegrees"), + make_pair(L"76", L"InverseSineRadians"), + make_pair(L"82", L"InverseSineGradians"), + make_pair(L"25", L"HyperbolicSine"), + make_pair(L"85", L"InverseHyperbolicSine"), - // Cosine permutations - make_pair(L"68", L"CosineDegrees"), make_pair(L"74", L"CosineRadians"), - make_pair(L"80", L"CosineGradians"), make_pair(L"71", L"InverseCosineDegrees"), - make_pair(L"77", L"InverseCosineRadians"), make_pair(L"83", L"InverseCosineGradians"), - make_pair(L"26", L"HyperbolicCosine"), make_pair(L"86", L"InverseHyperbolicCosine"), + // Cosine permutations + make_pair(L"68", L"CosineDegrees"), + make_pair(L"74", L"CosineRadians"), + make_pair(L"80", L"CosineGradians"), + make_pair(L"71", L"InverseCosineDegrees"), + make_pair(L"77", L"InverseCosineRadians"), + make_pair(L"83", L"InverseCosineGradians"), + make_pair(L"26", L"HyperbolicCosine"), + make_pair(L"86", L"InverseHyperbolicCosine"), - // Tangent permutations - make_pair(L"69", L"TangentDegrees"), make_pair(L"75", L"TangentRadians"), - make_pair(L"81", L"TangentGradians"), make_pair(L"72", L"InverseTangentDegrees"), - make_pair(L"78", L"InverseTangentRadians"), make_pair(L"84", L"InverseTangentGradians"), - make_pair(L"27", L"HyperbolicTangent"), make_pair(L"87", L"InverseHyperbolicTangent"), + // Tangent permutations + make_pair(L"69", L"TangentDegrees"), + make_pair(L"75", L"TangentRadians"), + make_pair(L"81", L"TangentGradians"), + make_pair(L"72", L"InverseTangentDegrees"), + make_pair(L"78", L"InverseTangentRadians"), + make_pair(L"84", L"InverseTangentGradians"), + make_pair(L"27", L"HyperbolicTangent"), + make_pair(L"87", L"InverseHyperbolicTangent"), - // Miscellaneous Scientific functions - make_pair(L"94", L"Factorial"), make_pair(L"35", L"DegreeMinuteSecond"), - make_pair(L"28", L"NaturalLog"), make_pair(L"91", L"Square") + // Miscellaneous Scientific functions + make_pair(L"94", L"Factorial"), + make_pair(L"35", L"DegreeMinuteSecond"), + make_pair(L"28", L"NaturalLog"), + make_pair(L"91", L"Square") }; static vector> s_noParenEngineKeyResourceMap = { // Programmer mode functions diff --git a/src/CalcViewModel/Common/LocalizationService.h b/src/CalcViewModel/Common/LocalizationService.h index f288d54e..736d5647 100644 --- a/src/CalcViewModel/Common/LocalizationService.h +++ b/src/CalcViewModel/Common/LocalizationService.h @@ -30,7 +30,9 @@ namespace CalculatorApp DEPENDENCY_PROPERTY_ATTACHED_WITH_DEFAULT_AND_CALLBACK(LanguageFontType, FontType, LanguageFontType::UIText); DEPENDENCY_PROPERTY_ATTACHED_WITH_CALLBACK(double, FontSize); - internal : static LocalizationService ^ GetInstance(); + internal: + static LocalizationService^ GetInstance(); + static void OverrideWithLanguage(_In_ const wchar_t * const language); Windows::UI::Xaml::FlowDirection GetFlowDirection(); bool IsRtlLayout(); @@ -41,46 +43,48 @@ namespace CalculatorApp Windows::UI::Text::FontWeight GetFontWeightOverride(); double GetFontScaleFactorOverride(LanguageFontType fontType); - 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, _In_ Platform::String ^ calendarIdentifier, - _In_ Platform::String ^ clockIdentifier); + Windows::Globalization::NumberFormatting::DecimalFormatter ^ GetRegionalSettingsAwareDecimalFormatter() const; + Windows::Globalization::DateTimeFormatting::DateTimeFormatter ^ GetRegionalSettingsAwareDateTimeFormatter(_In_ Platform::String ^ format) const; + Windows::Globalization::DateTimeFormatting::DateTimeFormatter ^ GetRegionalSettingsAwareDateTimeFormatter( + _In_ Platform::String ^ format, + _In_ Platform::String ^ calendarIdentifier, + _In_ Platform::String ^ clockIdentifier) const; - static Windows::Globalization::NumberFormatting::CurrencyFormatter ^ GetRegionalSettingsAwareCurrencyFormatter(); + Windows::Globalization::NumberFormatting::CurrencyFormatter ^ GetRegionalSettingsAwareCurrencyFormatter() const; static Platform::String ^ GetNarratorReadableToken(Platform::String ^ rawToken); static Platform::String ^ GetNarratorReadableString(Platform::String ^ rawString); private: + LocalizationService(_In_ const wchar_t* const overridedLanguage); Windows::Globalization::Fonts::LanguageFont ^ GetLanguageFont(LanguageFontType fontType); Windows::UI::Text::FontWeight ParseFontWeight(Platform::String ^ fontWeight); - static Windows::Foundation::Collections::IIterable ^ GetLanguageIdentifiers(); + Windows::Foundation::Collections::IIterable ^ GetLanguageIdentifiers() const; // Attached property callbacks 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 UpdateFontFamilyAndSize(Windows::UI::Xaml::DependencyObject ^ target); static std::unordered_map GetTokenToReadableNameMap(); - private: - LocalizationService(); - static LocalizationService ^ s_singletonInstance; - Windows::Globalization::Fonts::LanguageFontGroup ^ m_fontGroup; - Platform::String ^ m_language; - Windows::UI::Xaml::FlowDirection m_flowDirection; - bool m_overrideFontApiValues; - Platform::String ^ m_fontFamilyOverride; - Windows::UI::Text::FontWeight m_fontWeightOverride; - double m_uiTextFontScaleFactorOverride; - double m_uiCaptionFontScaleFactorOverride; + Windows::Globalization::Fonts::LanguageFontGroup ^ m_fontGroup; + Platform::String ^ m_language; + Windows::UI::Xaml::FlowDirection m_flowDirection; + bool m_overrideFontApiValues; + Platform::String ^ m_fontFamilyOverride; + bool m_isLanguageOverrided; + Windows::UI::Text::FontWeight m_fontWeightOverride; + double m_uiTextFontScaleFactorOverride; + double m_uiCaptionFontScaleFactorOverride; }; } diff --git a/src/CalcViewModel/Common/LocalizationSettings.h b/src/CalcViewModel/Common/LocalizationSettings.h index 881c592d..addc0c39 100644 --- a/src/CalcViewModel/Common/LocalizationSettings.h +++ b/src/CalcViewModel/Common/LocalizationSettings.h @@ -19,7 +19,7 @@ namespace CalculatorApp // Use DecimalFormatter as it respects the locale and the user setting Windows::Globalization::NumberFormatting::DecimalFormatter ^ formatter; - formatter = CalculatorApp::Common::LocalizationService::GetRegionalSettingsAwareDecimalFormatter(); + formatter = LocalizationService::GetInstance()->GetRegionalSettingsAwareDecimalFormatter(); formatter->FractionDigits = 0; formatter->IsDecimalPointAlwaysDisplayed = false; @@ -60,16 +60,22 @@ namespace CalculatorApp // Get locale info for List Separator, eg. comma is used in many locales wchar_t listSeparatorString[4] = L""; - result = ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SLIST, listSeparatorString, - static_cast(std::size(listSeparatorString))); // Max length of the expected return value is 4 + result = ::GetLocaleInfoEx( + m_resolvedName.c_str(), + LOCALE_SLIST, + listSeparatorString, + static_cast(std::size(listSeparatorString))); // Max length of the expected return value is 4 if (result == 0) { throw std::runtime_error("Unexpected error while getting locale info"); } int currencyTrailingDigits = 0; - result = GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER, (LPWSTR)¤cyTrailingDigits, - sizeof(currencyTrailingDigits) / sizeof(WCHAR)); + result = GetLocaleInfoEx( + m_resolvedName.c_str(), + LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER, + (LPWSTR)¤cyTrailingDigits, + sizeof(currencyTrailingDigits) / sizeof(WCHAR)); if (result == 0) { throw std::runtime_error("Unexpected error while getting locale info"); @@ -78,8 +84,11 @@ namespace CalculatorApp // Currency symbol precedence is either 0 or 1. // A value of 0 indicates the symbol follows the currency value. int currencySymbolPrecedence = 1; - result = GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_IPOSSYMPRECEDES | LOCALE_RETURN_NUMBER, (LPWSTR)¤cySymbolPrecedence, - sizeof(currencySymbolPrecedence) / sizeof(WCHAR)); + result = GetLocaleInfoEx( + m_resolvedName.c_str(), + LOCALE_IPOSSYMPRECEDES | LOCALE_RETURN_NUMBER, + (LPWSTR)¤cySymbolPrecedence, + sizeof(currencySymbolPrecedence) / sizeof(WCHAR)); // As CalcEngine only supports the first character of the decimal separator, // Only first character of the decimal separator string is supported. @@ -95,16 +104,17 @@ namespace CalculatorApp // Note: This function returns 0 on failure. // We'll ignore the failure in that case and the CalendarIdentifier would get set to GregorianCalendar. CALID calId; - ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_ICALENDARTYPE | LOCALE_RETURN_NUMBER, reinterpret_cast(&calId), sizeof(calId)); + ::GetLocaleInfoEx(m_resolvedName.c_str(), LOCALE_ICALENDARTYPE | LOCALE_RETURN_NUMBER, reinterpret_cast(&calId), sizeof(calId)); m_calendarIdentifier = GetCalendarIdentifierFromCalid(calId); // Get FirstDayOfWeek Date and Time setting wchar_t day[80] = L""; - ::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, - LOCALE_IFIRSTDAYOFWEEK, // The first day in a week - reinterpret_cast(day), // Argument is of type PWSTR - static_cast(std::size(day))); // Max return size are 80 characters + ::GetLocaleInfoEx( + m_resolvedName.c_str(), + LOCALE_IFIRSTDAYOFWEEK, // The first day in a week + reinterpret_cast(day), // Argument is of type PWSTR + static_cast(std::size(day))); // Max return size are 80 characters // The LOCALE_IFIRSTDAYOFWEEK integer value varies from 0, 1, .. 6 for Monday, Tuesday, ... Sunday // DayOfWeek enum value varies from 0, 1, .. 6 for Sunday, Monday, ... Saturday diff --git a/src/CalcViewModel/Common/NavCategory.cpp b/src/CalcViewModel/Common/NavCategory.cpp index da8de6e4..9dfd905c 100644 --- a/src/CalcViewModel/Common/NavCategory.cpp +++ b/src/CalcViewModel/Common/NavCategory.cpp @@ -49,42 +49,142 @@ static constexpr int CURRENCY_ID = 16; // ^^^ THESE CONSTANTS SHOULD NEVER CHANGE ^^^ // The order of items in this list determines the order of items in the menu. -static constexpr array s_categoryManifest = { - NavCategoryInitializer{ ViewMode::Standard, STANDARD_ID, L"Standard", L"StandardMode", L"\uE8EF", CategoryGroupType::Calculator, MyVirtualKey::Number1, - SUPPORTS_ALL }, - NavCategoryInitializer{ ViewMode::Scientific, SCIENTIFIC_ID, L"Scientific", L"ScientificMode", L"\uF196", CategoryGroupType::Calculator, - MyVirtualKey::Number2, SUPPORTS_ALL }, - NavCategoryInitializer{ ViewMode::Programmer, PROGRAMMER_ID, L"Programmer", L"ProgrammerMode", L"\uECCE", CategoryGroupType::Calculator, - MyVirtualKey::Number3, SUPPORTS_ALL }, - NavCategoryInitializer{ ViewMode::Date, DATE_ID, L"Date", L"DateCalculationMode", L"\uE787", CategoryGroupType::Calculator, MyVirtualKey::Number4, - SUPPORTS_ALL }, - NavCategoryInitializer{ ViewMode::Currency, CURRENCY_ID, L"Currency", L"CategoryName_Currency", L"\uEB0D", CategoryGroupType::Converter, MyVirtualKey::None, - POSITIVE_ONLY }, - NavCategoryInitializer{ ViewMode::Volume, VOLUME_ID, L"Volume", L"CategoryName_Volume", L"\uF1AA", CategoryGroupType::Converter, MyVirtualKey::None, - POSITIVE_ONLY }, - NavCategoryInitializer{ ViewMode::Length, LENGTH_ID, L"Length", L"CategoryName_Length", L"\uECC6", CategoryGroupType::Converter, MyVirtualKey::None, - POSITIVE_ONLY }, - NavCategoryInitializer{ ViewMode::Weight, WEIGHT_ID, L"Weight and Mass", L"CategoryName_Weight", L"\uF4C1", 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 } -}; +static constexpr array s_categoryManifest = { NavCategoryInitializer{ ViewMode::Standard, + STANDARD_ID, + L"Standard", + L"StandardMode", + L"\uE8EF", + CategoryGroupType::Calculator, + MyVirtualKey::Number1, + SUPPORTS_ALL }, + NavCategoryInitializer{ ViewMode::Scientific, + SCIENTIFIC_ID, + L"Scientific", + L"ScientificMode", + L"\uF196", + CategoryGroupType::Calculator, + MyVirtualKey::Number2, + SUPPORTS_ALL }, + NavCategoryInitializer{ ViewMode::Programmer, + PROGRAMMER_ID, + L"Programmer", + L"ProgrammerMode", + L"\uECCE", + CategoryGroupType::Calculator, + MyVirtualKey::Number3, + SUPPORTS_ALL }, + NavCategoryInitializer{ ViewMode::Date, + DATE_ID, + L"Date", + L"DateCalculationMode", + L"\uE787", + CategoryGroupType::Calculator, + MyVirtualKey::Number4, + SUPPORTS_ALL }, + NavCategoryInitializer{ ViewMode::Currency, + CURRENCY_ID, + L"Currency", + L"CategoryName_Currency", + L"\uEB0D", + CategoryGroupType::Converter, + MyVirtualKey::None, + POSITIVE_ONLY }, + NavCategoryInitializer{ ViewMode::Volume, + VOLUME_ID, + L"Volume", + L"CategoryName_Volume", + L"\uF1AA", + CategoryGroupType::Converter, + MyVirtualKey::None, + POSITIVE_ONLY }, + NavCategoryInitializer{ ViewMode::Length, + LENGTH_ID, + L"Length", + L"CategoryName_Length", + L"\uECC6", + CategoryGroupType::Converter, + MyVirtualKey::None, + POSITIVE_ONLY }, + NavCategoryInitializer{ ViewMode::Weight, + WEIGHT_ID, + L"Weight and Mass", + L"CategoryName_Weight", + L"\uF4C1", + 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. int NavCategory::Serialize(ViewMode mode) @@ -105,8 +205,9 @@ ViewMode NavCategory::Deserialize(Platform::Object ^ obj) if (boxed != nullptr) { int serializationId = boxed->Value; - auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), - [serializationId](const NavCategoryInitializer& initializer) { return initializer.serializationId == serializationId; }); + auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [serializationId](const NavCategoryInitializer& initializer) { + return initializer.serializationId == serializationId; + }); if (iter != s_categoryManifest.end()) { @@ -144,8 +245,9 @@ bool NavCategory::IsConverterViewMode(ViewMode mode) bool NavCategory::IsModeInCategoryGroup(ViewMode mode, CategoryGroupType type) { - auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), - [mode, type](const NavCategoryInitializer& initializer) { return initializer.viewMode == mode && initializer.groupType == type; }); + auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [mode, type](const NavCategoryInitializer& initializer) { + return initializer.viewMode == mode && initializer.groupType == type; + }); return iter != s_categoryManifest.end(); } @@ -160,8 +262,9 @@ String ^ NavCategory::GetFriendlyName(ViewMode mode) ViewMode NavCategory::GetViewModeForFriendlyName(String ^ name) { - auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), - [name](const NavCategoryInitializer& initializer) { return wcscmp(initializer.friendlyName, name->Data()) == 0; }); + auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [name](const NavCategoryInitializer& initializer) { + return wcscmp(initializer.friendlyName, name->Data()) == 0; + }); return (iter != s_categoryManifest.end()) ? iter->viewMode : ViewMode::None; } @@ -238,8 +341,9 @@ int NavCategory::GetPosition(ViewMode mode) ViewMode NavCategory::GetViewModeForVirtualKey(MyVirtualKey virtualKey) { - auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), - [virtualKey](const NavCategoryInitializer& initializer) { return initializer.virtualKey == virtualKey; }); + auto iter = find_if(begin(s_categoryManifest), end(s_categoryManifest), [virtualKey](const NavCategoryInitializer& initializer) { + return initializer.virtualKey == virtualKey; + }); return (iter != s_categoryManifest.end()) ? iter->viewMode : ViewMode::None; } @@ -258,7 +362,8 @@ vector NavCategory::GetCategoryAcceleratorKeys() return accelerators; } -NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupInitializer) : m_Categories(ref new Vector()) +NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupInitializer) + : m_Categories(ref new Vector()) { m_GroupType = groupInitializer.type; @@ -285,9 +390,14 @@ NavCategoryGroup::NavCategoryGroup(const NavCategoryGroupInitializer& groupIniti String ^ categoryAutomationName = ref new String( LocalizationStringUtil::GetLocalizedString(navCategoryItemAutomationNameFormat->Data(), categoryName->Data(), m_Name->Data()).c_str()); - m_Categories->Append(ref new NavCategory(categoryName, categoryAutomationName, StringReference(categoryInitializer.glyph), - resProvider.GetResourceString(nameResourceKey + "AccessKey"), groupMode, categoryInitializer.viewMode, - categoryInitializer.supportsNegative)); + m_Categories->Append(ref new NavCategory( + categoryName, + categoryAutomationName, + StringReference(categoryInitializer.glyph), + resProvider.GetResourceString(nameResourceKey + "AccessKey"), + groupMode, + categoryInitializer.viewMode, + categoryInitializer.supportsNegative)); } } } @@ -313,16 +423,18 @@ NavCategoryGroup ^ NavCategoryGroup::CreateConverterCategory() vector NavCategoryGroup::GetInitializerCategoryGroup(CategoryGroupType groupType) { vector initializers{}; - copy_if(begin(s_categoryManifest), end(s_categoryManifest), back_inserter(initializers), - [groupType](const NavCategoryInitializer& initializer) { return initializer.groupType == groupType; }); + copy_if(begin(s_categoryManifest), end(s_categoryManifest), back_inserter(initializers), [groupType](const NavCategoryInitializer& initializer) { + return initializer.groupType == groupType; + }); return initializers; } String ^ NavCategoryGroup::GetHeaderResourceKey(CategoryGroupType type) { - auto iter = find_if(begin(s_categoryGroupManifest), end(s_categoryGroupManifest), - [type](const NavCategoryGroupInitializer& initializer) { return initializer.type == type; }); + auto iter = find_if(begin(s_categoryGroupManifest), end(s_categoryGroupManifest), [type](const NavCategoryGroupInitializer& initializer) { + return initializer.type == type; + }); return (iter != s_categoryGroupManifest.end()) ? StringReference(iter->headerResourceKey) : nullptr; } diff --git a/src/CalcViewModel/Common/NavCategory.h b/src/CalcViewModel/Common/NavCategory.h index 84cfb562..b1cf1d3d 100644 --- a/src/CalcViewModel/Common/NavCategory.h +++ b/src/CalcViewModel/Common/NavCategory.h @@ -58,8 +58,15 @@ namespace CalculatorApp private struct NavCategoryInitializer { - constexpr NavCategoryInitializer(ViewMode mode, int id, wchar_t const* name, wchar_t const* nameKey, wchar_t const* glyph, CategoryGroupType group, - MyVirtualKey vKey, bool categorySupportsNegative) + constexpr NavCategoryInitializer( + ViewMode mode, + int id, + wchar_t const* name, + wchar_t const* nameKey, + wchar_t const* glyph, + CategoryGroupType group, + MyVirtualKey vKey, + bool categorySupportsNegative) : viewMode(mode) , serializationId(id) , friendlyName(name) @@ -85,7 +92,10 @@ namespace CalculatorApp struct NavCategoryGroupInitializer { 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) { } @@ -161,8 +171,14 @@ namespace CalculatorApp static ViewMode GetViewModeForVirtualKey(MyVirtualKey virtualKey); - internal : NavCategory(Platform::String ^ name, Platform::String ^ automationName, Platform::String ^ glyph, Platform::String ^ accessKey, - Platform::String ^ mode, ViewMode viewMode, bool supportsNegative) + internal : NavCategory( + Platform::String ^ name, + Platform::String ^ automationName, + Platform::String ^ glyph, + Platform::String ^ accessKey, + Platform::String ^ mode, + ViewMode viewMode, + bool supportsNegative) : m_name(name) , m_automationName(automationName) , m_glyph(glyph) diff --git a/src/CalcViewModel/Common/TraceActivity.h b/src/CalcViewModel/Common/TraceActivity.h index cb0d481a..41046a63 100644 --- a/src/CalcViewModel/Common/TraceActivity.h +++ b/src/CalcViewModel/Common/TraceActivity.h @@ -11,19 +11,30 @@ namespace CalculatorApp class TraceActivity { public: - TraceActivity() : m_channel(nullptr), m_activity(nullptr), m_fields(nullptr) + TraceActivity() + : m_channel(nullptr) + , m_activity(nullptr) + , m_fields(nullptr) { } - TraceActivity(winrt::Windows::Foundation::Diagnostics::LoggingChannel channel, std::wstring_view activityName, - winrt::Windows::Foundation::Diagnostics::LoggingFields fields) - : m_channel(channel), m_activityName(activityName), m_fields(fields), m_activity(nullptr) + TraceActivity( + winrt::Windows::Foundation::Diagnostics::LoggingChannel channel, + std::wstring_view activityName, + 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 // or level for START and STOP events because they always use the activity's // keyword and level. - m_activity = m_channel.StartActivity(m_activityName, m_fields, winrt::Windows::Foundation::Diagnostics::LoggingLevel::Verbose, - winrt::Windows::Foundation::Diagnostics::LoggingOptions(WINEVENT_KEYWORD_RESPONSE_TIME)); + m_activity = m_channel.StartActivity( + m_activityName, + m_fields, + winrt::Windows::Foundation::Diagnostics::LoggingLevel::Verbose, + winrt::Windows::Foundation::Diagnostics::LoggingOptions(WINEVENT_KEYWORD_RESPONSE_TIME)); } ~TraceActivity() diff --git a/src/CalcViewModel/Common/TraceLogger.cpp b/src/CalcViewModel/Common/TraceLogger.cpp index 47da9511..f7d32d99 100644 --- a/src/CalcViewModel/Common/TraceLogger.cpp +++ b/src/CalcViewModel/Common/TraceLogger.cpp @@ -607,8 +607,8 @@ 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; diff --git a/src/CalcViewModel/Common/TraceLogger.h b/src/CalcViewModel/Common/TraceLogger.h index 3ae91ed5..870cddf8 100644 --- a/src/CalcViewModel/Common/TraceLogger.h +++ b/src/CalcViewModel/Common/TraceLogger.h @@ -96,8 +96,8 @@ namespace CalculatorApp // Trace methods for Date Calculator usage void LogDateDifferenceModeUsed(int windowId); 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 LogWinRTException(std::wstring_view functionName, _In_ winrt::hresult_error const& e) const; diff --git a/src/CalcViewModel/Common/Utils.cpp b/src/CalcViewModel/Common/Utils.cpp index 45d55e89..8ad60816 100644 --- a/src/CalcViewModel/Common/Utils.cpp +++ b/src/CalcViewModel/Common/Utils.cpp @@ -92,8 +92,10 @@ wstring Utils::RemoveUnwantedCharsFromWstring(wstring input, wchar_t* unwantedCh return input; } -void Utils::SerializeCommandsAndTokens(_In_ shared_ptr>> const& tokens, - _In_ shared_ptr>> const& commands, DataWriter ^ writer) +void Utils::SerializeCommandsAndTokens( + _In_ shared_ptr>> const& tokens, + _In_ shared_ptr>> const& commands, + DataWriter ^ writer) { unsigned int commandsSize; IFTPlatformException(commands->GetSize(&commandsSize)); diff --git a/src/CalcViewModel/Common/Utils.h b/src/CalcViewModel/Common/Utils.h index 4aefcc36..45eeefe2 100644 --- a/src/CalcViewModel/Common/Utils.h +++ b/src/CalcViewModel/Common/Utils.h @@ -384,9 +384,10 @@ namespace Utils double GetDoubleFromWstring(std::wstring input); int GetWindowId(); void RunOnUIThreadNonblocking(std::function&& function, _In_ Windows::UI::Core::CoreDispatcher ^ currentDispatcher); - void SerializeCommandsAndTokens(_In_ std::shared_ptr>> const& tokens, - _In_ std::shared_ptr>> const& commands, - Windows::Storage::Streams::DataWriter ^ writer); + void SerializeCommandsAndTokens( + _In_ std::shared_ptr>> const& tokens, + _In_ std::shared_ptr>> const& commands, + Windows::Storage::Streams::DataWriter ^ writer); const std::shared_ptr>> DeserializeCommands(Windows::Storage::Streams::DataReader ^ reader); const std::shared_ptr>> DeserializeTokens(Windows::Storage::Streams::DataReader ^ reader); @@ -394,8 +395,11 @@ namespace Utils Windows::Foundation::DateTime GetUniversalSystemTime(); bool IsDateTimeOlderThan(Windows::Foundation::DateTime dateTime, const long long duration); - concurrency::task WriteFileToFolder(Windows::Storage::IStorageFolder ^ folder, Platform::String ^ fileName, Platform::String ^ contents, - Windows::Storage::CreationCollisionOption collisionOption); + concurrency::task WriteFileToFolder( + Windows::Storage::IStorageFolder ^ folder, + Platform::String ^ fileName, + Platform::String ^ contents, + Windows::Storage::CreationCollisionOption collisionOption); concurrency::task ReadFileFromFolder(Windows::Storage::IStorageFolder ^ folder, Platform::String ^ fileName); } diff --git a/src/CalcViewModel/Common/ValidatingConverters.h b/src/CalcViewModel/Common/ValidatingConverters.h index b8f3f979..bc168502 100644 --- a/src/CalcViewModel/Common/ValidatingConverters.h +++ b/src/CalcViewModel/Common/ValidatingConverters.h @@ -17,16 +17,22 @@ namespace CalculatorApp private: virtual Platform::Object - ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert + ^ Convert( + Platform::Object ^ value, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert { // Pass through as we don't want to change the value from the source return value; } virtual Platform::Object - ^ ConvertBack(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack + ^ ConvertBack( + Platform::Object ^ value, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack { if (value) { @@ -47,16 +53,22 @@ namespace CalculatorApp private: virtual Platform::Object - ^ Convert(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert + ^ Convert( + Platform::Object ^ value, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::Convert { // Pass through as we don't want to change the value from the source return value; } virtual Platform::Object - ^ ConvertBack(Platform::Object ^ value, Windows::UI::Xaml::Interop::TypeName /*targetType*/, Platform::Object ^ /*parameter*/, - Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack + ^ ConvertBack( + Platform::Object ^ value, + Windows::UI::Xaml::Interop::TypeName /*targetType*/, + Platform::Object ^ /*parameter*/, + Platform::String ^ /*language*/) = Windows::UI::Xaml::Data::IValueConverter::ConvertBack { // The value to be valid has to be a boxed int32 value // extract that value and ensure it is valid, ie >= 0 diff --git a/src/CalcViewModel/DataLoaders/CurrencyDataLoader.cpp b/src/CalcViewModel/DataLoaders/CurrencyDataLoader.cpp index 211605fe..2fb8f0a6 100644 --- a/src/CalcViewModel/DataLoaders/CurrencyDataLoader.cpp +++ b/src/CalcViewModel/DataLoaders/CurrencyDataLoader.cpp @@ -46,8 +46,10 @@ static constexpr auto CACHE_LANGCODE_KEY = L"CURRENCY_CONVERTER_LANGCODE"; static constexpr auto CACHE_DELIMITER = L"%"; static constexpr auto STATIC_DATA_FILENAME = L"CURRENCY_CONVERTER_STATIC_DATA.txt"; -static constexpr array STATIC_DATA_PROPERTIES = { wstring_view{ L"CountryCode", 11 }, wstring_view{ L"CountryName", 11 }, - wstring_view{ L"CurrencyCode", 12 }, wstring_view{ L"CurrencyName", 12 }, +static constexpr array STATIC_DATA_PROPERTIES = { wstring_view{ L"CountryCode", 11 }, + wstring_view{ L"CountryName", 11 }, + 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"; @@ -85,7 +87,7 @@ namespace CalculatorApp } } -CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr client) +CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr client, const wchar_t * forcedResponseLanguage) : m_client(move(client)) , m_loadStatus(CurrencyLoadStatus::NotLoaded) , m_responseLanguage(L"en-US") @@ -94,9 +96,20 @@ CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr clie , m_networkManager(ref new NetworkManager()) , m_meteredOverrideSet(false) { - if (GlobalizationPreferences::Languages->Size > 0) + if (forcedResponseLanguage != nullptr) { - m_responseLanguage = GlobalizationPreferences::Languages->GetAt(0); + m_responseLanguage = ref new Platform::String(forcedResponseLanguage); + } + else + { + if (GlobalizationPreferences::Languages->Size > 0) + { + m_responseLanguage = GlobalizationPreferences::Languages->GetAt(0); + } + else + { + m_responseLanguage = L"en-US"; + } } if (m_client != nullptr) @@ -105,13 +118,14 @@ CurrencyDataLoader::CurrencyDataLoader(_In_ unique_ptr clie m_client->SetResponseLanguage(m_responseLanguage); } + auto localizationService = LocalizationService::GetInstance(); if (CoreWindow::GetForCurrentThread() != nullptr) { // Must have a CoreWindow to access the resource context. - m_isRtlLanguage = LocalizationService::GetInstance()->IsRtlLayout(); + m_isRtlLanguage = localizationService->IsRtlLayout(); } - m_ratioFormatter = LocalizationService::GetRegionalSettingsAwareDecimalFormatter(); + m_ratioFormatter = localizationService->GetRegionalSettingsAwareDecimalFormatter(); m_ratioFormatter->IsGrouped = true; m_ratioFormatter->IsDecimalPointAlwaysDisplayed = true; m_ratioFormatter->FractionDigits = FORMATTER_DIGIT_COUNT; @@ -275,8 +289,8 @@ pair CurrencyDataLoader::GetCurrencyRatioEquality(_In_ const U wstring digitSymbol = wstring{ LocalizationSettings::GetInstance().GetDigitSymbolFromEnUsDigit(L'1') }; wstring roundedFormat = m_ratioFormatter->Format(rounded)->Data(); - wstring ratioString = LocalizationStringUtil::GetLocalizedString(m_ratioFormat.c_str(), digitSymbol.c_str(), unit1.abbreviation.c_str(), - roundedFormat.c_str(), unit2.abbreviation.c_str()); + wstring ratioString = LocalizationStringUtil::GetLocalizedString( + m_ratioFormat.c_str(), digitSymbol.c_str(), unit1.abbreviation.c_str(), roundedFormat.c_str(), unit2.abbreviation.c_str()); wstring accessibleRatioString = LocalizationStringUtil::GetLocalizedString( m_ratioFormat.c_str(), digitSymbol.c_str(), unit1.accessibleName.c_str(), roundedFormat.c_str(), unit2.accessibleName.c_str()); @@ -459,8 +473,11 @@ task CurrencyDataLoader::TryLoadDataFromWebOverrideAsync() }; #pragma optimize("", on) -bool CurrencyDataLoader::TryParseWebResponses(_In_ String ^ staticDataJson, _In_ String ^ allRatiosJson, _Inout_ vector& staticData, - _Inout_ CurrencyRatioMap& allRatiosData) +bool CurrencyDataLoader::TryParseWebResponses( + _In_ String ^ staticDataJson, + _In_ String ^ allRatiosJson, + _Inout_ vector& staticData, + _Inout_ CurrencyRatioMap& allRatiosData) { return TryParseStaticData(staticDataJson, staticData) && TryParseAllRatiosData(allRatiosJson, allRatiosData); } diff --git a/src/CalcViewModel/DataLoaders/CurrencyDataLoader.h b/src/CalcViewModel/DataLoaders/CurrencyDataLoader.h index cfd1468d..1ec031d1 100644 --- a/src/CalcViewModel/DataLoaders/CurrencyDataLoader.h +++ b/src/CalcViewModel/DataLoaders/CurrencyDataLoader.h @@ -43,7 +43,8 @@ namespace CalculatorApp struct CurrencyUnitMetadata { - CurrencyUnitMetadata(const std::wstring& s) : symbol(s) + CurrencyUnitMetadata(const std::wstring& s) + : symbol(s) { } @@ -53,7 +54,7 @@ namespace CalculatorApp class CurrencyDataLoader : public UCM::IConverterDataLoader, public UCM::ICurrencyConverterDataLoader { public: - CurrencyDataLoader(_In_ std::unique_ptr client); + CurrencyDataLoader(_In_ std::unique_ptr client, const wchar_t* overrideLanguage = nullptr); ~CurrencyDataLoader(); bool LoadFinished(); @@ -71,8 +72,8 @@ namespace CalculatorApp // ICurrencyConverterDataLoader void SetViewModelCallback(const std::shared_ptr& callback) override; std::pair GetCurrencySymbols(const UCM::Unit& unit1, const UCM::Unit& unit2) override; - std::pair GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, - _In_ const UnitConversionManager::Unit& unit2) override; + std::pair + GetCurrencyRatioEquality(_In_ const UnitConversionManager::Unit& unit1, _In_ const UnitConversionManager::Unit& unit2) override; std::wstring GetCurrencyTimestamp() override; concurrency::task TryLoadDataFromCacheAsync() override; @@ -88,8 +89,11 @@ namespace CalculatorApp concurrency::task TryFinishLoadFromCacheAsync(); - bool TryParseWebResponses(_In_ Platform::String ^ staticDataJson, _In_ Platform::String ^ allRatiosJson, - _Inout_ std::vector& staticData, _Inout_ CurrencyRatioMap& allRatiosData); + bool TryParseWebResponses( + _In_ Platform::String ^ staticDataJson, + _In_ Platform::String ^ allRatiosJson, + _Inout_ std::vector& staticData, + _Inout_ CurrencyRatioMap& allRatiosData); bool TryParseStaticData(_In_ Platform::String ^ rawJson, _Inout_ std::vector& staticData); bool TryParseAllRatiosData(_In_ Platform::String ^ rawJson, _Inout_ CurrencyRatioMap& allRatiosData); concurrency::task FinalizeUnits(_In_ const std::vector& staticData, _In_ const CurrencyRatioMap& ratioMap); diff --git a/src/CalcViewModel/DataLoaders/CurrencyHttpClient.cpp b/src/CalcViewModel/DataLoaders/CurrencyHttpClient.cpp index 649ba171..04167dab 100644 --- a/src/CalcViewModel/DataLoaders/CurrencyHttpClient.cpp +++ b/src/CalcViewModel/DataLoaders/CurrencyHttpClient.cpp @@ -13,7 +13,9 @@ using namespace Windows::Web::Http; 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="; -CurrencyHttpClient::CurrencyHttpClient() : m_client(ref new HttpClient()), m_responseLanguage(L"en-US") +CurrencyHttpClient::CurrencyHttpClient() + : m_client(ref new HttpClient()) + , m_responseLanguage(L"en-US") { } diff --git a/src/CalcViewModel/DataLoaders/UnitConverterDataLoader.cpp b/src/CalcViewModel/DataLoaders/UnitConverterDataLoader.cpp index 24c3518e..e69b8e2c 100644 --- a/src/CalcViewModel/DataLoaders/UnitConverterDataLoader.cpp +++ b/src/CalcViewModel/DataLoaders/UnitConverterDataLoader.cpp @@ -18,7 +18,8 @@ using namespace Windows::Globalization; static constexpr bool CONVERT_WITH_OFFSET_FIRST = true; -UnitConverterDataLoader::UnitConverterDataLoader(GeographicRegion ^ region) : m_currentRegionCode(region->CodeTwoLetter) +UnitConverterDataLoader::UnitConverterDataLoader(GeographicRegion ^ region) + : m_currentRegionCode(region->CodeTwoLetter) { m_categoryList = make_shared>(); m_categoryToUnits = make_shared(); @@ -53,8 +54,9 @@ bool UnitConverterDataLoader::SupportsCategory(const UCM::Category& target) } static int currencyId = NavCategory::Serialize(ViewMode::Currency); - auto itr = find_if(supportedCategories->begin(), supportedCategories->end(), - [&](const UCM::Category& category) { return currencyId != category.id && target.id == category.id; }); + auto itr = find_if(supportedCategories->begin(), supportedCategories->end(), [&](const UCM::Category& category) { + return currencyId != category.id && target.id == category.id; + }); return itr != supportedCategories->end(); } @@ -182,34 +184,65 @@ void UnitConverterDataLoader::GetUnits(_In_ unordered_map 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"), + GetLocalizedStringName(L"UnitAbbreviation_BritishThermalUnit"), + 7 }); energyUnits.push_back( OrderedUnit{ UnitConverterUnits::Energy_Calorie, GetLocalizedStringName(L"UnitName_Calorie"), GetLocalizedStringName(L"UnitAbbreviation_Calorie"), 4 }); - energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_ElectronVolt, GetLocalizedStringName(L"UnitName_Electron-Volt"), - GetLocalizedStringName(L"UnitAbbreviation_Electron-Volt"), 1 }); - energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_FootPound, GetLocalizedStringName(L"UnitName_Foot-Pound"), - GetLocalizedStringName(L"UnitAbbreviation_Foot-Pound"), 6 }); - 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_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 }); + energyUnits.push_back(OrderedUnit{ UnitConverterUnits::Energy_ElectronVolt, + GetLocalizedStringName(L"UnitName_Electron-Volt"), + GetLocalizedStringName(L"UnitAbbreviation_Electron-Volt"), + 1 }); + energyUnits.push_back(OrderedUnit{ + UnitConverterUnits::Energy_FootPound, GetLocalizedStringName(L"UnitName_Foot-Pound"), GetLocalizedStringName(L"UnitAbbreviation_Foot-Pound"), 6 }); + 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_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); vector 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"), + GetLocalizedStringName(L"UnitAbbreviation_Centimeter"), + 4, + useUSCustomary, + useSI, + false }); lengthUnits.push_back( OrderedUnit{ UnitConverterUnits::Length_Foot, GetLocalizedStringName(L"UnitName_Foot"), GetLocalizedStringName(L"UnitAbbreviation_Foot"), 8 }); - lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Inch, GetLocalizedStringName(L"UnitName_Inch"), - GetLocalizedStringName(L"UnitAbbreviation_Inch"), 7, useSI, useUSCustomary, false }); - lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Kilometer, GetLocalizedStringName(L"UnitName_Kilometer"), - GetLocalizedStringName(L"UnitAbbreviation_Kilometer"), 6 }); + lengthUnits.push_back(OrderedUnit{ UnitConverterUnits::Length_Inch, + GetLocalizedStringName(L"UnitName_Inch"), + GetLocalizedStringName(L"UnitAbbreviation_Inch"), + 7, + useSI, + useUSCustomary, + false }); + lengthUnits.push_back(OrderedUnit{ + UnitConverterUnits::Length_Kilometer, GetLocalizedStringName(L"UnitName_Kilometer"), GetLocalizedStringName(L"UnitAbbreviation_Kilometer"), 6 }); lengthUnits.push_back( OrderedUnit{ UnitConverterUnits::Length_Meter, GetLocalizedStringName(L"UnitName_Meter"), GetLocalizedStringName(L"UnitAbbreviation_Meter"), 5 }); lengthUnits.push_back( OrderedUnit{ UnitConverterUnits::Length_Micron, GetLocalizedStringName(L"UnitName_Micron"), GetLocalizedStringName(L"UnitAbbreviation_Micron"), 2 }); lengthUnits.push_back( 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_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 }); + 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); vector powerUnits; - powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_BritishThermalUnitPerMinute, GetLocalizedStringName(L"UnitName_BTUPerMinute"), - GetLocalizedStringName(L"UnitAbbreviation_BTUPerMinute"), 5 }); - powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_FootPoundPerMinute, GetLocalizedStringName(L"UnitName_Foot-PoundPerMinute"), - GetLocalizedStringName(L"UnitAbbreviation_Foot-PoundPerMinute"), 4 }); - 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_Kilowatt, GetLocalizedStringName(L"UnitName_Kilowatt"), - 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 }); + powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_BritishThermalUnitPerMinute, + GetLocalizedStringName(L"UnitName_BTUPerMinute"), + GetLocalizedStringName(L"UnitAbbreviation_BTUPerMinute"), + 5 }); + powerUnits.push_back(OrderedUnit{ UnitConverterUnits::Power_FootPoundPerMinute, + GetLocalizedStringName(L"UnitName_Foot-PoundPerMinute"), + GetLocalizedStringName(L"UnitAbbreviation_Foot-PoundPerMinute"), + 4 }); + 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_Kilowatt, + GetLocalizedStringName(L"UnitName_Kilowatt"), + 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); vector 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_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 }); + 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_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); vector timeUnits; timeUnits.push_back( OrderedUnit{ UnitConverterUnits::Time_Day, GetLocalizedStringName(L"UnitName_Day"), GetLocalizedStringName(L"UnitAbbreviation_Day"), 6 }); - timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Hour, GetLocalizedStringName(L"UnitName_Hour"), GetLocalizedStringName(L"UnitAbbreviation_Hour"), - 5, true, false, false }); - timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Microsecond, GetLocalizedStringName(L"UnitName_Microsecond"), - GetLocalizedStringName(L"UnitAbbreviation_Microsecond"), 1 }); - timeUnits.push_back(OrderedUnit{ UnitConverterUnits::Time_Millisecond, GetLocalizedStringName(L"UnitName_Millisecond"), - 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_Hour, GetLocalizedStringName(L"UnitName_Hour"), GetLocalizedStringName(L"UnitAbbreviation_Hour"), 5, true, false, false }); + timeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Time_Microsecond, GetLocalizedStringName(L"UnitName_Microsecond"), GetLocalizedStringName(L"UnitAbbreviation_Microsecond"), 1 }); + timeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Time_Millisecond, GetLocalizedStringName(L"UnitName_Millisecond"), 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( @@ -392,136 +531,239 @@ void UnitConverterDataLoader::GetUnits(_In_ unordered_map speedUnits; - speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_CentimetersPerSecond, GetLocalizedStringName(L"UnitName_CentimetersPerSecond"), - GetLocalizedStringName(L"UnitAbbreviation_CentimetersPerSecond"), 1 }); - speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_FeetPerSecond, GetLocalizedStringName(L"UnitName_FeetPerSecond"), - GetLocalizedStringName(L"UnitAbbreviation_FeetPerSecond"), 4 }); - 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_CentimetersPerSecond, + GetLocalizedStringName(L"UnitName_CentimetersPerSecond"), + GetLocalizedStringName(L"UnitAbbreviation_CentimetersPerSecond"), + 1 }); + speedUnits.push_back(OrderedUnit{ UnitConverterUnits::Speed_FeetPerSecond, + GetLocalizedStringName(L"UnitName_FeetPerSecond"), + GetLocalizedStringName(L"UnitAbbreviation_FeetPerSecond"), + 4 }); + 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_Knot, GetLocalizedStringName(L"UnitName_Knot"), GetLocalizedStringName(L"UnitAbbreviation_Knot"), 6 }); speedUnits.push_back( 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 }); + 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); vector volumeUnits; - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicCentimeter, GetLocalizedStringName(L"UnitName_CubicCentimeter"), - GetLocalizedStringName(L"UnitAbbreviation_CubicCentimeter"), 2 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicFoot, GetLocalizedStringName(L"UnitName_CubicFoot"), - GetLocalizedStringName(L"UnitAbbreviation_CubicFoot"), 13 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicInch, GetLocalizedStringName(L"UnitName_CubicInch"), - GetLocalizedStringName(L"UnitAbbreviation_CubicInch"), 12 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicMeter, GetLocalizedStringName(L"UnitName_CubicMeter"), - GetLocalizedStringName(L"UnitAbbreviation_CubicMeter"), 4 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicYard, GetLocalizedStringName(L"UnitName_CubicYard"), - GetLocalizedStringName(L"UnitAbbreviation_CubicYard"), 14 }); + volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_CubicCentimeter, + GetLocalizedStringName(L"UnitName_CubicCentimeter"), + GetLocalizedStringName(L"UnitAbbreviation_CubicCentimeter"), + 2 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_CubicFoot, GetLocalizedStringName(L"UnitName_CubicFoot"), GetLocalizedStringName(L"UnitAbbreviation_CubicFoot"), 13 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_CubicInch, GetLocalizedStringName(L"UnitName_CubicInch"), GetLocalizedStringName(L"UnitAbbreviation_CubicInch"), 12 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_CubicMeter, GetLocalizedStringName(L"UnitName_CubicMeter"), GetLocalizedStringName(L"UnitAbbreviation_CubicMeter"), 4 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_CubicYard, GetLocalizedStringName(L"UnitName_CubicYard"), GetLocalizedStringName(L"UnitAbbreviation_CubicYard"), 14 }); volumeUnits.push_back( OrderedUnit{ UnitConverterUnits::Volume_CupUS, GetLocalizedStringName(L"UnitName_CupUS"), GetLocalizedStringName(L"UnitAbbreviation_CupUS"), 8 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUK, GetLocalizedStringName(L"UnitName_FluidOunceUK"), - GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUK"), 17 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUS, GetLocalizedStringName(L"UnitName_FluidOunceUS"), - GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUS"), 7 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUK, GetLocalizedStringName(L"UnitName_GallonUK"), - GetLocalizedStringName(L"UnitAbbreviation_GallonUK"), 20 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_GallonUS, GetLocalizedStringName(L"UnitName_GallonUS"), - GetLocalizedStringName(L"UnitAbbreviation_GallonUS"), 11 }); + volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUK, + GetLocalizedStringName(L"UnitName_FluidOunceUK"), + GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUK"), + 17 }); + volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_FluidOunceUS, + GetLocalizedStringName(L"UnitName_FluidOunceUS"), + GetLocalizedStringName(L"UnitAbbreviation_FluidOunceUS"), + 7 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_GallonUK, GetLocalizedStringName(L"UnitName_GallonUK"), GetLocalizedStringName(L"UnitAbbreviation_GallonUK"), 20 }); + volumeUnits.push_back(OrderedUnit{ + UnitConverterUnits::Volume_GallonUS, GetLocalizedStringName(L"UnitName_GallonUS"), GetLocalizedStringName(L"UnitAbbreviation_GallonUS"), 11 }); volumeUnits.push_back( OrderedUnit{ UnitConverterUnits::Volume_Liter, GetLocalizedStringName(L"UnitName_Liter"), GetLocalizedStringName(L"UnitAbbreviation_Liter"), 3 }); - volumeUnits.push_back(OrderedUnit{ UnitConverterUnits::Volume_Milliliter, GetLocalizedStringName(L"UnitName_Milliliter"), - GetLocalizedStringName(L"UnitAbbreviation_Milliliter"), 1, useUSCustomary, useSI }); + 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 }); + 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); vector weightUnits; weightUnits.push_back( OrderedUnit{ UnitConverterUnits::Weight_Carat, GetLocalizedStringName(L"UnitName_Carat"), GetLocalizedStringName(L"UnitAbbreviation_Carat"), 1 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Centigram, GetLocalizedStringName(L"UnitName_Centigram"), - GetLocalizedStringName(L"UnitAbbreviation_Centigram"), 3 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decigram, GetLocalizedStringName(L"UnitName_Decigram"), - GetLocalizedStringName(L"UnitAbbreviation_Decigram"), 4 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Decagram, GetLocalizedStringName(L"UnitName_Decagram"), - GetLocalizedStringName(L"UnitAbbreviation_Decagram"), 6 }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_Centigram, GetLocalizedStringName(L"UnitName_Centigram"), GetLocalizedStringName(L"UnitAbbreviation_Centigram"), 3 }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_Decigram, GetLocalizedStringName(L"UnitName_Decigram"), GetLocalizedStringName(L"UnitAbbreviation_Decigram"), 4 }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_Decagram, GetLocalizedStringName(L"UnitName_Decagram"), GetLocalizedStringName(L"UnitAbbreviation_Decagram"), 6 }); weightUnits.push_back( OrderedUnit{ UnitConverterUnits::Weight_Gram, GetLocalizedStringName(L"UnitName_Gram"), GetLocalizedStringName(L"UnitAbbreviation_Gram"), 5 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Hectogram, GetLocalizedStringName(L"UnitName_Hectogram"), - GetLocalizedStringName(L"UnitAbbreviation_Hectogram"), 7 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Kilogram, GetLocalizedStringName(L"UnitName_Kilogram"), - GetLocalizedStringName(L"UnitAbbreviation_Kilogram"), 8, useUSCustomary, useSI }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_LongTon, GetLocalizedStringName(L"UnitName_LongTon"), - GetLocalizedStringName(L"UnitAbbreviation_LongTon"), 14 }); - weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Milligram, GetLocalizedStringName(L"UnitName_Milligram"), - GetLocalizedStringName(L"UnitAbbreviation_Milligram"), 2 }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_Hectogram, GetLocalizedStringName(L"UnitName_Hectogram"), GetLocalizedStringName(L"UnitAbbreviation_Hectogram"), 7 }); + weightUnits.push_back(OrderedUnit{ UnitConverterUnits::Weight_Kilogram, + GetLocalizedStringName(L"UnitName_Kilogram"), + GetLocalizedStringName(L"UnitAbbreviation_Kilogram"), + 8, + useUSCustomary, + useSI }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_LongTon, GetLocalizedStringName(L"UnitName_LongTon"), GetLocalizedStringName(L"UnitAbbreviation_LongTon"), 14 }); + weightUnits.push_back(OrderedUnit{ + UnitConverterUnits::Weight_Milligram, GetLocalizedStringName(L"UnitName_Milligram"), 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_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 }); + 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); vector 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_Bar, GetLocalizedStringName(L"UnitName_Bar"), - GetLocalizedStringName(L"UnitAbbreviation_Bar"), 2, false, true, false }); - pressureUnits.push_back(OrderedUnit{ UnitConverterUnits::Pressure_KiloPascal, GetLocalizedStringName(L"UnitName_KiloPascal"), - 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_Atmosphere, + GetLocalizedStringName(L"UnitName_Atmosphere"), + GetLocalizedStringName(L"UnitAbbreviation_Atmosphere"), + 1, + true, + false, + false }); + pressureUnits.push_back(OrderedUnit{ + UnitConverterUnits::Pressure_Bar, GetLocalizedStringName(L"UnitName_Bar"), GetLocalizedStringName(L"UnitAbbreviation_Bar"), 2, false, true, false }); + pressureUnits.push_back(OrderedUnit{ + UnitConverterUnits::Pressure_KiloPascal, GetLocalizedStringName(L"UnitName_KiloPascal"), 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 }); + pressureUnits.push_back(OrderedUnit{ + UnitConverterUnits::Pressure_PSI, GetLocalizedStringName(L"UnitName_PSI"), GetLocalizedStringName(L"UnitAbbreviation_PSI"), 6, false, false, false }); unitMap.emplace(ViewMode::Pressure, pressureUnits); vector 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_Radian, GetLocalizedStringName(L"UnitName_Radian"), - GetLocalizedStringName(L"UnitAbbreviation_Radian"), 2, false, true, false }); + 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_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); @@ -721,12 +963,24 @@ void UnitConverterDataLoader::GetExplicitConversionData(_In_ unordered_mapGetRegionalSettingsAwareDateTimeFormatter( + L"longdate", + calendarIdentifier, + ClockIdentifiers::TwentyFourHour); // Clock Identifier is not used // Format for Date Difference m_allDateUnitsOutputFormat = DateUnit::Year | DateUnit::Month | DateUnit::Week | DateUnit::Day; diff --git a/src/CalcViewModel/HistoryItemViewModel.cpp b/src/CalcViewModel/HistoryItemViewModel.cpp index d4fbde77..63d5e966 100644 --- a/src/CalcViewModel/HistoryItemViewModel.cpp +++ b/src/CalcViewModel/HistoryItemViewModel.cpp @@ -10,9 +10,15 @@ using namespace CalculatorApp::ViewModel; using namespace std; using namespace Platform; -HistoryItemViewModel::HistoryItemViewModel(String ^ expression, String ^ result, _In_ const shared_ptr>>& spTokens, - _In_ const shared_ptr>>& spCommands) - : m_expression(expression), m_result(result), m_spTokens(spTokens), m_spCommands(spCommands) +HistoryItemViewModel::HistoryItemViewModel( + String ^ expression, + String ^ result, + _In_ const shared_ptr>>& spTokens, + _In_ const shared_ptr>>& spCommands) + : m_expression(expression) + , m_result(result) + , m_spTokens(spTokens) + , m_spCommands(spCommands) { // updating accessibility names for expression and result m_accExpression = HistoryItemViewModel::GetAccessibleExpressionFromTokens(spTokens, m_expression); @@ -20,8 +26,9 @@ HistoryItemViewModel::HistoryItemViewModel(String ^ expression, String ^ result, } String - ^ HistoryItemViewModel::GetAccessibleExpressionFromTokens(_In_ shared_ptr>> const& spTokens, - _In_ String ^ fallbackExpression) + ^ HistoryItemViewModel::GetAccessibleExpressionFromTokens( + _In_ shared_ptr>> const& spTokens, + _In_ String ^ fallbackExpression) { // updating accessibility names for expression and result wstringstream accExpression{}; diff --git a/src/CalcViewModel/HistoryItemViewModel.h b/src/CalcViewModel/HistoryItemViewModel.h index 3d7e5888..fae51e69 100644 --- a/src/CalcViewModel/HistoryItemViewModel.h +++ b/src/CalcViewModel/HistoryItemViewModel.h @@ -14,9 +14,11 @@ namespace CalculatorApp { internal : - HistoryItemViewModel(Platform::String ^ expression, Platform::String ^ result, - _In_ std::shared_ptr>> const& spTokens, - _In_ std::shared_ptr>> const& spCommands); + HistoryItemViewModel( + Platform::String ^ expression, + Platform::String ^ result, + _In_ std::shared_ptr>> const& spTokens, + _In_ std::shared_ptr>> const& spCommands); std::shared_ptr>> const& GetTokens() { @@ -59,8 +61,9 @@ namespace CalculatorApp ^ GetStringRepresentation() { return m_accExpression + " " + m_accResult; } private : static Platform::String - ^ GetAccessibleExpressionFromTokens(_In_ std::shared_ptr>> const& spTokens, - _In_ Platform::String ^ fallbackExpression); + ^ GetAccessibleExpressionFromTokens( + _In_ std::shared_ptr>> const& spTokens, + _In_ Platform::String ^ fallbackExpression); private: Platform::String ^ m_expression; diff --git a/src/CalcViewModel/HistoryViewModel.cpp b/src/CalcViewModel/HistoryViewModel.cpp index 6e0b9814..70374252 100644 --- a/src/CalcViewModel/HistoryViewModel.cpp +++ b/src/CalcViewModel/HistoryViewModel.cpp @@ -27,7 +27,8 @@ namespace CalculatorApp::ViewModel::HistoryResourceKeys } HistoryViewModel::HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager) - : m_calculatorManager(calculatorManager), m_localizedHistoryCleared(nullptr) + : m_calculatorManager(calculatorManager) + , m_localizedHistoryCleared(nullptr) { AreHistoryShortcutsEnabled = true; @@ -69,8 +70,11 @@ void HistoryViewModel::ReloadHistory(_In_ ViewMode currentMode) localizer.LocalizeDisplayValue(&expression); localizer.LocalizeDisplayValue(&result); - auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()), ref new Platform::String(result.c_str()), - (*ritr)->historyItemVector.spTokens, (*ritr)->historyItemVector.spCommands); + auto item = ref new HistoryItemViewModel( + ref new Platform::String(expression.c_str()), + ref new Platform::String(result.c_str()), + (*ritr)->historyItemVector.spTokens, + (*ritr)->historyItemVector.spCommands); historyListVM->Append(item); } } @@ -87,8 +91,11 @@ void HistoryViewModel::OnHistoryItemAdded(_In_ unsigned int addedItemIndex) wstring result = newItem->historyItemVector.result; localizer.LocalizeDisplayValue(&expression); localizer.LocalizeDisplayValue(&result); - auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()), ref new Platform::String(result.c_str()), - newItem->historyItemVector.spTokens, newItem->historyItemVector.spCommands); + auto item = ref new HistoryItemViewModel( + ref new Platform::String(expression.c_str()), + ref new Platform::String(result.c_str()), + newItem->historyItemVector.spTokens, + newItem->historyItemVector.spCommands); // check if we have not hit the max items if (Items->Size >= m_calculatorManager->MaxHistorySize()) @@ -310,8 +317,8 @@ Platform::String ^ HistoryViewModel::SerializeHistoryItem(_In_ std::shared_ptrValues->HasKey(historyItemKey)) @@ -352,8 +359,9 @@ CalculationManager::HISTORYITEM HistoryViewModel::DeserializeHistoryItem(_In_ Pl bool HistoryViewModel::IsValid(_In_ CalculationManager::HISTORYITEM item) { - return (!item.historyItemVector.expression.empty() && !item.historyItemVector.result.empty() && (bool)item.historyItemVector.spCommands - && (bool)item.historyItemVector.spTokens); + return ( + !item.historyItemVector.expression.empty() && !item.historyItemVector.result.empty() && (bool)item.historyItemVector.spCommands + && (bool)item.historyItemVector.spTokens); } void HistoryViewModel::UpdateItemSize() diff --git a/src/CalcViewModel/HistoryViewModel.h b/src/CalcViewModel/HistoryViewModel.h index 07336c42..4ed61d92 100644 --- a/src/CalcViewModel/HistoryViewModel.h +++ b/src/CalcViewModel/HistoryViewModel.h @@ -60,8 +60,8 @@ namespace CalculatorApp Platform::String ^ m_localizedHistoryCleared; 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); Platform::String ^ GetHistoryContainerKey(_In_ CalculationManager::CALCULATOR_MODE cMode); void ClearHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode); diff --git a/src/CalcViewModel/MemoryItemViewModel.h b/src/CalcViewModel/MemoryItemViewModel.h index 1a67f3db..9a85a2bc 100644 --- a/src/CalcViewModel/MemoryItemViewModel.h +++ b/src/CalcViewModel/MemoryItemViewModel.h @@ -18,7 +18,9 @@ namespace CalculatorApp Windows::UI::Xaml::Data::ICustomPropertyProvider { public: - MemoryItemViewModel(StandardCalculatorViewModel ^ calcVM) : m_Position(-1), m_calcVM(calcVM) + MemoryItemViewModel(StandardCalculatorViewModel ^ calcVM) + : m_Position(-1) + , m_calcVM(calcVM) { } OBSERVABLE_OBJECT(); diff --git a/src/CalcViewModel/StandardCalculatorViewModel.cpp b/src/CalcViewModel/StandardCalculatorViewModel.cpp index be656b2e..dd0283da 100644 --- a/src/CalcViewModel/StandardCalculatorViewModel.cpp +++ b/src/CalcViewModel/StandardCalculatorViewModel.cpp @@ -235,9 +235,10 @@ void StandardCalculatorViewModel::SetOpenParenthesisCountNarratorAnnouncement() wstring localizedParenthesisCount = to_wstring(m_OpenParenthesisCount).c_str(); LocalizationSettings::GetInstance().LocalizeDisplayValue(&localizedParenthesisCount); - String ^ announcement = - LocalizationStringUtil::GetLocalizedNarratorAnnouncement(CalculatorResourceKeys::OpenParenthesisCountAutomationFormat, - m_localizedOpenParenthesisCountChangedAutomationFormat, localizedParenthesisCount.c_str()); + String ^ announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement( + CalculatorResourceKeys::OpenParenthesisCountAutomationFormat, + m_localizedOpenParenthesisCountChangedAutomationFormat, + localizedParenthesisCount.c_str()); Announcement = CalculatorAnnouncement::GetOpenParenthesisCountChangedAnnouncement(announcement); } @@ -283,8 +284,9 @@ void StandardCalculatorViewModel::DisableButtons(CommandType selectedExpressionC } } -void StandardCalculatorViewModel::SetExpressionDisplay(_Inout_ shared_ptr>> const& tokens, - _Inout_ shared_ptr>> const& commands) +void StandardCalculatorViewModel::SetExpressionDisplay( + _Inout_ shared_ptr>> const& tokens, + _Inout_ shared_ptr>> const& commands) { m_tokens = tokens; m_commands = commands; @@ -298,8 +300,9 @@ void StandardCalculatorViewModel::SetExpressionDisplay(_Inout_ shared_ptr>> const& tokens, - _Inout_ shared_ptr>> const& commands) +void StandardCalculatorViewModel::SetHistoryExpressionDisplay( + _Inout_ shared_ptr>> const& tokens, + _Inout_ shared_ptr>> const& commands) { m_tokens = make_shared>>(*tokens); m_commands = make_shared>>(*commands); @@ -878,14 +881,25 @@ void StandardCalculatorViewModel::OnPaste(String ^ pastedString, ViewMode mode) } } - // Handle exponent and exponent sign (...e+... or ...e-...) + // Handle exponent and exponent sign (...e+... or ...e-... or ...e...) if (mappedNumOp == NumbersAndOperatorsEnum::Exp) { - ++it; - if (!(MapCharacterToButtonId(*it, canSendNegate) == NumbersAndOperatorsEnum::Add)) + //Check the following item + switch (MapCharacterToButtonId(*(it + 1), canSendNegate)) + { + case NumbersAndOperatorsEnum::Subtract: { Command cmdNegate = ConvertToOperatorsEnum(NumbersAndOperatorsEnum::Negate); m_standardCalculatorManager.SendCommand(cmdNegate); + ++it; + } + break; + case NumbersAndOperatorsEnum::Add: + { + //Nothing to do, skip to the next item + ++it; + } + break; } } @@ -1035,8 +1049,8 @@ void StandardCalculatorViewModel::OnMemoryButtonPressed() int windowId = Utils::GetWindowId(); TraceLogger::GetInstance().InsertIntoMemoryMap(windowId, IsStandard, IsScientific, IsProgrammer); - String ^ announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement(CalculatorResourceKeys::MemorySave, m_localizedMemorySavedAutomationFormat, - m_DisplayValue->Data()); + String ^ announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement( + CalculatorResourceKeys::MemorySave, m_localizedMemorySavedAutomationFormat, m_DisplayValue->Data()); Announcement = CalculatorAnnouncement::GetMemoryItemAddedAnnouncement(announcement); } @@ -1149,110 +1163,6 @@ void StandardCalculatorViewModel::OnMemoryClear(_In_ Object ^ memoryItemPosition } } -Array ^ StandardCalculatorViewModel::Serialize() -{ - DataWriter ^ writer = ref new DataWriter(); - writer->WriteUInt32(static_cast(m_CurrentAngleType)); - writer->WriteBoolean(IsFToEChecked); - writer->WriteBoolean(IsCurrentViewPinned); - writer->WriteUInt32(static_cast(m_standardCalculatorManager.SerializeSavedDegreeMode())); - - // Serialize Memory - vector serializedMemory; - serializedMemory = m_standardCalculatorManager.GetSerializedMemory(); - size_t lengthOfSerializedMemory = serializedMemory.size(); - writer->WriteUInt32(static_cast(lengthOfSerializedMemory)); - for (auto data : serializedMemory) - { - writer->WriteInt32(data); - } - - // Serialize Primary Display - vector serializedPrimaryDisplay = m_standardCalculatorManager.GetSerializedPrimaryDisplay(); - writer->WriteUInt32(static_cast(serializedPrimaryDisplay.size())); - for (auto data : serializedPrimaryDisplay) - { - writer->WriteInt32(data); - } - - // For ProgrammerMode - writer->WriteUInt32(static_cast(CurrentRadixType)); - - // Serialize commands of calculator manager - vector serializedCommand = m_standardCalculatorManager.SerializeCommands(); - writer->WriteUInt32(static_cast(serializedCommand.size())); - writer->WriteBytes(ref new Array(serializedCommand.data(), static_cast(serializedCommand.size()))); - - if (IsInError) - { - Utils::SerializeCommandsAndTokens(m_tokens, m_commands, writer); - } - - // Convert viewmodel data in writer to bytes - IBuffer ^ buffer = writer->DetachBuffer(); - DataReader ^ reader = DataReader::FromBuffer(buffer); - Platform::Array ^ viewModelDataAsBytes = ref new Array(buffer->Length); - reader->ReadBytes(viewModelDataAsBytes); - - // Return byte array - return viewModelDataAsBytes; -} - -void StandardCalculatorViewModel::Deserialize(Array ^ state) -{ - // Read byte array into a buffer - DataWriter ^ writer = ref new DataWriter(); - writer->WriteBytes(state); - IBuffer ^ buffer = writer->DetachBuffer(); - - // Read view model data - if (buffer->Length != 0) - { - DataReader ^ reader = DataReader::FromBuffer(buffer); - m_CurrentAngleType = ConvertIntegerToNumbersAndOperatorsEnum(reader->ReadUInt32()); - - IsFToEChecked = reader->ReadBoolean(); - IsCurrentViewPinned = reader->ReadBoolean(); - Command serializedDegreeMode = static_cast(reader->ReadUInt32()); - - m_standardCalculatorManager.SendCommand(serializedDegreeMode); - - // Deserialize Memory - UINT32 memoryDataLength = reader->ReadUInt32(); - vector serializedMemory; - for (unsigned int i = 0; i < memoryDataLength; i++) - { - serializedMemory.push_back(reader->ReadInt32()); - } - m_standardCalculatorManager.DeSerializeMemory(serializedMemory); - - // Serialize Primary Display - UINT32 serializedPrimaryDisplayLength = reader->ReadUInt32(); - vector serializedPrimaryDisplay; - for (unsigned int i = 0; i < serializedPrimaryDisplayLength; i++) - { - serializedPrimaryDisplay.push_back(reader->ReadInt32()); - } - m_standardCalculatorManager.DeSerializePrimaryDisplay(serializedPrimaryDisplay); - - CurrentRadixType = reader->ReadUInt32(); - // Read command data and Deserialize - UINT32 modeldatalength = reader->ReadUInt32(); - Array ^ modelDataAsBytes = ref new Array(modeldatalength); - reader->ReadBytes(modelDataAsBytes); - m_standardCalculatorManager.DeSerializeCommands(vector(modelDataAsBytes->begin(), modelDataAsBytes->end())); - - // After recalculation. If there is an error then - // IsInError should be set synchronously. - if (IsInError) - { - shared_ptr>> commandVector = Utils::DeserializeCommands(reader); - shared_ptr>> tokenVector = Utils::DeserializeTokens(reader); - SetExpressionDisplay(tokenVector, commandVector); - } - } -} - void StandardCalculatorViewModel::OnPropertyChanged(String ^ propertyname) { if (propertyname == IsScientificPropertyName) @@ -1313,13 +1223,18 @@ void StandardCalculatorViewModel::SetCalculatorType(ViewMode targetState) } } -Platform::String ^ StandardCalculatorViewModel::GetRawDisplayValue() +String^ StandardCalculatorViewModel::GetRawDisplayValue() { - wstring rawValue; - - LocalizationSettings::GetInstance().RemoveGroupSeparators(DisplayValue->Data(), DisplayValue->Length(), &rawValue); - - return ref new Platform::String(rawValue.c_str()); + if (IsInError) + { + return DisplayValue; + } + else + { + wstring rawValue; + LocalizationSettings::GetInstance().RemoveGroupSeparators(DisplayValue->Data(), DisplayValue->Length(), &rawValue); + return ref new String(rawValue.c_str()); + } } // Given a format string, returns a string with the input display value inserted. @@ -1957,9 +1872,11 @@ NarratorAnnouncement ^ StandardCalculatorViewModel::GetDisplayUpdatedNarratorAnn } else { - announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement(CalculatorResourceKeys::ButtonPressFeedbackFormat, - m_localizedButtonPressFeedbackAutomationFormat, - m_CalculationResultAutomationName->Data(), m_feedbackForButtonPress->Data()); + announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement( + CalculatorResourceKeys::ButtonPressFeedbackFormat, + m_localizedButtonPressFeedbackAutomationFormat, + m_CalculationResultAutomationName->Data(), + m_feedbackForButtonPress->Data()); } // Make sure we don't accidentally repeat an announcement. diff --git a/src/CalcViewModel/StandardCalculatorViewModel.h b/src/CalcViewModel/StandardCalculatorViewModel.h index fc433752..59dbbcb1 100644 --- a/src/CalcViewModel/StandardCalculatorViewModel.h +++ b/src/CalcViewModel/StandardCalculatorViewModel.h @@ -334,10 +334,12 @@ namespace CalculatorApp void SetPrimaryDisplay(_In_ std::wstring const& displayString, _In_ bool isError); void DisplayPasteError(); void SetTokens(_Inout_ std::shared_ptr>> const& tokens); - void SetExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands); - void SetHistoryExpressionDisplay(_Inout_ std::shared_ptr>> const& tokens, - _Inout_ std::shared_ptr>> const& commands); + void SetExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands); + void SetHistoryExpressionDisplay( + _Inout_ std::shared_ptr>> const& tokens, + _Inout_ std::shared_ptr>> const& commands); void SetParenthesisCount(_In_ unsigned int parenthesisCount); void SetOpenParenthesisCountNarratorAnnouncement(); void OnNoRightParenAdded(); @@ -346,8 +348,6 @@ namespace CalculatorApp void OnBinaryOperatorReceived(); void OnMemoryItemChanged(unsigned int indexOfMemory); - Platform::Array ^ Serialize(); - void Deserialize(Platform::Array ^ state); Platform::String ^ GetLocalizedStringFormat(Platform::String ^ format, Platform::String ^ displayValue); void OnPropertyChanged(Platform::String ^ propertyname); diff --git a/src/CalcViewModel/UnitConverterViewModel.cpp b/src/CalcViewModel/UnitConverterViewModel.cpp index f705d6e9..72d31464 100644 --- a/src/CalcViewModel/UnitConverterViewModel.cpp +++ b/src/CalcViewModel/UnitConverterViewModel.cpp @@ -122,14 +122,15 @@ UnitConverterViewModel::UnitConverterViewModel(const shared_ptrSetViewModelCallback(make_shared(this)); m_model->SetViewModelCurrencyCallback(make_shared(this)); - m_decimalFormatter = LocalizationService::GetRegionalSettingsAwareDecimalFormatter(); + m_decimalFormatter = localizationService->GetRegionalSettingsAwareDecimalFormatter(); m_decimalFormatter->FractionDigits = 0; m_decimalFormatter->IsGrouped = true; m_decimalSeparator = LocalizationSettings::GetInstance().GetDecimalSeparator(); - m_currencyFormatter = LocalizationService::GetRegionalSettingsAwareCurrencyFormatter(); + m_currencyFormatter = localizationService->GetRegionalSettingsAwareCurrencyFormatter(); m_currencyFormatter->IsGrouped = true; m_currencyFormatter->Mode = CurrencyFormatterMode::UseCurrencyCode; m_currencyFormatter->ApplyRoundingForCurrency(RoundingAlgorithm::RoundHalfDown); @@ -463,7 +464,8 @@ void UnitConverterViewModel::UpdateSupplementaryResults(const std::vector(m_value1cp)) << delimiter; - out << m_Value1Active << delimiter << m_Value2Active << delimiter; - out << m_Value1->Data() << delimiter << m_Value2->Data() << delimiter; - out << m_valueFromUnlocalized << delimiter << m_valueToUnlocalized << delimiter << L"[###]"; - wstring unitConverterSerializedData = m_model->Serialize(); - - if (!unitConverterSerializedData.empty()) - { - out << m_model->Serialize() << L"[###]"; - String ^ serializedData = ref new String(wstring(out.str()).c_str()); - return serializedData; - } - - return nullptr; -} - -void UnitConverterViewModel::Deserialize(Platform::String ^ state) -{ - wstring serializedData = wstring(state->Data()); - vector tokens = UCM::UnitConverter::StringToVector(serializedData, L"[###]"); - assert(tokens.size() >= 2); - vector viewModelData = UCM::UnitConverter::StringToVector(tokens[0], L"[;;;]"); - assert(viewModelData.size() == EXPECTEDVIEWMODELDATATOKENS); - m_resettingTimer = (viewModelData[0].compare(L"1") == 0); - m_value1cp = (ConversionParameter)_wtoi(viewModelData[1].c_str()); - m_Value1Active = (viewModelData[2].compare(L"1") == 0); - m_Value2Active = (viewModelData[3].compare(L"1") == 0); - m_Value1 = ref new String(viewModelData[4].c_str()); - m_Value2 = ref new String(viewModelData[5].c_str()); - m_valueFromUnlocalized = viewModelData[6]; - m_valueToUnlocalized = viewModelData[7]; - wstringstream modelData(wstringstream::out); - for (unsigned int i = 1; i < tokens.size(); i++) - { - modelData << tokens[i] << L"[###]"; - } - m_model->DeSerialize(modelData.str()); - InitializeView(); - RaisePropertyChanged(nullptr); // Update since all props have been updated. -} - // Saving User Preferences of Category and Associated-Units across Sessions. void UnitConverterViewModel::SaveUserPreferences() { @@ -1010,12 +966,16 @@ String ^ UnitConverterViewModel::GetLocalizedAutomationName(_In_ String ^ displa } String - ^ UnitConverterViewModel::GetLocalizedConversionResultStringFormat(_In_ String ^ fromValue, _In_ String ^ fromUnit, _In_ String ^ toValue, - _In_ String ^ toUnit) + ^ UnitConverterViewModel::GetLocalizedConversionResultStringFormat( + _In_ String ^ fromValue, + _In_ String ^ fromUnit, + _In_ String ^ toValue, + _In_ String ^ toUnit) { - String ^ localizedString = ref new String(LocalizationStringUtil::GetLocalizedString(m_localizedConversionResultFormat->Data(), fromValue->Data(), - fromUnit->Data(), toValue->Data(), toUnit->Data()) - .c_str()); + String ^ localizedString = + ref new String(LocalizationStringUtil::GetLocalizedString( + m_localizedConversionResultFormat->Data(), fromValue->Data(), fromUnit->Data(), toValue->Data(), toUnit->Data()) + .c_str()); return localizedString; } diff --git a/src/CalcViewModel/UnitConverterViewModel.h b/src/CalcViewModel/UnitConverterViewModel.h index 5fea4721..b0cc0241 100644 --- a/src/CalcViewModel/UnitConverterViewModel.h +++ b/src/CalcViewModel/UnitConverterViewModel.h @@ -17,7 +17,8 @@ namespace CalculatorApp { [Windows::UI::Xaml::Data::Bindable] public ref class Category sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged { - internal : Category(const UnitConversionManager::Category& category) : m_original(category) + internal : Category(const UnitConversionManager::Category& category) + : m_original(category) { } @@ -46,7 +47,8 @@ namespace CalculatorApp [Windows::UI::Xaml::Data::Bindable] public ref class Unit sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged { - internal : Unit(const UnitConversionManager::Unit& unit) : m_original(unit) + internal : Unit(const UnitConversionManager::Unit& unit) + : m_original(unit) { } @@ -80,7 +82,9 @@ namespace CalculatorApp [Windows::UI::Xaml::Data::Bindable] public ref class SupplementaryResult sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged { - internal : SupplementaryResult(Platform::String ^ value, Unit ^ unit) : m_Value(value), m_Unit(unit) + internal : SupplementaryResult(Platform::String ^ value, Unit ^ unit) + : m_Value(value) + , m_Unit(unit) { } @@ -110,7 +114,8 @@ namespace CalculatorApp TActivatable m_activatable; public: - Activatable(TActivatable activatable) : m_activatable(activatable) + Activatable(TActivatable activatable) + : m_activatable(activatable) { } @@ -207,13 +212,13 @@ namespace CalculatorApp Platform::String ^ GetLocalizedAutomationName(_In_ Platform::String ^ displayvalue, _In_ Platform::String ^ unitname, _In_ Platform::String ^ format); Platform::String - ^ GetLocalizedConversionResultStringFormat(_In_ Platform::String ^ fromValue, _In_ Platform::String ^ fromUnit, _In_ Platform::String ^ toValue, - _In_ Platform::String ^ toUnit); + ^ GetLocalizedConversionResultStringFormat( + _In_ Platform::String ^ fromValue, + _In_ Platform::String ^ fromUnit, + _In_ Platform::String ^ toValue, + _In_ Platform::String ^ toUnit); void UpdateValue1AutomationName(); void UpdateValue2AutomationName(); - Platform::String ^ Serialize(); - void Deserialize(Platform::String ^ state); - void ResetCategoriesAndRatio(); // Saving And Restoring User Preferences of Category and Associated-Units across Sessions. void SaveUserPreferences(); @@ -330,7 +335,8 @@ namespace CalculatorApp class UnitConverterVMCallback : public UnitConversionManager::IUnitConverterVMCallback { public: - UnitConverterVMCallback(UnitConverterViewModel ^ viewModel) : m_viewModel(viewModel) + UnitConverterVMCallback(UnitConverterViewModel ^ viewModel) + : m_viewModel(viewModel) { } @@ -356,7 +362,8 @@ namespace CalculatorApp class ViewModelCurrencyCallback : public UnitConversionManager::IViewModelCurrencyCallback { public: - ViewModelCurrencyCallback(UnitConverterViewModel ^ viewModel) : m_viewModel(viewModel) + ViewModelCurrencyCallback(UnitConverterViewModel ^ viewModel) + : m_viewModel(viewModel) { } diff --git a/src/Calculator.sln b/src/Calculator.sln index 47084340..11fe757e 100644 --- a/src/Calculator.sln +++ b/src/Calculator.sln @@ -9,8 +9,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CalcManager", "CalcManager\ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3A5DF651-B8A1-45CA-9135-964A6FC7F5D1}" ProjectSection(SolutionItems) = preProject - .clang-format = .clang-format - clang-format-all.sh = clang-format-all.sh + ..\.clang-format = ..\.clang-format nuget.config = nuget.config EndProjectSection EndProject diff --git a/src/Calculator/App.xaml b/src/Calculator/App.xaml index 918034c0..910a5856 100644 --- a/src/Calculator/App.xaml +++ b/src/Calculator/App.xaml @@ -353,8 +353,7 @@ -