forked from microsoft/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StandardCalculatorViewModel.cpp
1867 lines (1647 loc) · 64.1 KB
/
StandardCalculatorViewModel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "StandardCalculatorViewModel.h"
#include "Common/CalculatorButtonPressedEventArgs.h"
#include "Common/LocalizationStringUtil.h"
#include "Common/LocalizationSettings.h"
#include "Common/CopyPasteManager.h"
#include "Common/TraceLogger.h"
using namespace CalculatorApp;
using namespace CalculatorApp::Common;
using namespace CalculatorApp::Common::Automation;
using namespace CalculatorApp::ViewModel;
using namespace CalculationManager;
using namespace Platform;
using namespace Platform::Collections;
using namespace std;
using namespace Windows::ApplicationModel::Resources;
using namespace Windows::Foundation;
using namespace Windows::System;
using namespace Windows::UI::Core;
using namespace Windows::UI::Popups;
using namespace Windows::Storage::Streams;
using namespace Windows::Foundation::Collections;
using namespace Utils;
using namespace concurrency;
constexpr int StandardModePrecision = 16;
constexpr int ScientificModePrecision = 32;
constexpr int ProgrammerModePrecision = 64;
namespace
{
StringReference IsStandardPropertyName(L"IsStandard");
StringReference IsScientificPropertyName(L"IsScientific");
StringReference IsProgrammerPropertyName(L"IsProgrammer");
StringReference IsAlwaysOnTopPropertyName(L"IsAlwaysOnTop");
StringReference DisplayValuePropertyName(L"DisplayValue");
StringReference CalculationResultAutomationNamePropertyName(L"CalculationResultAutomationName");
StringReference IsBitFlipCheckedPropertyName(L"IsBitFlipChecked");
}
namespace CalculatorResourceKeys
{
StringReference CalculatorExpression(L"Format_CalculatorExpression");
StringReference CalculatorResults(L"Format_CalculatorResults");
StringReference CalculatorResults_DecimalSeparator_Announced(L"Format_CalculatorResults_Decimal");
StringReference HexButton(L"Format_HexButtonValue");
StringReference DecButton(L"Format_DecButtonValue");
StringReference OctButton(L"Format_OctButtonValue");
StringReference BinButton(L"Format_BinButtonValue");
StringReference OpenParenthesisCountAutomationFormat(L"Format_OpenParenthesisCountAutomationNamePrefix");
StringReference NoParenthesisAdded(L"NoRightParenthesisAdded_Announcement");
StringReference MaxDigitsReachedFormat(L"Format_MaxDigitsReached");
StringReference ButtonPressFeedbackFormat(L"Format_ButtonPressAuditoryFeedback");
StringReference MemorySave(L"Format_MemorySave");
StringReference MemoryItemChanged(L"Format_MemorySlotChanged");
StringReference MemoryItemCleared(L"Format_MemorySlotCleared");
StringReference MemoryCleared(L"Memory_Cleared");
StringReference DisplayCopied(L"Display_Copied");
}
StandardCalculatorViewModel::StandardCalculatorViewModel()
: m_DisplayValue(L"0")
, m_DecimalDisplayValue(L"0")
, m_HexDisplayValue(L"0")
, m_BinaryDisplayValue(L"0")
, m_OctalDisplayValue(L"0")
, m_BinaryDigits(ref new Vector<bool>(64, false))
, m_standardCalculatorManager(&m_calculatorDisplay, &m_resourceProvider)
, m_ExpressionTokens(ref new Vector<DisplayExpressionToken ^>())
, m_MemorizedNumbers(ref new Vector<MemoryItemViewModel ^>())
, m_IsMemoryEmpty(true)
, m_IsFToEChecked(false)
, m_IsShiftProgrammerChecked(false)
, m_valueBitLength(BitLength::BitLengthQWord)
, m_isBitFlipChecked(false)
, m_isBinaryBitFlippingEnabled(false)
, m_CurrentRadixType(RADIX_TYPE::DEC_RADIX)
, m_CurrentAngleType(NumbersAndOperatorsEnum::Degree)
, m_Announcement(nullptr)
, m_OpenParenthesisCount(0)
, m_feedbackForButtonPress(nullptr)
, m_isRtlLanguage(false)
, m_localizedMaxDigitsReachedAutomationFormat(nullptr)
, m_localizedButtonPressFeedbackAutomationFormat(nullptr)
, m_localizedMemorySavedAutomationFormat(nullptr)
, m_localizedMemoryItemChangedAutomationFormat(nullptr)
, m_localizedMemoryItemClearedAutomationFormat(nullptr)
, m_localizedMemoryCleared(nullptr)
, m_localizedOpenParenthesisCountChangedAutomationFormat(nullptr)
, m_localizedNoRightParenthesisAddedFormat(nullptr)
{
WeakReference calculatorViewModel(this);
auto appResourceProvider = AppResourceProvider::GetInstance();
m_calculatorDisplay.SetCallback(calculatorViewModel);
m_expressionAutomationNameFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::CalculatorExpression);
m_localizedCalculationResultAutomationFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::CalculatorResults);
m_localizedCalculationResultDecimalAutomationFormat =
appResourceProvider->GetResourceString(CalculatorResourceKeys::CalculatorResults_DecimalSeparator_Announced);
m_localizedHexaDecimalAutomationFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::HexButton);
m_localizedDecimalAutomationFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::DecButton);
m_localizedOctalAutomationFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::OctButton);
m_localizedBinaryAutomationFormat = appResourceProvider->GetResourceString(CalculatorResourceKeys::BinButton);
// Initialize the Automation Name
CalculationResultAutomationName = GetLocalizedStringFormat(m_localizedCalculationResultAutomationFormat, m_DisplayValue);
CalculationExpressionAutomationName = GetLocalizedStringFormat(m_expressionAutomationNameFormat, L"");
// Initialize history view model
m_HistoryVM = ref new HistoryViewModel(&m_standardCalculatorManager);
m_HistoryVM->SetCalculatorDisplay(m_calculatorDisplay);
m_decimalSeparator = LocalizationSettings::GetInstance().GetDecimalSeparator();
if (CoreWindow::GetForCurrentThread() != nullptr)
{
// Must have a CoreWindow to access the resource context.
m_isRtlLanguage = LocalizationService::GetInstance()->IsRtlLayout();
}
IsEditingEnabled = false;
IsUnaryOperatorEnabled = true;
IsBinaryOperatorEnabled = true;
IsOperandEnabled = true;
IsNegateEnabled = true;
IsDecimalEnabled = true;
AreHistoryShortcutsEnabled = true;
AreProgrammerRadixOperatorsEnabled = false;
m_tokenPosition = -1;
m_isLastOperationHistoryLoad = false;
}
String ^ StandardCalculatorViewModel::LocalizeDisplayValue(_In_ wstring const& displayValue, _In_ bool isError)
{
wstring result(displayValue);
LocalizationSettings::GetInstance().LocalizeDisplayValue(&result);
// WINBLUE: 440747 - In BiDi languages, error messages need to be wrapped in LRE/PDF
if (isError && m_isRtlLanguage)
{
result.insert(result.begin(), Utils::LRE);
result.push_back(Utils::PDF);
}
return ref new Platform::String(result.c_str());
}
String ^ StandardCalculatorViewModel::CalculateNarratorDisplayValue(_In_ wstring const& displayValue, _In_ String ^ localizedDisplayValue, _In_ bool isError)
{
String ^ localizedValue = localizedDisplayValue;
String ^ automationFormat = m_localizedCalculationResultAutomationFormat;
// The narrator doesn't read the decimalSeparator if it's the last character
if (Utils::IsLastCharacterTarget(displayValue, m_decimalSeparator))
{
// remove the decimal separator, to avoid a long pause between words
localizedValue = LocalizeDisplayValue(displayValue.substr(0, displayValue.length() - 1), isError);
// Use a format which has a word in the decimal separator's place
// "The Display is 10 point"
automationFormat = m_localizedCalculationResultDecimalAutomationFormat;
}
// In Programmer modes using non-base10, we want the strings to be read as literal digits.
if (IsProgrammer && CurrentRadixType != RADIX_TYPE::DEC_RADIX)
{
localizedValue = GetNarratorStringReadRawNumbers(localizedValue);
}
return GetLocalizedStringFormat(automationFormat, localizedValue);
}
String ^ StandardCalculatorViewModel::GetNarratorStringReadRawNumbers(_In_ String ^ localizedDisplayValue)
{
wstringstream wss;
auto& locSettings = LocalizationSettings::GetInstance();
// Insert a space after each digit in the string, to force Narrator to read them as separate numbers.
wstring wstrValue(localizedDisplayValue->Data());
for (wchar_t& c : wstrValue)
{
wss << c;
if (locSettings.IsLocalizedHexDigit(c))
{
wss << L' ';
}
}
return ref new String(wss.str().c_str());
}
void StandardCalculatorViewModel::SetPrimaryDisplay(_In_ String ^ displayStringValue, _In_ bool isError)
{
String ^ localizedDisplayStringValue = LocalizeDisplayValue(displayStringValue->Data(), isError);
// Set this variable before the DisplayValue is modified, Otherwise the DisplayValue will
// not match what the narrator is saying
m_CalculationResultAutomationName = CalculateNarratorDisplayValue(displayStringValue->Data(), localizedDisplayStringValue, isError);
AreAlwaysOnTopResultsUpdated = false;
if (DisplayValue != localizedDisplayStringValue)
{
DisplayValue = localizedDisplayStringValue;
AreAlwaysOnTopResultsUpdated = true;
}
IsInError = isError;
if (IsProgrammer)
{
UpdateProgrammerPanelDisplay();
}
}
void StandardCalculatorViewModel::DisplayPasteError()
{
m_standardCalculatorManager.DisplayPasteError();
}
void StandardCalculatorViewModel::SetParenthesisCount(_In_ unsigned int parenthesisCount)
{
if (m_OpenParenthesisCount == parenthesisCount)
{
return;
}
OpenParenthesisCount = parenthesisCount;
if (IsProgrammer || IsScientific)
{
SetOpenParenthesisCountNarratorAnnouncement();
}
}
void StandardCalculatorViewModel::SetOpenParenthesisCountNarratorAnnouncement()
{
wstring localizedParenthesisCount = to_wstring(m_OpenParenthesisCount).c_str();
LocalizationSettings::GetInstance().LocalizeDisplayValue(&localizedParenthesisCount);
if (m_localizedOpenParenthesisCountChangedAutomationFormat == nullptr)
{
m_localizedOpenParenthesisCountChangedAutomationFormat =
AppResourceProvider::GetInstance()->GetResourceString(CalculatorResourceKeys::OpenParenthesisCountAutomationFormat);
}
String ^ announcement =
LocalizationStringUtil::GetLocalizedString(m_localizedOpenParenthesisCountChangedAutomationFormat, StringReference(localizedParenthesisCount.c_str()));
Announcement = CalculatorAnnouncement::GetOpenParenthesisCountChangedAnnouncement(announcement);
}
void StandardCalculatorViewModel::OnNoRightParenAdded()
{
SetNoParenAddedNarratorAnnouncement();
}
void StandardCalculatorViewModel::SetNoParenAddedNarratorAnnouncement()
{
if (m_localizedNoRightParenthesisAddedFormat == nullptr)
{
m_localizedNoRightParenthesisAddedFormat =
AppResourceProvider::GetInstance()->GetResourceString(CalculatorResourceKeys::NoParenthesisAdded);
}
Announcement = CalculatorAnnouncement::GetNoRightParenthesisAddedAnnouncement(m_localizedNoRightParenthesisAddedFormat);
}
void StandardCalculatorViewModel::DisableButtons(CommandType selectedExpressionCommandType)
{
if (selectedExpressionCommandType == CommandType::OperandCommand)
{
IsBinaryOperatorEnabled = false;
IsUnaryOperatorEnabled = false;
IsOperandEnabled = true;
IsNegateEnabled = true;
IsDecimalEnabled = true;
}
if (selectedExpressionCommandType == CommandType::BinaryCommand)
{
IsBinaryOperatorEnabled = true;
IsUnaryOperatorEnabled = false;
IsOperandEnabled = false;
IsNegateEnabled = false;
IsDecimalEnabled = false;
}
if (selectedExpressionCommandType == CommandType::UnaryCommand)
{
IsBinaryOperatorEnabled = false;
IsUnaryOperatorEnabled = true;
IsOperandEnabled = false;
IsNegateEnabled = true;
IsDecimalEnabled = false;
}
}
void StandardCalculatorViewModel::SetExpressionDisplay(
_Inout_ shared_ptr<std::vector<pair<wstring, int>>> const& tokens,
_Inout_ shared_ptr<std::vector<shared_ptr<IExpressionCommand>>> const& commands)
{
m_tokens = tokens;
m_commands = commands;
if (!IsEditingEnabled)
{
SetTokens(tokens);
}
CalculationExpressionAutomationName = GetCalculatorExpressionAutomationName();
AreTokensUpdated = true;
}
void StandardCalculatorViewModel::SetHistoryExpressionDisplay(
_Inout_ shared_ptr<vector<pair<wstring, int>>> const& tokens,
_Inout_ shared_ptr<vector<shared_ptr<IExpressionCommand>>> const& commands)
{
m_tokens = make_shared<vector<pair<wstring, int>>>(*tokens);
m_commands = make_shared<vector<shared_ptr<IExpressionCommand>>>(*commands);
IsEditingEnabled = false;
// Setting the History Item Load Mode so that UI does not get updated with recalculation of every token
m_standardCalculatorManager.SetInHistoryItemLoadMode(true);
Recalculate(true);
m_standardCalculatorManager.SetInHistoryItemLoadMode(false);
m_isLastOperationHistoryLoad = true;
}
void StandardCalculatorViewModel::SetTokens(_Inout_ shared_ptr<vector<pair<wstring, int>>> const& tokens)
{
AreTokensUpdated = false;
const size_t nTokens = tokens->size();
if (nTokens == 0)
{
m_ExpressionTokens->Clear();
return;
}
const auto& localizer = LocalizationSettings::GetInstance();
const wstring separator = L" ";
for (unsigned int i = 0; i < nTokens; ++i)
{
auto currentToken = (*tokens)[i];
Common::TokenType type;
bool isEditable = currentToken.second != -1;
localizer.LocalizeDisplayValue(&(currentToken.first));
if (!isEditable)
{
type = currentToken.first == separator ? TokenType::Separator : TokenType::Operator;
}
else
{
const shared_ptr<IExpressionCommand>& command = m_commands->at(currentToken.second);
type = command->GetCommandType() == CommandType::OperandCommand ? TokenType::Operand : TokenType::Operator;
}
auto currentTokenString = StringReference(currentToken.first.c_str());
if (i < m_ExpressionTokens->Size)
{
auto existingItem = m_ExpressionTokens->GetAt(i);
if (type == existingItem->Type && existingItem->Token->Equals(currentTokenString))
{
existingItem->TokenPosition = i;
existingItem->IsTokenEditable = isEditable;
existingItem->CommandIndex = 0;
}
else
{
auto expressionToken = ref new DisplayExpressionToken(currentTokenString, i, isEditable, type);
m_ExpressionTokens->InsertAt(i, expressionToken);
}
}
else
{
auto expressionToken = ref new DisplayExpressionToken(currentTokenString, i, isEditable, type);
m_ExpressionTokens->Append(expressionToken);
}
}
while (m_ExpressionTokens->Size != nTokens)
{
m_ExpressionTokens->RemoveAtEnd();
}
}
String ^ StandardCalculatorViewModel::GetCalculatorExpressionAutomationName()
{
String ^ expression = L"";
for (auto&& token : m_ExpressionTokens)
{
expression += LocalizationService::GetNarratorReadableToken(token->Token);
}
return GetLocalizedStringFormat(m_expressionAutomationNameFormat, expression);
}
void StandardCalculatorViewModel::SetMemorizedNumbers(const vector<wstring>& newMemorizedNumbers)
{
const auto& localizer = LocalizationSettings::GetInstance();
if (newMemorizedNumbers.size() == 0) // Memory has been cleared
{
MemorizedNumbers->Clear();
IsMemoryEmpty = true;
}
// A new value is added to the memory
else if (newMemorizedNumbers.size() > MemorizedNumbers->Size)
{
while (newMemorizedNumbers.size() > MemorizedNumbers->Size)
{
size_t newValuePosition = newMemorizedNumbers.size() - MemorizedNumbers->Size - 1;
auto stringValue = newMemorizedNumbers.at(newValuePosition);
MemoryItemViewModel ^ memorySlot = ref new MemoryItemViewModel(this);
memorySlot->Position = 0;
localizer.LocalizeDisplayValue(&stringValue);
memorySlot->Value = Utils::LRO + ref new String(stringValue.c_str()) + Utils::PDF;
MemorizedNumbers->InsertAt(0, memorySlot);
IsMemoryEmpty = IsAlwaysOnTop;
// Update the slot position for the rest of the slots
for (unsigned int i = 1; i < MemorizedNumbers->Size; i++)
{
MemorizedNumbers->GetAt(i)->Position++;
}
}
}
else if (newMemorizedNumbers.size() == MemorizedNumbers->Size) // Either M+ or M-
{
for (unsigned int i = 0; i < MemorizedNumbers->Size; i++)
{
auto newStringValue = newMemorizedNumbers.at(i);
localizer.LocalizeDisplayValue(&newStringValue);
// If the value is different, update the value
if (MemorizedNumbers->GetAt(i)->Value != StringReference(newStringValue.c_str()))
{
MemorizedNumbers->GetAt(i)->Value = Utils::LRO + ref new String(newStringValue.c_str()) + Utils::PDF;
}
}
}
}
void StandardCalculatorViewModel::FtoEButtonToggled()
{
OnButtonPressed(NumbersAndOperatorsEnum::FToE);
}
void StandardCalculatorViewModel::HandleUpdatedOperandData(Command cmdenum)
{
DisplayExpressionToken ^ displayExpressionToken = ExpressionTokens->GetAt(m_tokenPosition);
if (displayExpressionToken == nullptr)
{
return;
}
if ((displayExpressionToken->Token == nullptr) || (displayExpressionToken->Token->Length() == 0))
{
displayExpressionToken->CommandIndex = 0;
}
wchar_t ch = 0;
if ((cmdenum >= Command::Command0) && (cmdenum <= Command::Command9))
{
switch (cmdenum)
{
case Command::Command0:
ch = L'0';
break;
case Command::Command1:
ch = L'1';
break;
case Command::Command2:
ch = L'2';
break;
case Command::Command3:
ch = L'3';
break;
case Command::Command4:
ch = L'4';
break;
case Command::Command5:
ch = L'5';
break;
case Command::Command6:
ch = L'6';
break;
case Command::Command7:
ch = L'7';
break;
case Command::Command8:
ch = L'8';
break;
case Command::Command9:
ch = L'9';
break;
}
}
else if (cmdenum == Command::CommandPNT)
{
ch = L'.';
}
else if (cmdenum == Command::CommandBACK)
{
ch = L'x';
}
else
{
return;
}
int length = 0;
wchar_t* temp = new wchar_t[100];
const wchar_t* data = m_selectedExpressionLastData->Data();
int i = 0, j = 0;
int commandIndex = displayExpressionToken->CommandIndex;
if (IsOperandTextCompletelySelected)
{
// Clear older text;
m_selectedExpressionLastData = L"";
if (ch == L'x')
{
temp[0] = L'\0';
commandIndex = 0;
}
else
{
temp[0] = ch;
temp[1] = L'\0';
commandIndex = 1;
}
IsOperandTextCompletelySelected = false;
}
else
{
if (ch == L'x')
{
if (commandIndex == 0)
{
delete[] temp;
return;
}
length = m_selectedExpressionLastData->Length();
for (; j < length; ++j)
{
if (j == commandIndex - 1)
{
continue;
}
temp[i++] = data[j];
}
temp[i] = L'\0';
commandIndex -= 1;
}
else
{
length = m_selectedExpressionLastData->Length() + 1;
if (length > 50)
{
delete[] temp;
return;
}
for (; i < length; ++i)
{
if (i == commandIndex)
{
temp[i] = ch;
continue;
}
temp[i] = data[j++];
}
temp[i] = L'\0';
commandIndex += 1;
}
}
String ^ updatedData = ref new String(temp);
UpdateOperand(m_tokenPosition, updatedData);
displayExpressionToken->Token = updatedData;
IsOperandUpdatedUsingViewModel = true;
displayExpressionToken->CommandIndex = commandIndex;
}
bool StandardCalculatorViewModel::IsOperator(Command cmdenum)
{
if ((cmdenum >= Command::Command0 && cmdenum <= Command::Command9) || (cmdenum == Command::CommandPNT) || (cmdenum == Command::CommandBACK)
|| (cmdenum == Command::CommandEXP) || (cmdenum == Command::CommandFE) || (cmdenum == Command::ModeBasic) || (cmdenum == Command::ModeProgrammer)
|| (cmdenum == Command::ModeScientific) || (cmdenum == Command::CommandINV) || (cmdenum == Command::CommandCENTR) || (cmdenum == Command::CommandDEG)
|| (cmdenum == Command::CommandRAD) || (cmdenum == Command::CommandGRAD)
|| ((cmdenum >= Command::CommandBINEDITSTART) && (cmdenum <= Command::CommandBINEDITEND)))
{
return false;
}
return true;
}
void StandardCalculatorViewModel::OnButtonPressed(Object ^ parameter)
{
m_feedbackForButtonPress = CalculatorButtonPressedEventArgs::GetAuditoryFeedbackFromCommandParameter(parameter);
NumbersAndOperatorsEnum numOpEnum = CalculatorButtonPressedEventArgs::GetOperationFromCommandParameter(parameter);
Command cmdenum = ConvertToOperatorsEnum(numOpEnum);
if (IsInError)
{
m_standardCalculatorManager.SendCommand(Command::CommandCLEAR);
if (!IsRecoverableCommand(static_cast<Command>(numOpEnum)))
{
return;
}
}
if (IsEditingEnabled && numOpEnum != NumbersAndOperatorsEnum::IsScientificMode && numOpEnum != NumbersAndOperatorsEnum::IsStandardMode
&& numOpEnum != NumbersAndOperatorsEnum::IsProgrammerMode && numOpEnum != NumbersAndOperatorsEnum::FToE
&& (numOpEnum != NumbersAndOperatorsEnum::Degree) && (numOpEnum != NumbersAndOperatorsEnum::Radians) && (numOpEnum != NumbersAndOperatorsEnum::Grads))
{
if (!m_keyPressed)
{
SaveEditedCommand(m_selectedExpressionToken->TokenPosition, cmdenum);
}
}
else
{
if (numOpEnum == NumbersAndOperatorsEnum::IsStandardMode || numOpEnum == NumbersAndOperatorsEnum::IsScientificMode
|| numOpEnum == NumbersAndOperatorsEnum::IsProgrammerMode)
{
IsEditingEnabled = false;
}
if (numOpEnum == NumbersAndOperatorsEnum::Memory)
{
OnMemoryButtonPressed();
}
else
{
if (numOpEnum == NumbersAndOperatorsEnum::Clear || numOpEnum == NumbersAndOperatorsEnum::ClearEntry
|| numOpEnum == NumbersAndOperatorsEnum::IsStandardMode || numOpEnum == NumbersAndOperatorsEnum::IsProgrammerMode)
{
// On Clear('C') the F-E button needs to be UnChecked if it in Checked state.
// Also, the Primary Display Value should not show in exponential format.
// Hence the check below to ensure parity with Desktop Calculator.
// Clear the FE mode if the switching to StandardMode, since 'C'/'CE' in StandardMode
// doesn't honor the FE button.
if (IsFToEChecked)
{
IsFToEChecked = false;
}
}
if (numOpEnum == NumbersAndOperatorsEnum::Degree || numOpEnum == NumbersAndOperatorsEnum::Radians || numOpEnum == NumbersAndOperatorsEnum::Grads)
{
m_CurrentAngleType = numOpEnum;
}
if ((cmdenum >= Command::Command0 && cmdenum <= Command::Command9) || (cmdenum == Command::CommandPNT) || (cmdenum == Command::CommandBACK)
|| (cmdenum == Command::CommandEXP))
{
IsOperatorCommand = false;
}
else
{
IsOperatorCommand = true;
}
if (m_isLastOperationHistoryLoad
&& ((numOpEnum != NumbersAndOperatorsEnum::Degree) && (numOpEnum != NumbersAndOperatorsEnum::Radians)
&& (numOpEnum != NumbersAndOperatorsEnum::Grads)))
{
IsFToEEnabled = true;
m_isLastOperationHistoryLoad = false;
}
TraceLogger::GetInstance()->UpdateButtonUsage(numOpEnum, GetCalculatorMode());
m_standardCalculatorManager.SendCommand(cmdenum);
}
}
}
int StandardCalculatorViewModel::GetNumberBase()
{
if (CurrentRadixType == HEX_RADIX)
{
return HexBase;
}
else if (CurrentRadixType == DEC_RADIX)
{
return DecBase;
}
else if (CurrentRadixType == OCT_RADIX)
{
return OctBase;
}
else
{
return BinBase;
}
}
void StandardCalculatorViewModel::OnCopyCommand(Object ^ parameter)
{
CopyPasteManager::CopyToClipboard(GetRawDisplayValue());
String ^ announcement = AppResourceProvider::GetInstance()->GetResourceString(CalculatorResourceKeys::DisplayCopied);
Announcement = CalculatorAnnouncement::GetDisplayCopiedAnnouncement(announcement);
}
void StandardCalculatorViewModel::OnPasteCommand(Object ^ parameter)
{
auto that(this);
ViewMode mode;
int NumberBase = -1;
BitLength bitLengthType = BitLength::BitLengthUnknown;
if (IsScientific)
{
mode = ViewMode::Scientific;
}
else if (IsProgrammer)
{
mode = ViewMode::Programmer;
NumberBase = GetNumberBase();
bitLengthType = m_valueBitLength;
}
else
{
mode = ViewMode::Standard;
}
// if there's nothing to copy early out
if (IsEditingEnabled || !CopyPasteManager::HasStringToPaste())
{
return;
}
// Ensure that the paste happens on the UI thread
create_task(CopyPasteManager::GetStringToPaste(mode, NavCategory::GetGroupType(mode), NumberBase, bitLengthType))
.then([that, mode](String ^ pastedString) { that->OnPaste(pastedString); }, concurrency::task_continuation_context::use_current());
}
CalculationManager::Command StandardCalculatorViewModel::ConvertToOperatorsEnum(NumbersAndOperatorsEnum operation)
{
return safe_cast<Command>(operation);
}
void StandardCalculatorViewModel::OnPaste(String ^ pastedString)
{
// If pastedString is invalid("NoOp") then display pasteError else process the string
if (CopyPasteManager::IsErrorMessage(pastedString))
{
this->DisplayPasteError();
return;
}
TraceLogger::GetInstance()->LogInputPasted(GetCalculatorMode());
bool isFirstLegalChar = true;
m_standardCalculatorManager.SendCommand(Command::CommandCENTR);
bool sendNegate = false;
bool processedDigit = false;
bool sentEquals = false;
bool isPreviousOperator = false;
vector<bool> negateStack;
// Iterate through each character pasted, and if it's valid, send it to the model.
auto it = pastedString->Begin();
while (it != pastedString->End())
{
bool sendCommand = true;
bool canSendNegate = false;
NumbersAndOperatorsEnum mappedNumOp = MapCharacterToButtonId(*it, canSendNegate);
if (mappedNumOp == NumbersAndOperatorsEnum::None)
{
++it;
continue;
}
if (isFirstLegalChar || isPreviousOperator)
{
isFirstLegalChar = false;
isPreviousOperator = false;
// If the character is a - sign, send negate
// after sending the next legal character. Send nothing now, or
// it will be ignored.
if (NumbersAndOperatorsEnum::Subtract == mappedNumOp)
{
sendNegate = true;
sendCommand = false;
}
// Support (+) sign prefix
if (NumbersAndOperatorsEnum::Add == mappedNumOp)
{
sendCommand = false;
}
}
switch (mappedNumOp)
{
// Opening parenthesis starts a new expression and pushes negation state onto the stack
case NumbersAndOperatorsEnum::OpenParenthesis:
negateStack.push_back(sendNegate);
sendNegate = false;
break;
// Closing parenthesis pops the negation state off the stack and sends it down to the calc engine
case NumbersAndOperatorsEnum::CloseParenthesis:
if (!negateStack.empty())
{
sendNegate = negateStack.back();
negateStack.pop_back();
canSendNegate = true;
}
else
{
// Don't send a closing parenthesis if a matching opening parenthesis hasn't been sent already
sendCommand = false;
}
break;
case NumbersAndOperatorsEnum::Zero:
case NumbersAndOperatorsEnum::One:
case NumbersAndOperatorsEnum::Two:
case NumbersAndOperatorsEnum::Three:
case NumbersAndOperatorsEnum::Four:
case NumbersAndOperatorsEnum::Five:
case NumbersAndOperatorsEnum::Six:
case NumbersAndOperatorsEnum::Seven:
case NumbersAndOperatorsEnum::Eight:
case NumbersAndOperatorsEnum::Nine:
processedDigit = true;
break;
case NumbersAndOperatorsEnum::Add:
case NumbersAndOperatorsEnum::Subtract:
case NumbersAndOperatorsEnum::Multiply:
case NumbersAndOperatorsEnum::Divide:
isPreviousOperator = true;
break;
}
if (sendCommand)
{
sentEquals = (mappedNumOp == NumbersAndOperatorsEnum::Equals);
Command cmdenum = ConvertToOperatorsEnum(mappedNumOp);
m_standardCalculatorManager.SendCommand(cmdenum);
// The CalcEngine state machine won't allow the negate command to be sent before any
// other digits, so instead a flag is set and the command is sent after the first appropriate
// command.
if (sendNegate)
{
if (canSendNegate)
{
Command cmdNegate = ConvertToOperatorsEnum(NumbersAndOperatorsEnum::Negate);
m_standardCalculatorManager.SendCommand(cmdNegate);
}
// Can't send negate on a leading zero, so wait until the appropriate time to send it.
if (NumbersAndOperatorsEnum::Zero != mappedNumOp && NumbersAndOperatorsEnum::Decimal != mappedNumOp)
{
sendNegate = false;
}
}
}
// Handle exponent and exponent sign (...e+... or ...e-... or ...e...)
if (mappedNumOp == NumbersAndOperatorsEnum::Exp)
{
// 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;
}
}
++it;
}
}
void StandardCalculatorViewModel::OnClearMemoryCommand(Object ^ parameter)
{
m_standardCalculatorManager.MemorizedNumberClearAll();
TraceLogger::GetInstance()->UpdateButtonUsage(NumbersAndOperatorsEnum::MemoryClear, GetCalculatorMode());
if (m_localizedMemoryCleared == nullptr)
{
m_localizedMemoryCleared = AppResourceProvider::GetInstance()->GetResourceString(CalculatorResourceKeys::MemoryCleared);
}
Announcement = CalculatorAnnouncement::GetMemoryClearedAnnouncement(m_localizedMemoryCleared);
}
void StandardCalculatorViewModel::OnPinUnpinCommand(Object ^ parameter)
{
SetViewPinnedState(!IsViewPinned());
}
bool StandardCalculatorViewModel::IsViewPinned()
{
return m_IsCurrentViewPinned;
}
void StandardCalculatorViewModel::SetViewPinnedState(bool pinned)
{
IsCurrentViewPinned = pinned;
}
NumbersAndOperatorsEnum StandardCalculatorViewModel::MapCharacterToButtonId(const wchar_t ch, bool& canSendNegate)
{
NumbersAndOperatorsEnum mappedValue = NumbersAndOperatorsEnum::None;
canSendNegate = false;
switch (ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
mappedValue = NumbersAndOperatorsEnum::Zero + static_cast<NumbersAndOperatorsEnum>(ch - L'0');
canSendNegate = true;
break;
case '*':
mappedValue = NumbersAndOperatorsEnum::Multiply;
break;
case '+':
mappedValue = NumbersAndOperatorsEnum::Add;
break;
case '-':
mappedValue = NumbersAndOperatorsEnum::Subtract;
break;
case '/':
mappedValue = NumbersAndOperatorsEnum::Divide;
break;
case '^':
if (IsScientific)
{
mappedValue = NumbersAndOperatorsEnum::XPowerY;
}
break;
case '%':
if (IsScientific || IsProgrammer)
{
mappedValue = NumbersAndOperatorsEnum::Mod;
}
break;
case '=':
mappedValue = NumbersAndOperatorsEnum::Equals;
break;
case '(':
mappedValue = NumbersAndOperatorsEnum::OpenParenthesis;
break;
case ')':
mappedValue = NumbersAndOperatorsEnum::CloseParenthesis;
break;
case 'a':
case 'A':
mappedValue = NumbersAndOperatorsEnum::A;
break;
case 'b':
case 'B':
mappedValue = NumbersAndOperatorsEnum::B;
break;
case 'c':
case 'C':
mappedValue = NumbersAndOperatorsEnum::C;
break;