mirror of
https://github.com/Microsoft/calculator.git
synced 2025-07-11 15:56:01 -07:00
* Hello C# - Going to an official feature branch (#1544) * change CalcViewModel into a WindowsRuntimeComponent project (#5) * change CalcViewModel into a WindowsRuntimeComponent project * remove the old UI codebase (#6) * initially migrated C# codebase by tian (#7) * initial migrated C# codebase by tian * format the codebase * resolve comments * undo: modifications on UI test project * Remove the blocks that have more than 1 empty line. * Register DP using keyword 'nameof' * C# Migration: Initially migrated C# codebase by Han (#8) * C# Migration: Initially migrated C# codebase by Han * Resolved comments and misssing asset * Added three files to Calculator project * Added TODO comment and updated Object * NavCategory: temporary resolution of the hang issue (#9) * Updated CalcViewModel and missing files (#10) * Updated CalcViewModel and WinMeta * Added Calculator.rc * Resolved comment for InitializeLocalizationSettings * add: views/unitconverter.xaml (#11) * add: views/unitconverter.xaml * format the code * remove the extra empty line * add an empty line * check null before invoking event handlers (#12) * fix problems of the migration of OBSERVABLE_PROPERTY_RW (#13) * fixes crash in MathRichEditBox.ctor() (#14) * fixes crash in MathRichEditBox.ctor() * typo * Update azure-pipelines.ci.yaml for Azure Pipelines * Added a link copy of CalcViewModel to temporarily pass Unit Tests (#16) * Updated CalcViewModelCopyForUT configuration (#17) * changes output path of the UI project to align with other projects (#15) * fixes EETypeLoadException issue: export class DelegateCommand (#18) * fixes EETypeLoadException issue: export class DelegateCommand * weak-reference in C++/CX * WeakRef in C# codebase * UTF-8-BOM * spaces in macro * resolve some comments from the offline review * format * rename file * fixes the memory list issue (#20) * fixes a wrongly migrated property * UTF-8-BOM * fixes up the crash of type casting (#21) * Update localized strings 2021-01-04 (#1458) (#23) (cherry picked from commitcdcb95656d
) Co-authored-by: Matt Cooley <macool@microsoft.com> * Fixup tests (#1429) (#24) - Removed unneeded "ToString" calls - Fixed typos - Renamed "fEButtonState" to "FEButtonState" (cherry picked from commit66ad328d00
) Co-authored-by: N <71219152+PokeCodec@users.noreply.github.com> * Update graph internal engine verseion (#1466) (#25) (cherry picked from commit0048dcb500
) Co-authored-by: Quentin Al-Timimi <27322516+quentin987@users.noreply.github.com> * Turn off DFS file shares in internal build system (#1470) (#26) (cherry picked from commit885fa23a89
) Co-authored-by: Matt Cooley <macool@microsoft.com> * Improve clarity of math expressions in history for Standard Calculator (feature #138) (#1453) (#27) * Implemented feature & added unit tests * Fixed more unit/ui tests * Refactored tests * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp * Update HistoryTests.cpp (cherry picked from commit565e3e2714
) Co-authored-by: Wei (Waley) Zhang <waley.zhang@microsoft.com> * Adds unit-test cases for NarratorAnnouncement after fixing issue #1386 (#1469) (#28) * fix bug: No confirmation is announced by the narrator after activating 'Remove equation' button #1386 * Unit Test: Add NarratorAnnouncementUnitTests Co-authored-by: tain <tankle_@hotmail.com> (cherry picked from commit9d8e2ad18c
) Co-authored-by: Tian L <60599517+MSFT-Tilia@users.noreply.github.com> * Move localization pipeline sync schedule to the YAML file (#1478) (#30) (cherry picked from commit007eccd940
) Co-authored-by: Matt Cooley <macool@microsoft.com> * remove the strong reference carried from delegate (#32) * Remove the finalizer of ControlSizeTrigger (#31) * Normalize the namespace of CalcViewModel (#33) * ViewMode: arrange namespaces * UI build pass * run release * UT build pass * pass build * resolve comment: make the diff results cleaner * resolve comment: make the diff results cleaner (2) * resolve comment: make the diff results cleaner (3) * resolve comment: move impl into a namespace * update: spaces * update: CalculatorButtonUser.h * UTF-8 to UTF-8-BOM * remove ViewState.h/.cpp from CalcViewModel path * revert changes for NavCategory.cpp * remove extra space * remove UCM * remove BOM * Fixed a graphing calculator "permissions" bug caused by PR #1426 (#1471) (#34) - The PR #1426 can cause a crash when no users are returned via `User::FindAllAsync(UserType::LocalUser)` when subsequently trying to access the first user. The existing code also does not guarantee that the returned user is the currently active user. - This fix retrieves the user that opened the app and passes this user into a function to check if this user has the proper permissions to access the graphing mode. This makes sense since the active user is indistinguishable (at least from the app's perspective) to the user who opened the app. This user's permissions are then propagated downwards to properly set up the navigation menu of the app. - Implementation detail worth pointing out: `s_categoryManifest` is what is used to populate the navigation menu of the app, but this variable is static by design, so a separate function was written to override the appropriate `isEnabled` value in `s_categoryManifest`. This function is called by `onLaunched`. - Manual testing Co-authored-by: Wei (Waley) Zhang <waley.zhang@microsoft.com> * fixes up a bug (#35) * fix csproj (#37) Co-authored-by: hanzhang54 <zhangh@microsoft.com> Co-authored-by: Matt Cooley <macool@microsoft.com> Co-authored-by: N <71219152+PokeCodec@users.noreply.github.com> Co-authored-by: Quentin Al-Timimi <27322516+quentin987@users.noreply.github.com> Co-authored-by: Wei (Waley) Zhang <waley.zhang@microsoft.com> Co-authored-by: Tian L <60599517+MSFT-Tilia@users.noreply.github.com> * **BYPASS_SECRET_SCANNING** (#1546) * Fixes a bug about the UI of expression tokens (#1547) * fix * [FeatureBranch] Fixes x86/ARM/ARM64 builds for the CI-Pipeline (#1550) * **BYPASS_SECRET_SCANNING** * fix * fixes x86/ARM/ARM64 builds for CI-Pipeline * Add headers missing for compilation with GCC (#1468) (#1551) Things that required such update included: * `wstringstream` * `setprecision` * `SCODE_CODE`, `E_BOUNDS` * Various SAL macros Co-authored-by: Michał Janiszewski <janisozaur@users.noreply.github.com> * Update nuget.config file (#1486) (#1552) Co-authored-by: Matt Cooley <macool@microsoft.com> * Fixes up some simple miscellaneous TODO items (#1556) * #DEBUG is a known C# preprocessor directive * So far, we haven't observed the problem described in the comment from C# async * fixes misc TODO items * resolve some warnings (#1564) * Add internal CI pipeline (#1553) (#1565) * Add CI-internal pipeline * No ARM64, to match release Co-authored-by: Matt Cooley <macool@microsoft.com> * Temporarily disable PGO NuGet package (#1510) (#1566) Co-authored-by: Matt Cooley <macool@microsoft.com> * [C# Calc]Removes WinMeta.cs (#1567) * remove WinMeta.cs * undo a trivial change * UTF-8 BOM * [C# Calc] Reverts some changes for Currency constants (#1570) * Update2108release - experimental (#1572) * adjusts Calculator.csproj (#1571) * fixes BinSkim problems (#1573) * fixes an issue around line style (#1575) * fixes the missed NULLs (#1576) (#1578) * Fix the Missing Part in Unit Converter Constructor (#1579) * fixes: calculator doesn't remember its previous mode (#1580) * Fixes: GraphingNumber doesn't work correctly (#1585) * fixes: GraphingNumber doesn't work correctly * Avoid crashing * fixes binding (#1586) * resolve TODO items (#1589) * Improving keyboard support in VariableValueSlider (#1559) (#1595) Co-authored-by: Dave Grochocki <grochocki@users.noreply.github.com> * [C# Calc] Fixes: Keep the value away from getting rounded in Graphing Mode (#1596) * keep the value away from getting rounded * set the display precision to 6 to align with C++ impl * fixes the button-light-up time (#1597) * fixes up merging flaws * Update2108release * fixes (#1599) * keep master for ci pipeline * remove the Resources filter from CalcViewModel project * removes `that` since `this` can be captured automatically * AppxBundlePlatforms * StampAssemblyInfo * removes PreferredToolArchitecture * Change the arg AppVersion into Version * Change the arg AppVersion into Version * from Calculator.rc to AssemblyInfo.cs * Adds assembly-info Co-authored-by: hanzhang54 <zhangh@microsoft.com> Co-authored-by: Matt Cooley <macool@microsoft.com> Co-authored-by: N <71219152+PokeCodec@users.noreply.github.com> Co-authored-by: Quentin Al-Timimi <27322516+quentin987@users.noreply.github.com> Co-authored-by: Wei (Waley) Zhang <waley.zhang@microsoft.com> Co-authored-by: Tian L <60599517+MSFT-Tilia@users.noreply.github.com> Co-authored-by: Michał Janiszewski <janisozaur@users.noreply.github.com> Co-authored-by: Dave Grochocki <grochocki@users.noreply.github.com>
361 lines
14 KiB
C++
361 lines
14 KiB
C++
// Copyright (c) Microsoft Corporation. All rights reserved.
|
|
// Licensed under the MIT License.
|
|
|
|
#include "pch.h"
|
|
#include "DateCalculator.h"
|
|
|
|
using namespace Platform;
|
|
using namespace Windows::Foundation;
|
|
using namespace Windows::Globalization;
|
|
using namespace CalculatorApp::ViewModel::Common::DateCalculation;
|
|
|
|
bool operator==(const DateDifference& l, const DateDifference& r)
|
|
{
|
|
return l.year == r.year && l.month == r.month && l.week == r.week && l.day == r.day;
|
|
}
|
|
|
|
DateCalculationEngine::DateCalculationEngine(_In_ String ^ calendarIdentifier)
|
|
{
|
|
m_calendar = ref new Calendar();
|
|
m_calendar->ChangeTimeZone("UTC");
|
|
m_calendar->ChangeCalendarSystem(calendarIdentifier);
|
|
}
|
|
|
|
// Adding Duration to a Date
|
|
// Returns: True if function succeeds to calculate the date else returns False
|
|
IBox<DateTime> ^ DateCalculationEngine::AddDuration(DateTime startDate, DateDifference duration)
|
|
{
|
|
auto currentCalendarSystem = m_calendar->GetCalendarSystem();
|
|
try
|
|
{
|
|
m_calendar->SetDateTime(startDate);
|
|
|
|
// The Japanese Era system can have multiple year partitions within the same year.
|
|
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
|
|
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results
|
|
// in a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date
|
|
// math, and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and
|
|
// durations as the Gregorian system and is only different in display value.
|
|
if (currentCalendarSystem == CalendarIdentifiers::Japanese)
|
|
{
|
|
m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian);
|
|
}
|
|
|
|
if (duration.year != 0)
|
|
{
|
|
m_calendar->AddYears(duration.year);
|
|
}
|
|
if (duration.month != 0)
|
|
{
|
|
m_calendar->AddMonths(duration.month);
|
|
}
|
|
if (duration.day != 0)
|
|
{
|
|
m_calendar->AddDays(duration.day);
|
|
}
|
|
|
|
m_calendar->ChangeCalendarSystem(currentCalendarSystem);
|
|
return m_calendar->GetDateTime();
|
|
}
|
|
catch (Platform::InvalidArgumentException ^ ex)
|
|
{
|
|
// ensure that we revert to the correct calendar system
|
|
m_calendar->ChangeCalendarSystem(currentCalendarSystem);
|
|
|
|
// Do nothing
|
|
return nullptr;
|
|
}
|
|
}
|
|
|
|
// Subtracting Duration from a Date
|
|
// Returns: True if function succeeds to calculate the date else returns False
|
|
IBox<DateTime> ^ DateCalculationEngine::SubtractDuration(_In_ DateTime startDate, _In_ DateDifference duration)
|
|
{
|
|
auto currentCalendarSystem = m_calendar->GetCalendarSystem();
|
|
|
|
// For Subtract the Algorithm is different than Add. Here the smaller units are subtracted first
|
|
// and then the larger units.
|
|
try
|
|
{
|
|
m_calendar->SetDateTime(startDate);
|
|
|
|
// The Japanese Era system can have multiple year partitions within the same year.
|
|
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
|
|
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results
|
|
// in a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date
|
|
// math, and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and
|
|
// durations as the Gregorian system and is only different in display value.
|
|
if (currentCalendarSystem == CalendarIdentifiers::Japanese)
|
|
{
|
|
m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian);
|
|
}
|
|
|
|
if (duration.day != 0)
|
|
{
|
|
m_calendar->AddDays(-duration.day);
|
|
}
|
|
if (duration.month != 0)
|
|
{
|
|
m_calendar->AddMonths(-duration.month);
|
|
}
|
|
if (duration.year != 0)
|
|
{
|
|
m_calendar->AddYears(-duration.year);
|
|
}
|
|
m_calendar->ChangeCalendarSystem(currentCalendarSystem);
|
|
|
|
auto dateTime = m_calendar->GetDateTime();
|
|
// Check that the UniversalTime value is not negative
|
|
if (dateTime.UniversalTime >= 0)
|
|
{
|
|
return dateTime;
|
|
}
|
|
else
|
|
{
|
|
return nullptr;
|
|
}
|
|
}
|
|
catch (Platform::InvalidArgumentException ^ ex)
|
|
{
|
|
// ensure that we revert to the correct calendar system
|
|
m_calendar->ChangeCalendarSystem(currentCalendarSystem);
|
|
|
|
// Do nothing
|
|
return nullptr;
|
|
}
|
|
}
|
|
|
|
// Calculate the difference between two dates
|
|
IBox<DateDifference> ^ DateCalculationEngine::TryGetDateDifference(_In_ DateTime date1, _In_ DateTime date2, _In_ DateUnit outputFormat)
|
|
{
|
|
DateTime startDate;
|
|
DateTime endDate;
|
|
DateTime pivotDate;
|
|
DateTime tempPivotDate;
|
|
UINT daysDiff = 0;
|
|
UINT differenceInDates[c_unitsOfDate] = { 0 };
|
|
|
|
if (date1.UniversalTime < date2.UniversalTime)
|
|
{
|
|
startDate = date1;
|
|
endDate = date2;
|
|
}
|
|
else
|
|
{
|
|
startDate = date2;
|
|
endDate = date1;
|
|
}
|
|
|
|
pivotDate = startDate;
|
|
|
|
daysDiff = GetDifferenceInDays(startDate, endDate);
|
|
|
|
// If output has units other than days
|
|
// 0th bit: Year, 1st bit: Month, 2nd bit: Week, 3rd bit: Day
|
|
if (static_cast<int>(outputFormat) & 7)
|
|
{
|
|
UINT daysInMonth;
|
|
UINT approximateDaysInYear;
|
|
|
|
// If we're unable to calculate the days-in-month or days-in-year, we'll leave the values at 0.
|
|
if (TryGetCalendarDaysInMonth(startDate, daysInMonth) && TryGetCalendarDaysInYear(endDate, approximateDaysInYear))
|
|
{
|
|
UINT daysIn[c_unitsOfDate] = { approximateDaysInYear, daysInMonth, c_daysInWeek, 1 };
|
|
|
|
for (int unitIndex = 0; unitIndex < c_unitsGreaterThanDays; unitIndex++)
|
|
{
|
|
tempPivotDate = pivotDate;
|
|
|
|
// Check if the bit flag is set for the date unit
|
|
DateUnit dateUnit = static_cast<DateUnit>(1 << unitIndex);
|
|
|
|
if (static_cast<int>(outputFormat & dateUnit))
|
|
{
|
|
bool isEndDateHit = false;
|
|
differenceInDates[unitIndex] = (daysDiff / daysIn[unitIndex]);
|
|
|
|
if (differenceInDates[unitIndex] != 0)
|
|
{
|
|
try
|
|
{
|
|
pivotDate = AdjustCalendarDate(pivotDate, dateUnit, static_cast<int>(differenceInDates[unitIndex]));
|
|
}
|
|
catch (Platform::InvalidArgumentException ^)
|
|
{
|
|
// Operation failed due to out of bound result
|
|
// For example: 31st Dec, 9999 - last valid date
|
|
return nullptr;
|
|
}
|
|
}
|
|
|
|
int tempDaysDiff;
|
|
|
|
do
|
|
{
|
|
tempDaysDiff = GetDifferenceInDays(pivotDate, endDate);
|
|
|
|
if (tempDaysDiff < 0)
|
|
{
|
|
// pivotDate has gone over the end date; start from the beginning of this unit
|
|
if (differenceInDates[unitIndex] == 0)
|
|
{
|
|
// differenceInDates[unitIndex] is unsigned, the value can't be negative
|
|
return nullptr;
|
|
}
|
|
differenceInDates[unitIndex] -= 1;
|
|
pivotDate = tempPivotDate;
|
|
pivotDate = AdjustCalendarDate(pivotDate, dateUnit, static_cast<int>(differenceInDates[unitIndex]));
|
|
isEndDateHit = true;
|
|
}
|
|
else if (tempDaysDiff > 0)
|
|
{
|
|
if (isEndDateHit)
|
|
{
|
|
// This is the closest the pivot can get to the end date for this unit
|
|
break;
|
|
}
|
|
|
|
// pivotDate is still below the end date
|
|
try
|
|
{
|
|
pivotDate = AdjustCalendarDate(tempPivotDate, dateUnit, static_cast<int>(differenceInDates[unitIndex] + 1));
|
|
differenceInDates[unitIndex] += 1;
|
|
}
|
|
catch (Platform::InvalidArgumentException ^)
|
|
{
|
|
// Operation failed due to out of bound result
|
|
// For example: 31st Dec, 9999 - last valid date
|
|
return nullptr;
|
|
}
|
|
}
|
|
} while (tempDaysDiff != 0); // dates are the same - exit the loop
|
|
|
|
tempPivotDate = AdjustCalendarDate(tempPivotDate, dateUnit, static_cast<int>(differenceInDates[unitIndex]));
|
|
pivotDate = tempPivotDate;
|
|
int signedDaysDiff = GetDifferenceInDays(pivotDate, endDate);
|
|
if (signedDaysDiff < 0)
|
|
{
|
|
// daysDiff is unsigned, the value can't be negative
|
|
return nullptr;
|
|
}
|
|
|
|
daysDiff = signedDaysDiff;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
differenceInDates[3] = daysDiff;
|
|
|
|
DateDifference result;
|
|
result.year = differenceInDates[0];
|
|
result.month = differenceInDates[1];
|
|
result.week = differenceInDates[2];
|
|
result.day = differenceInDates[3];
|
|
return result;
|
|
}
|
|
|
|
// Private Methods
|
|
|
|
// Gets number of days between the two date time values
|
|
int DateCalculationEngine::GetDifferenceInDays(DateTime date1, DateTime date2)
|
|
{
|
|
// A tick is defined as the number of 100 nanoseconds
|
|
long long ticksDifference = date2.UniversalTime - date1.UniversalTime;
|
|
return static_cast<int>(ticksDifference / static_cast<long long>(c_day));
|
|
}
|
|
|
|
// Gets number of Calendar days in the month in which this date falls.
|
|
// Returns true if successful, false otherwise.
|
|
bool DateCalculationEngine::TryGetCalendarDaysInMonth(_In_ DateTime date, _Out_ UINT& daysInMonth)
|
|
{
|
|
bool result = false;
|
|
m_calendar->SetDateTime(date);
|
|
|
|
// NumberOfDaysInThisMonth returns -1 if unknown.
|
|
int daysInThisMonth = m_calendar->NumberOfDaysInThisMonth;
|
|
if (daysInThisMonth != -1)
|
|
{
|
|
daysInMonth = static_cast<UINT>(daysInThisMonth);
|
|
result = true;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Gets number of Calendar days in the year in which this date falls.
|
|
// Returns true if successful, false otherwise.
|
|
bool DateCalculationEngine::TryGetCalendarDaysInYear(_In_ DateTime date, _Out_ UINT& daysInYear)
|
|
{
|
|
bool result = false;
|
|
UINT days = 0;
|
|
|
|
m_calendar->SetDateTime(date);
|
|
|
|
// NumberOfMonthsInThisYear returns -1 if unknown.
|
|
int monthsInYear = m_calendar->NumberOfMonthsInThisYear;
|
|
if (monthsInYear != -1)
|
|
{
|
|
bool monthResult = true;
|
|
|
|
// Not all years begin with Month 1.
|
|
int firstMonthThisYear = m_calendar->FirstMonthInThisYear;
|
|
for (int month = 0; month < monthsInYear; month++)
|
|
{
|
|
m_calendar->Month = firstMonthThisYear + month;
|
|
|
|
// NumberOfDaysInThisMonth returns -1 if unknown.
|
|
int daysInMonth = m_calendar->NumberOfDaysInThisMonth;
|
|
if (daysInMonth == -1)
|
|
{
|
|
monthResult = false;
|
|
break;
|
|
}
|
|
|
|
days += daysInMonth;
|
|
}
|
|
|
|
if (monthResult)
|
|
{
|
|
daysInYear = days;
|
|
result = true;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Adds/Subtracts certain value for a particular date unit
|
|
DateTime DateCalculationEngine::AdjustCalendarDate(Windows::Foundation::DateTime date, DateUnit dateUnit, int difference)
|
|
{
|
|
m_calendar->SetDateTime(date);
|
|
|
|
// The Japanese Era system can have multiple year partitions within the same year.
|
|
// For example, April 30, 2019 is denoted April 30, Heisei 31; May 1, 2019 is denoted as May 1, Reiwa 1.
|
|
// The Calendar treats Heisei 31 and Reiwa 1 as separate years, which results in some unexpected behaviors where subtracting a year from Reiwa 1 results in
|
|
// a date in Heisei 31. To provide the expected result across era boundaries, we first convert the Japanese era system to a Gregorian system, do date math,
|
|
// and then convert back to the Japanese era system. This works because the Japanese era system maintains the same year/month boundaries and durations as
|
|
// the Gregorian system and is only different in display value.
|
|
auto currentCalendarSystem = m_calendar->GetCalendarSystem();
|
|
if (currentCalendarSystem == CalendarIdentifiers::Japanese)
|
|
{
|
|
m_calendar->ChangeCalendarSystem(CalendarIdentifiers::Gregorian);
|
|
}
|
|
|
|
switch (dateUnit)
|
|
{
|
|
case DateUnit::Year:
|
|
m_calendar->AddYears(difference);
|
|
break;
|
|
case DateUnit::Month:
|
|
m_calendar->AddMonths(difference);
|
|
break;
|
|
case DateUnit::Week:
|
|
m_calendar->AddWeeks(difference);
|
|
break;
|
|
}
|
|
|
|
m_calendar->ChangeCalendarSystem(currentCalendarSystem);
|
|
|
|
return m_calendar->GetDateTime();
|
|
}
|