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

View file

@ -2,6 +2,7 @@
// Licensed under the MIT License.
#include <cassert>
#include <utility>
#include "Header Files/CalcEngine.h"
#include "CalculatorResource.h"
@ -96,7 +97,7 @@ CCalcEngine::CCalcEngine(
, m_nLastCom(0)
, m_angletype(AngleType::Degrees)
, 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)
{
InitChopNumbers();

View file

@ -1124,5 +1124,5 @@ double CCalcEngine::GenerateRandomNumber()
m_randomGeneratorEngine = std::make_unique<std::mt19937>(rd());
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;
int32_t precision;
uint32_t radix;
int nFE;
NumberFormat nFE;
NUM_WIDTH numwidth;
bool fIntMath;
bool bRecord;
bool bUseSep;
} 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
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
// 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.precision = m_precision;
gldPrevious.radix = m_radix;
gldPrevious.nFE = (int)m_nFE;
gldPrevious.nFE = m_nFE;
gldPrevious.numwidth = m_numwidth;
gldPrevious.fIntMath = m_fIntegerMode;
@ -156,7 +156,7 @@ int CCalcEngine::IsNumberInvalid(const wstring& numberString, int iMaxExp, int i
auto intEnd = exp.end();
while (intItr != intEnd && *intItr == L'0')
{
intItr++;
++intItr;
}
auto iMantissa = distance(intItr, intEnd) + matches.length(2);

View file

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

View file

@ -10,9 +10,7 @@ namespace CalculationManager
class IResourceProvider
{
public:
virtual ~IResourceProvider()
{
}
virtual ~IResourceProvider() = default;
// Should return a string from the resource table for strings used
// 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)
{
static const wchar_t chZero = L'0';
static constexpr wchar_t chZero = L'0';
const size_t nCommands = m_commands->size();
m_token.clear();

View file

@ -154,14 +154,14 @@ private:
std::unique_ptr<std::mt19937> m_randomGeneratorEngine;
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
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
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;
private:

View file

@ -44,12 +44,12 @@ private:
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
// 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_lastBinOpStartIndex; // index of the beginning of the last binary operator 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
std::array<int, MAXPRECDEPTH>
m_operandIndices; // Stack of index of opnd's beginning for each '('. A parallel array to m_hnoParNum, but abstracted independently of that
int m_curOperandIndex; // Stack index for the above stack
bool m_bLastOpndBrace; // iff the last opnd in history is already braced so we can avoid putting another one for unary operator
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
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;
std::shared_ptr<std::vector<std::pair<std::wstring, int>>> m_spTokens;
std::shared_ptr<std::vector<std::shared_ptr<IExpressionCommand>>> m_spCommands;

View file

@ -9,7 +9,7 @@
class IHistoryDisplay
{
public:
virtual ~IHistoryDisplay(){};
virtual ~IHistoryDisplay() = default;
virtual unsigned int AddToHistory(
_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,

View file

@ -411,7 +411,7 @@ void UnitConverter::SendCommand(Command command)
{
clearFront = (m_currentDisplay == L"0");
clearBack =
((m_currentHasDecimal && m_currentDisplay.size() - 1 >= MAXIMUMDIGITSALLOWED)
((m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED + 1)
|| (!m_currentHasDecimal && m_currentDisplay.size() >= MAXIMUMDIGITSALLOWED));
}
@ -619,15 +619,15 @@ vector<tuple<wstring, Unit>> UnitConverter::CalculateSuggested()
vector<SuggestedValueIntermediate> intermediateWhimsicalVector;
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
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;
newEntry.magnitude = log10(convertedValue);
newEntry.value = convertedValue;
newEntry.type = cur.first;
newEntry.type = first;
if (newEntry.type.isWhimsical)
intermediateWhimsicalVector.push_back(newEntry);
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(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))
{
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
for (const auto& entry : intermediateVector)
for (const auto& [magnitude, value, type] : intermediateVector)
{
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
{
roundedString = RoundSignificantDigits(entry.value, 0U);
roundedString = RoundSignificantDigits(value, 0U);
}
if (stod(roundedString) != 0.0 || m_currentCategory.supportsNegative)
{
TrimTrailingZeros(roundedString);
returnVector.emplace_back(roundedString, entry.type);
returnVector.emplace_back(roundedString, type);
}
}
// The Whimsicals are determined differently
// 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))
{
return first.magnitude > second.magnitude;

View file

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

View file

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

View file

@ -601,21 +601,19 @@ namespace CalculatorApp
{
if (itemRef.Target is MUXC.NavigationView item)
{
var navView = item;
var menuItems = ((List<object>)navView.MenuItemsSource);
var menuItems = ((List<object>)item.MenuItemsSource);
if (menuItems != null)
{
var vm = (navView.DataContext as ApplicationViewModel);
var vm = (item.DataContext as ApplicationViewModel);
if (null != vm)
{
ViewMode realToMode = toMode.HasValue ? toMode.Value : NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key));
var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)];
if (CanNavigateModeByShortcut(navView, nvi, vm, realToMode))
if (CanNavigateModeByShortcut(item, nvi, vm, realToMode))
{
vm.Mode = realToMode;
navView.SelectedItem = nvi;
item.SelectedItem = nvi;
}
}
}
@ -685,14 +683,13 @@ namespace CalculatorApp
{
if (currentHonorShortcuts)
{
var myVirtualKey = key;
var lookupMap = GetCurrentKeyDictionary(isControlKeyPressed, isShiftKeyPressed, isAltKeyPressed);
if (lookupMap == null)
{
return;
}
var buttons = EqualRange(lookupMap, (MyVirtualKey)myVirtualKey);
var buttons = EqualRange(lookupMap, (MyVirtualKey)key);
if (!buttons.Any())
{
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.
using System;
@ -44,8 +44,6 @@ namespace CalculatorApp
{
// The value to be valid has to be a boxed int32 value
// 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)
{
int index = box.GetInt32();
@ -54,7 +52,6 @@ namespace CalculatorApp
return value;
}
}
}
// The value is not valid therefore stop the binding right here
return Windows.UI.Xaml.DependencyProperty.UnsetValue;
}

View file

@ -376,10 +376,7 @@ namespace CalculatorApp
var peer = FrameworkElementAutomationPeer.FromElement(TraceValue);
if (peer != null)
{
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
peer?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
PositionGraphPopup();
}
@ -547,10 +544,7 @@ namespace CalculatorApp
var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName);
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)

View file

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

View file

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

View file

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

View file

@ -17,12 +17,12 @@ namespace CalculatorUITestFramework
public string GetValue()
{
var equalSignIndex = Item.Text.IndexOf("=");
return Item.Text.Substring(equalSignIndex + 1).Trim();
return Item.Text[(equalSignIndex + 1)..].Trim();
}
public string GetExpression()
{
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);
if (numberStr.StartsWith("-"))
{
numberStr = numberStr.Substring(1) + "-";
numberStr = numberStr[1..] + "-";
}
foreach (char digit in numberStr)
{

View file

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

View file

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