Do some codebase modernization

This commit is contained in:
Rose 2022-11-04 11:57:36 -04:00
commit 755e251125
23 changed files with 83 additions and 138 deletions

View file

@ -1,6 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
#include <utility>
#include "Header Files/CalcEngine.h" #include "Header Files/CalcEngine.h"
#include "Command.h" #include "Command.h"
#include "ExpressionCommand.h" #include "ExpressionCommand.h"
@ -45,7 +47,7 @@ void CHistoryCollector::ReinitHistory()
// Constructor // Constructor
// Can throw Out of memory error // Can throw Out of memory error
CHistoryCollector::CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol) CHistoryCollector::CHistoryCollector(ICalcDisplay* pCalcDisplay, std::shared_ptr<IHistoryDisplay> pHistoryDisplay, wchar_t decimalSymbol)
: m_pHistoryDisplay(pHistoryDisplay) : m_pHistoryDisplay(std::move(pHistoryDisplay))
, m_pCalcDisplay(pCalcDisplay) , m_pCalcDisplay(pCalcDisplay)
, m_iCurLineHistStart(-1) , m_iCurLineHistStart(-1)
, m_decimalSymbol(decimalSymbol) , m_decimalSymbol(decimalSymbol)

View file

@ -2,6 +2,7 @@
// Licensed under the MIT License. // Licensed under the MIT License.
#include <cassert> #include <cassert>
#include <utility>
#include "Header Files/CalcEngine.h" #include "Header Files/CalcEngine.h"
#include "CalculatorResource.h" #include "CalculatorResource.h"
@ -96,7 +97,7 @@ CCalcEngine::CCalcEngine(
, m_nLastCom(0) , m_nLastCom(0)
, m_angletype(AngleType::Degrees) , m_angletype(AngleType::Degrees)
, m_numwidth(NUM_WIDTH::QWORD_WIDTH) , m_numwidth(NUM_WIDTH::QWORD_WIDTH)
, m_HistoryCollector(pCalcDisplay, pHistoryDisplay, DEFAULT_DEC_SEPARATOR) , m_HistoryCollector(pCalcDisplay, std::move(pHistoryDisplay), DEFAULT_DEC_SEPARATOR)
, m_groupSeparator(DEFAULT_GRP_SEPARATOR) , m_groupSeparator(DEFAULT_GRP_SEPARATOR)
{ {
InitChopNumbers(); InitChopNumbers();

View file

@ -1124,5 +1124,5 @@ double CCalcEngine::GenerateRandomNumber()
m_randomGeneratorEngine = std::make_unique<std::mt19937>(rd()); m_randomGeneratorEngine = std::make_unique<std::mt19937>(rd());
m_distr = std::make_unique<std::uniform_real_distribution<>>(0, 1); m_distr = std::make_unique<std::uniform_real_distribution<>>(0, 1);
} }
return (*m_distr.get())(*m_randomGeneratorEngine.get()); return (*m_distr)(*m_randomGeneratorEngine);
} }

View file

@ -41,14 +41,14 @@ typedef struct
Rational value; Rational value;
int32_t precision; int32_t precision;
uint32_t radix; uint32_t radix;
int nFE; NumberFormat nFE;
NUM_WIDTH numwidth; NUM_WIDTH numwidth;
bool fIntMath; bool fIntMath;
bool bRecord; bool bRecord;
bool bUseSep; bool bUseSep;
} LASTDISP; } LASTDISP;
static LASTDISP gldPrevious = { 0, -1, 0, -1, (NUM_WIDTH)-1, false, false, false }; static LASTDISP gldPrevious = { 0, -1, 0, (NumberFormat)-1, (NUM_WIDTH)-1, false, false, false };
// Truncates if too big, makes it a non negative - the number in rat. Doesn't do anything if not in INT mode // Truncates if too big, makes it a non negative - the number in rat. Doesn't do anything if not in INT mode
CalcEngine::Rational CCalcEngine::TruncateNumForIntMath(CalcEngine::Rational const& rat) CalcEngine::Rational CCalcEngine::TruncateNumForIntMath(CalcEngine::Rational const& rat)
@ -84,12 +84,12 @@ void CCalcEngine::DisplayNum(void)
// something important has changed since the last time DisplayNum was // something important has changed since the last time DisplayNum was
// called. // called.
// //
if (m_bRecord || gldPrevious.value != m_currentVal || gldPrevious.precision != m_precision || gldPrevious.radix != m_radix || gldPrevious.nFE != (int)m_nFE if (m_bRecord || gldPrevious.value != m_currentVal || gldPrevious.precision != m_precision || gldPrevious.radix != m_radix || gldPrevious.nFE != m_nFE
|| !gldPrevious.bUseSep || gldPrevious.numwidth != m_numwidth || gldPrevious.fIntMath != m_fIntegerMode || gldPrevious.bRecord != m_bRecord) || !gldPrevious.bUseSep || gldPrevious.numwidth != m_numwidth || gldPrevious.fIntMath != m_fIntegerMode || gldPrevious.bRecord != m_bRecord)
{ {
gldPrevious.precision = m_precision; gldPrevious.precision = m_precision;
gldPrevious.radix = m_radix; gldPrevious.radix = m_radix;
gldPrevious.nFE = (int)m_nFE; gldPrevious.nFE = m_nFE;
gldPrevious.numwidth = m_numwidth; gldPrevious.numwidth = m_numwidth;
gldPrevious.fIntMath = m_fIntegerMode; gldPrevious.fIntMath = m_fIntegerMode;
@ -156,7 +156,7 @@ int CCalcEngine::IsNumberInvalid(const wstring& numberString, int iMaxExp, int i
auto intEnd = exp.end(); auto intEnd = exp.end();
while (intItr != intEnd && *intItr == L'0') while (intItr != intEnd && *intItr == L'0')
{ {
intItr++; ++intItr;
} }
auto iMantissa = distance(intItr, intEnd) + matches.length(2); auto iMantissa = distance(intItr, intEnd) + matches.length(2);

View file

@ -44,7 +44,7 @@ namespace CalculationManager
class CalculatorManager final : public ICalcDisplay class CalculatorManager final : public ICalcDisplay
{ {
private: private:
static const unsigned int m_maximumMemorySize = 100; static constexpr unsigned int m_maximumMemorySize = 100;
ICalcDisplay* const m_displayCallback; ICalcDisplay* const m_displayCallback;
CCalcEngine* m_currentCalculatorEngine; CCalcEngine* m_currentCalculatorEngine;
std::unique_ptr<CCalcEngine> m_scientificCalculatorEngine; std::unique_ptr<CCalcEngine> m_scientificCalculatorEngine;

View file

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

View file

@ -212,7 +212,7 @@ void COpndCommand::ClearAllAndAppendCommand(CalculationManager::Command command)
const wstring& COpndCommand::GetToken(wchar_t decimalSymbol) const wstring& COpndCommand::GetToken(wchar_t decimalSymbol)
{ {
static const wchar_t chZero = L'0'; static constexpr wchar_t chZero = L'0';
const size_t nCommands = m_commands->size(); const size_t nCommands = m_commands->size();
m_token.clear(); m_token.clear();

View file

@ -154,14 +154,14 @@ private:
std::unique_ptr<std::mt19937> m_randomGeneratorEngine; std::unique_ptr<std::mt19937> m_randomGeneratorEngine;
std::unique_ptr<std::uniform_real_distribution<>> m_distr; std::unique_ptr<std::uniform_real_distribution<>> m_distr;
uint64_t m_carryBit; uint64_t m_carryBit{};
CHistoryCollector m_HistoryCollector; // Accumulator of each line of history as various commands are processed CHistoryCollector m_HistoryCollector; // Accumulator of each line of history as various commands are processed
std::array<CalcEngine::Rational, NUM_WIDTH_LENGTH> m_chopNumbers; // word size enforcement std::array<CalcEngine::Rational, NUM_WIDTH_LENGTH> m_chopNumbers; // word size enforcement
std::array<std::wstring, NUM_WIDTH_LENGTH> m_maxDecimalValueStrings; // maximum values represented by a given word width based off m_chopNumbers std::array<std::wstring, NUM_WIDTH_LENGTH> m_maxDecimalValueStrings; // maximum values represented by a given word width based off m_chopNumbers
static std::unordered_map<std::wstring_view, std::wstring> s_engineStrings; // the string table shared across all instances static std::unordered_map<std::wstring_view, std::wstring> s_engineStrings; // the string table shared across all instances
wchar_t m_decimalSeparator; wchar_t m_decimalSeparator{};
wchar_t m_groupSeparator; wchar_t m_groupSeparator;
private: private:

View file

@ -44,12 +44,12 @@ private:
int m_iCurLineHistStart; // index of the beginning of the current equation int m_iCurLineHistStart; // index of the beginning of the current equation
// a sort of state, set to the index before 2 after 2 in the expression 2 + 3 say. Useful for auto correct portion of history and for // a sort of state, set to the index before 2 after 2 in the expression 2 + 3 say. Useful for auto correct portion of history and for
// attaching the unary op around the last operand // attaching the unary op around the last operand
int m_lastOpStartIndex; // index of the beginning of the last operand added to the history int m_lastOpStartIndex{}; // index of the beginning of the last operand added to the history
int m_lastBinOpStartIndex; // index of the beginning of the last binary operator added to the history int m_lastBinOpStartIndex{}; // index of the beginning of the last binary operator added to the history
std::array<int, MAXPRECDEPTH> std::array<int, MAXPRECDEPTH>
m_operandIndices; // Stack of index of opnd's beginning for each '('. A parallel array to m_hnoParNum, but abstracted independently of that m_operandIndices{}; // Stack of index of opnd's beginning for each '('. A parallel array to m_hnoParNum, but abstracted independently of that
int m_curOperandIndex; // Stack index for the above stack int m_curOperandIndex{}; // Stack index for the above stack
bool m_bLastOpndBrace; // iff the last opnd in history is already braced so we can avoid putting another one for unary operator bool m_bLastOpndBrace = false; // iff the last opnd in history is already braced so we can avoid putting another one for unary operator
wchar_t m_decimalSymbol; wchar_t m_decimalSymbol;
std::shared_ptr<std::vector<std::pair<std::wstring, int>>> m_spTokens; std::shared_ptr<std::vector<std::pair<std::wstring, int>>> m_spTokens;
std::shared_ptr<std::vector<std::shared_ptr<IExpressionCommand>>> m_spCommands; std::shared_ptr<std::vector<std::shared_ptr<IExpressionCommand>>> m_spCommands;

View file

@ -9,7 +9,7 @@
class IHistoryDisplay class IHistoryDisplay
{ {
public: public:
virtual ~IHistoryDisplay(){}; virtual ~IHistoryDisplay() = default;
virtual unsigned int AddToHistory( virtual unsigned int AddToHistory(
_In_ std::shared_ptr<std::vector<std::pair<std::wstring, int>>> const& tokens, _In_ std::shared_ptr<std::vector<std::pair<std::wstring, int>>> const& tokens,
_In_ std::shared_ptr<std::vector<std::shared_ptr<IExpressionCommand>>> const& commands, _In_ std::shared_ptr<std::vector<std::shared_ptr<IExpressionCommand>>> const& commands,

View file

@ -411,7 +411,7 @@ void UnitConverter::SendCommand(Command command)
{ {
clearFront = (m_currentDisplay == L"0"); clearFront = (m_currentDisplay == L"0");
clearBack = clearBack =
((m_currentHasDecimal && m_currentDisplay.size() - 1 >= MAXIMUMDIGITSALLOWED) ((m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED + 1)
|| (!m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED)); || (!m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED));
} }
@ -619,15 +619,15 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
vector<SuggestedValueIntermediate> intermediateWhimsicalVector; vector<SuggestedValueIntermediate> intermediateWhimsicalVector;
unordered_map<Unit, ConversionData, UnitHash> ratios = m_ratioMap[m_fromType]; unordered_map<Unit, ConversionData, UnitHash> ratios = m_ratioMap[m_fromType];
// Calculate converted values for every other unit type in this category, along with their magnitude // Calculate converted values for every other unit type in this category, along with their magnitude
for (const auto& cur : ratios) for (const auto& [first, second] : ratios)
{ {
if (cur.first != m_fromType && cur.first != m_toType) if (first != m_fromType && first != m_toType)
{ {
double convertedValue = Convert(stod(m_currentDisplay), cur.second); double convertedValue = Convert(stod(m_currentDisplay), second);
SuggestedValueIntermediate newEntry; SuggestedValueIntermediate newEntry;
newEntry.magnitude = log10(convertedValue); newEntry.magnitude = log10(convertedValue);
newEntry.value = convertedValue; newEntry.value = convertedValue;
newEntry.type = cur.first; newEntry.type = first;
if (newEntry.type.isWhimsical) if (newEntry.type.isWhimsical)
intermediateWhimsicalVector.push_back(newEntry); intermediateWhimsicalVector.push_back(newEntry);
else else
@ -636,7 +636,7 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
} }
// Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value // Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value
sort(intermediateVector.begin(), intermediateVector.end(), [](SuggestedValueIntermediate first, SuggestedValueIntermediate second) { sort(intermediateVector.begin(), intermediateVector.end(), [](const SuggestedValueIntermediate& first, const SuggestedValueIntermediate& second) {
if (abs(first.magnitude) == abs(second.magnitude)) if (abs(first.magnitude) == abs(second.magnitude))
{ {
return first.magnitude > second.magnitude; return first.magnitude > second.magnitude;
@ -648,31 +648,32 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
}); });
// Now that the list is sorted, iterate over it and populate the return vector with properly rounded and formatted return strings // Now that the list is sorted, iterate over it and populate the return vector with properly rounded and formatted return strings
for (const auto& entry : intermediateVector) for (const auto& [magnitude, value, type] : intermediateVector)
{ {
wstring roundedString; wstring roundedString;
if (abs(entry.value) < 100) if (abs(value) < 100)
{ {
roundedString = RoundSignificantDigits(entry.value, 2U); roundedString = RoundSignificantDigits(value, 2U);
} }
else if (abs(entry.value) < 1000) else if (abs(value) < 1000)
{ {
roundedString = RoundSignificantDigits(entry.value, 1U); roundedString = RoundSignificantDigits(value, 1U);
} }
else else
{ {
roundedString = RoundSignificantDigits(entry.value, 0U); roundedString = RoundSignificantDigits(value, 0U);
} }
if (stod(roundedString) != 0.0 || m_currentCategory.supportsNegative) if (stod(roundedString) != 0.0 || m_currentCategory.supportsNegative)
{ {
TrimTrailingZeros(roundedString); TrimTrailingZeros(roundedString);
returnVector.emplace_back(roundedString, entry.type); returnVector.emplace_back(roundedString, type);
} }
} }
// The Whimsicals are determined differently // The Whimsicals are determined differently
// Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value // Sort the resulting list by absolute magnitude, breaking ties by choosing the positive value
sort(intermediateWhimsicalVector.begin(), intermediateWhimsicalVector.end(), [](SuggestedValueIntermediate first, SuggestedValueIntermediate second) { sort(intermediateWhimsicalVector.begin(), intermediateWhimsicalVector.end(), [](const SuggestedValueIntermediate& first, const SuggestedValueIntermediate&
second) {
if (abs(first.magnitude) == abs(second.magnitude)) if (abs(first.magnitude) == abs(second.magnitude))
{ {
return first.magnitude > second.magnitude; return first.magnitude > second.magnitude;

View file

@ -15,9 +15,8 @@ namespace UnitConversionManager
struct Unit struct Unit
{ {
Unit() Unit() = default;
{
}
Unit(int id, std::wstring_view name, std::wstring abbreviation, bool isConversionSource, bool isConversionTarget, bool isWhimsical) Unit(int id, std::wstring_view name, std::wstring abbreviation, bool isConversionSource, bool isConversionTarget, bool isWhimsical)
: id(id) : id(id)
, name(name) , name(name)
@ -53,13 +52,13 @@ namespace UnitConversionManager
accessibleName.append(1, L' ').append(nameValue2); accessibleName.append(1, L' ').append(nameValue2);
} }
int id; int id{};
std::wstring name; std::wstring name;
std::wstring accessibleName; std::wstring accessibleName;
std::wstring abbreviation; std::wstring abbreviation;
bool isConversionSource; bool isConversionSource{};
bool isConversionTarget; bool isConversionTarget{};
bool isWhimsical; bool isWhimsical{};
bool operator!=(const Unit& that) const bool operator!=(const Unit& that) const
{ {
@ -81,9 +80,7 @@ namespace UnitConversionManager
struct Category struct Category
{ {
Category() Category() = default;
{
}
Category(int id, std::wstring name, bool supportsNegative) Category(int id, std::wstring name, bool supportsNegative)
: id(id) : id(id)
@ -92,9 +89,9 @@ namespace UnitConversionManager
{ {
} }
int id; int id{};
std::wstring name; std::wstring name;
bool supportsNegative; bool supportsNegative{};
bool operator!=(const Category& that) const bool operator!=(const Category& that) const
{ {
@ -118,16 +115,15 @@ namespace UnitConversionManager
struct SuggestedValueIntermediate struct SuggestedValueIntermediate
{ {
double magnitude; double magnitude{};
double value; double value{};
Unit type; Unit type;
}; };
struct ConversionData struct ConversionData
{ {
ConversionData() ConversionData() = default;
{
}
ConversionData(double ratio, double offset, bool offsetFirst) ConversionData(double ratio, double offset, bool offsetFirst)
: ratio(ratio) : ratio(ratio)
, offset(offset) , offset(offset)
@ -166,7 +162,7 @@ namespace UnitConversionManager
class IViewModelCurrencyCallback class IViewModelCurrencyCallback
{ {
public: public:
virtual ~IViewModelCurrencyCallback(){}; virtual ~IViewModelCurrencyCallback() = default;
virtual void CurrencyDataLoadFinished(bool didLoad) = 0; virtual void CurrencyDataLoadFinished(bool didLoad) = 0;
virtual void CurrencySymbolsCallback(_In_ const std::wstring& fromSymbol, _In_ const std::wstring& toSymbol) = 0; virtual void CurrencySymbolsCallback(_In_ const std::wstring& fromSymbol, _In_ const std::wstring& toSymbol) = 0;
virtual void CurrencyRatiosCallback(_In_ const std::wstring& ratioEquality, _In_ const std::wstring& accRatioEquality) = 0; virtual void CurrencyRatiosCallback(_In_ const std::wstring& ratioEquality, _In_ const std::wstring& accRatioEquality) = 0;
@ -177,7 +173,7 @@ namespace UnitConversionManager
class IConverterDataLoader class IConverterDataLoader
{ {
public: public:
virtual ~IConverterDataLoader(){}; virtual ~IConverterDataLoader() = default;
virtual void LoadData() = 0; // prepare data if necessary before calling other functions virtual void LoadData() = 0; // prepare data if necessary before calling other functions
virtual std::vector<Category> GetOrderedCategories() = 0; virtual std::vector<Category> GetOrderedCategories() = 0;
virtual std::vector<Unit> GetOrderedUnits(const Category& c) = 0; virtual std::vector<Unit> GetOrderedUnits(const Category& c) = 0;
@ -203,7 +199,7 @@ namespace UnitConversionManager
class IUnitConverterVMCallback class IUnitConverterVMCallback
{ {
public: public:
virtual ~IUnitConverterVMCallback(){}; virtual ~IUnitConverterVMCallback() = default;
virtual void DisplayCallback(const std::wstring& from, const std::wstring& to) = 0; virtual void DisplayCallback(const std::wstring& from, const std::wstring& to) = 0;
virtual void SuggestedValueCallback(const std::vector<std::tuple<std::wstring, Unit>>& suggestedValues) = 0; virtual void SuggestedValueCallback(const std::vector<std::tuple<std::wstring, Unit>>& suggestedValues) = 0;
virtual void MaxDigitsReached() = 0; virtual void MaxDigitsReached() = 0;
@ -212,9 +208,7 @@ namespace UnitConversionManager
class IUnitConverter class IUnitConverter
{ {
public: public:
virtual ~IUnitConverter() virtual ~IUnitConverter() = default;
{
}
virtual void Initialize() = 0; // Use to initialize first time, use deserialize instead to rehydrate virtual void Initialize() = 0; // Use to initialize first time, use deserialize instead to rehydrate
virtual std::vector<Category> GetCategories() = 0; virtual std::vector<Category> GetCategories() = 0;
virtual CategorySelectionInitializer SetCurrentCategory(const Category& input) = 0; virtual CategorySelectionInitializer SetCurrentCategory(const Category& input) = 0;
@ -289,8 +283,8 @@ namespace UnitConversionManager
Unit m_toType; Unit m_toType;
std::wstring m_currentDisplay; std::wstring m_currentDisplay;
std::wstring m_returnDisplay; std::wstring m_returnDisplay;
bool m_currentHasDecimal; bool m_currentHasDecimal{};
bool m_returnHasDecimal; bool m_returnHasDecimal{};
bool m_switchedActive; bool m_switchedActive{};
}; };
} }

View file

@ -474,14 +474,7 @@ namespace CalculatorApp
m_windowsMapLock.EnterReadLock(); m_windowsMapLock.EnterReadLock();
try try
{ {
if (m_secondaryWindows.TryGetValue(viewId, out var windowMapEntry)) return m_secondaryWindows.TryGetValue(viewId, out var windowMapEntry) ? windowMapEntry : null;
{
return windowMapEntry;
}
else
{
return null;
}
} }
finally finally
{ {

View file

@ -601,21 +601,19 @@ namespace CalculatorApp
{ {
if (itemRef.Target is MUXC.NavigationView item) if (itemRef.Target is MUXC.NavigationView item)
{ {
var navView = item; var menuItems = ((List<object>)item.MenuItemsSource);
var menuItems = ((List<object>)navView.MenuItemsSource);
if (menuItems != null) if (menuItems != null)
{ {
var vm = (navView.DataContext as ApplicationViewModel); var vm = (item.DataContext as ApplicationViewModel);
if (null != vm) if (null != vm)
{ {
ViewMode realToMode = toMode.HasValue ? toMode.Value : NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key)); ViewMode realToMode = toMode.HasValue ? toMode.Value : NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key));
var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)]; var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)];
if (CanNavigateModeByShortcut(navView, nvi, vm, realToMode)) if (CanNavigateModeByShortcut(item, nvi, vm, realToMode))
{ {
vm.Mode = realToMode; vm.Mode = realToMode;
navView.SelectedItem = nvi; item.SelectedItem = nvi;
} }
} }
} }
@ -685,14 +683,13 @@ namespace CalculatorApp
{ {
if (currentHonorShortcuts) if (currentHonorShortcuts)
{ {
var myVirtualKey = key;
var lookupMap = GetCurrentKeyDictionary(isControlKeyPressed, isShiftKeyPressed, isAltKeyPressed); var lookupMap = GetCurrentKeyDictionary(isControlKeyPressed, isShiftKeyPressed, isAltKeyPressed);
if (lookupMap == null) if (lookupMap == null)
{ {
return; return;
} }
var buttons = EqualRange(lookupMap, (MyVirtualKey)myVirtualKey); var buttons = EqualRange(lookupMap, (MyVirtualKey)key);
if (!buttons.Any()) if (!buttons.Any())
{ {
return; return;

View file

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
using System; using System;
@ -44,8 +44,6 @@ namespace CalculatorApp
{ {
// The value to be valid has to be a boxed int32 value // The value to be valid has to be a boxed int32 value
// extract that value and ensure it is valid, ie >= 0 // extract that value and ensure it is valid, ie >= 0
if (value != null)
{
if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32) if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32)
{ {
int index = box.GetInt32(); int index = box.GetInt32();
@ -54,7 +52,6 @@ namespace CalculatorApp
return value; return value;
} }
} }
}
// The value is not valid therefore stop the binding right here // The value is not valid therefore stop the binding right here
return Windows.UI.Xaml.DependencyProperty.UnsetValue; return Windows.UI.Xaml.DependencyProperty.UnsetValue;
} }

View file

@ -376,10 +376,7 @@ namespace CalculatorApp
var peer = FrameworkElementAutomationPeer.FromElement(TraceValue); var peer = FrameworkElementAutomationPeer.FromElement(TraceValue);
if (peer != null) peer?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
{
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
PositionGraphPopup(); PositionGraphPopup();
} }
@ -547,10 +544,7 @@ namespace CalculatorApp
var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName); var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName);
var peer = FrameworkElementAutomationPeer.FromElement(GraphingControl); var peer = FrameworkElementAutomationPeer.FromElement(GraphingControl);
if (peer != null) peer?.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId);
{
peer.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId);
}
} }
private void GraphingControl_GraphPlottedEvent(object sender, RoutedEventArgs e) private void GraphingControl_GraphPlottedEvent(object sender, RoutedEventArgs e)

View file

@ -66,10 +66,7 @@ namespace CalculatorApp
Window.Current.SizeChanged -= WindowSizeChanged; Window.Current.SizeChanged -= WindowSizeChanged;
m_accessibilitySettings.HighContrastChanged -= OnHighContrastChanged; m_accessibilitySettings.HighContrastChanged -= OnHighContrastChanged;
if (m_calculator != null) m_calculator?.UnregisterEventHandlers();
{
m_calculator.UnregisterEventHandlers();
}
} }
public void SetDefaultFocus() public void SetDefaultFocus()
@ -435,10 +432,7 @@ namespace CalculatorApp
private void UpdatePanelViewState() private void UpdatePanelViewState()
{ {
if (m_calculator != null) m_calculator?.UpdatePanelViewState();
{
m_calculator.UpdatePanelViewState();
}
} }
private void OnHighContrastChanged(AccessibilitySettings sender, object args) private void OnHighContrastChanged(AccessibilitySettings sender, object args)
@ -528,10 +522,7 @@ namespace CalculatorApp
ShowHideControls(Model.Mode); ShowHideControls(Model.Mode);
} }
if (m_dateCalculator != null) m_dateCalculator?.CloseCalendarFlyout();
{
m_dateCalculator.CloseCalendarFlyout();
}
} }
private void EnsureDateCalculator() private void EnsureDateCalculator()

View file

@ -1,4 +1,4 @@
using CalculatorApp.ViewModel; using CalculatorApp.ViewModel;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -56,14 +56,7 @@ namespace CalculatorApp
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{ {
SupplementaryResult result = (SupplementaryResult)item; SupplementaryResult result = (SupplementaryResult)item;
if (result.IsWhimsical()) return result.IsWhimsical() ? DelighterTemplate : RegularTemplate;
{
return DelighterTemplate;
}
else
{
return RegularTemplate;
}
} }
} }

View file

@ -166,14 +166,7 @@ namespace CalculatorApp
// Returns nullptr if no service is registered with the specified id // Returns nullptr if no service is registered with the specified id
private object TryResolveRuntimeWindowService(Type serviceId) private object TryResolveRuntimeWindowService(Type serviceId)
{ {
if (m_runtimeServicesMap.TryGetValue(serviceId.Name, out object retval)) return m_runtimeServicesMap.TryGetValue(serviceId.Name, out object retval) ? retval : null;
{
return retval;
}
else
{
return null;
}
} }
private readonly Windows.UI.Core.CoreWindow m_currentWindow; private readonly Windows.UI.Core.CoreWindow m_currentWindow;

View file

@ -17,12 +17,12 @@ namespace CalculatorUITestFramework
public string GetValue() public string GetValue()
{ {
var equalSignIndex = Item.Text.IndexOf("="); var equalSignIndex = Item.Text.IndexOf("=");
return Item.Text.Substring(equalSignIndex + 1).Trim(); return Item.Text[(equalSignIndex + 1)..].Trim();
} }
public string GetExpression() public string GetExpression()
{ {
var equalSignIndex = Item.Text.IndexOf("="); var equalSignIndex = Item.Text.IndexOf("=");
return Item.Text.Substring(0, equalSignIndex + 1).Trim(); return Item.Text[..(equalSignIndex + 1)].Trim();
} }
} }
} }

View file

@ -34,7 +34,7 @@ namespace CalculatorUITestFramework
string numberStr = number.ToString(CultureInfo.InvariantCulture); string numberStr = number.ToString(CultureInfo.InvariantCulture);
if (numberStr.StartsWith("-")) if (numberStr.StartsWith("-"))
{ {
numberStr = numberStr.Substring(1) + "-"; numberStr = numberStr[1..] + "-";
} }
foreach (char digit in numberStr) foreach (char digit in numberStr)
{ {

View file

@ -85,10 +85,7 @@ namespace CalculatorUITestFramework
} }
finally finally
{ {
if (sock != null) sock?.Dispose();
{
sock.Dispose();
}
} }
} }
} }

View file

@ -59,9 +59,7 @@ namespace MockGraphingImpl
class MockExpression : public Graphing::IExpression class MockExpression : public Graphing::IExpression
{ {
public: public:
MockExpression() MockExpression() = default;
{
}
unsigned int GetExpressionID() const override unsigned int GetExpressionID() const override
{ {
@ -76,9 +74,7 @@ namespace MockGraphingImpl
class MockVariable : public Graphing::IVariable class MockVariable : public Graphing::IVariable
{ {
public: public:
MockVariable() MockVariable() = default;
{
}
int GetVariableID() const override int GetVariableID() const override
{ {
@ -96,9 +92,7 @@ namespace MockGraphingImpl
class MathSolver : public Graphing::IMathSolver class MathSolver : public Graphing::IMathSolver
{ {
public: public:
MathSolver() MathSolver() = default;
{
}
Graphing::IParsingOptions& ParsingOptions() override Graphing::IParsingOptions& ParsingOptions() override
{ {