forked from microsoft/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHistoryViewModel.cpp
372 lines (319 loc) · 13.1 KB
/
HistoryViewModel.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "HistoryViewModel.h"
#include "Common/TraceLogger.h"
#include "Common/LocalizationStringUtil.h"
#include "Common/LocalizationSettings.h"
using namespace CalculatorApp;
using namespace CalculatorApp::Common;
using namespace CalculatorApp::Common::Automation;
using namespace CalculatorApp::ViewModel;
using namespace Platform;
using namespace std;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Security::Cryptography;
using namespace Windows::Foundation::Collections;
static StringReference HistoryVectorLengthKey{ L"HistoryVectorLength" };
namespace CalculatorApp::ViewModel::HistoryResourceKeys
{
StringReference HistoryCleared(L"HistoryList_Cleared");
}
HistoryViewModel::HistoryViewModel(_In_ CalculationManager::CalculatorManager* calculatorManager) :
m_calculatorManager(calculatorManager),
m_localizedHistoryCleared(nullptr)
{
AreHistoryShortcutsEnabled = true;
Items = ref new Platform::Collections::Vector<HistoryItemViewModel^>();
ItemSize = 0;
}
void HistoryViewModel::RestoreCompleteHistory()
{
RestoreHistory(CalculationManager::CALCULATOR_MODE::CM_STD);
RestoreHistory(CalculationManager::CALCULATOR_MODE::CM_SCI);
}
// this will reload Items with the history list based on current mode
void HistoryViewModel::ReloadHistory(_In_ ViewMode currentMode)
{
if (currentMode == ViewMode::Standard)
{
m_currentMode = CalculationManager::CALCULATOR_MODE::CM_STD;
}
else if (currentMode == ViewMode::Scientific)
{
m_currentMode = CalculationManager::CALCULATOR_MODE::CM_SCI;
}
else
{
return;
}
auto historyListModel = m_calculatorManager->GetHistoryItems(m_currentMode);
auto historyListVM = ref new Platform::Collections::Vector<HistoryItemViewModel^>();
const auto& localizer = LocalizationSettings::GetInstance();
if (historyListModel.size() > 0)
{
for (auto ritr = historyListModel.rbegin(); ritr != historyListModel.rend(); ++ritr)
{
wstring expression = (*ritr)->historyItemVector.expression;
wstring result = (*ritr)->historyItemVector.result;
localizer.LocalizeDisplayValue(&expression);
localizer.LocalizeDisplayValue(&result);
auto item = ref new HistoryItemViewModel(ref new Platform::String( expression.c_str()),
ref new Platform::String(result.c_str()),
(*ritr)->historyItemVector.spTokens, (*ritr)->historyItemVector.spCommands);
historyListVM->Append(item);
}
}
Items = historyListVM;
UpdateItemSize();
}
void HistoryViewModel::OnHistoryItemAdded(_In_ unsigned int addedItemIndex)
{
auto newItem = m_calculatorManager->GetHistoryItem(addedItemIndex);
const auto& localizer = LocalizationSettings::GetInstance();
wstring expression = newItem->historyItemVector.expression;
wstring result = newItem->historyItemVector.result;
localizer.LocalizeDisplayValue(&expression);
localizer.LocalizeDisplayValue(&result);
auto item = ref new HistoryItemViewModel(ref new Platform::String(expression.c_str()),
ref new Platform::String(result.c_str()),
newItem->historyItemVector.spTokens, newItem->historyItemVector.spCommands );
// check if we have not hit the max items
if (Items->Size >= m_calculatorManager->MaxHistorySize())
{
// this means the item already exists
Items->RemoveAt(Items->Size -1);
}
assert(addedItemIndex <= m_calculatorManager->MaxHistorySize() && addedItemIndex >= 0);
Items->InsertAt(0, item);
UpdateItemSize();
SaveHistory();
}
void HistoryViewModel::SetCalculatorDisplay(CalculatorDisplay &calculatorDisplay)
{
WeakReference historyViewModel(this);
calculatorDisplay.SetHistoryCallback(historyViewModel);
}
void HistoryViewModel::ShowItem(_In_ HistoryItemViewModel^ e)
{
HistoryItemClicked(e);
}
void HistoryViewModel::DeleteItem(_In_ HistoryItemViewModel^ e)
{
uint32_t itemIndex;
if (Items->IndexOf(e, &itemIndex))
{
if (m_calculatorManager->RemoveHistoryItem(itemIndex))
{
// Keys for the history container are index based.
// SaveHistory() re-inserts the items anyway, so it's faster to just clear out the container.
CalculationManager::CALCULATOR_MODE currentMode = m_currentMode;
ApplicationDataContainer^ historyContainer = GetHistoryContainer(currentMode);
historyContainer->Values->Clear();
Items->RemoveAt(itemIndex);
UpdateItemSize();
SaveHistory();
}
}
}
void HistoryViewModel::OnHideCommand(_In_ Platform::Object^ e)
{
// added at VM layer so that the views do not have to individually raise events
HideHistoryClicked();
}
void HistoryViewModel::OnClearCommand(_In_ Platform::Object^ e)
{
TraceLogger::GetInstance().LogClearHistory();
if (AreHistoryShortcutsEnabled == true)
{
m_calculatorManager->ClearHistory();
if (Items->Size > 0)
{
CalculationManager::CALCULATOR_MODE currentMode = m_currentMode;
ClearHistoryContainer(currentMode);
Items->Clear();
UpdateItemSize();
}
MakeHistoryClearedNarratorAnnouncement(HistoryResourceKeys::HistoryCleared, m_localizedHistoryCleared);
}
}
// this method restores history vector per mode
void HistoryViewModel::RestoreHistory(_In_ CalculationManager::CALCULATOR_MODE cMode)
{
ApplicationDataContainer^ historyContainer = GetHistoryContainer(cMode);
std::shared_ptr<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>> historyVector = std::make_shared<std::vector<std::shared_ptr<CalculationManager::HISTORYITEM>>>();
auto historyVectorLength = static_cast<int>(historyContainer->Values->Lookup(HistoryVectorLengthKey));
bool failure = false;
if (historyVectorLength > 0)
{
for (int i = 0; i < historyVectorLength; ++i)
{
try
{
// deserialize each item
auto item = DeserializeHistoryItem(i.ToString(), historyContainer);
std::shared_ptr<CalculationManager::HISTORYITEM> Item = std::make_shared<CalculationManager::HISTORYITEM>(item);
historyVector->push_back(Item);
}
catch (Platform::Exception^ e)
{
failure = true;
break;
}
}
if (!failure)
{
// if task has been cancelled set history to 0
m_calculatorManager->SetHistory(cMode, *historyVector);
// update length once again for consistency between stored number of items and length
UpdateHistoryVectorLength(static_cast<int>(historyVector->size()), cMode);
}
else
{
// in case of failure do not show any item
UpdateHistoryVectorLength(0, cMode);
}
}
}
Platform::String^ HistoryViewModel::GetHistoryContainerKey(_In_ CalculationManager::CALCULATOR_MODE cMode)
{
Platform::ValueType^ modeValue = static_cast<int>(cMode);
return Platform::String::Concat(modeValue->ToString(), L"_History");
}
ApplicationDataContainer^ HistoryViewModel::GetHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode)
{
ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
ApplicationDataContainer^ historyContainer;
// naming container based on mode
Platform::String^ historyContainerKey = GetHistoryContainerKey(cMode);
if (localSettings->Containers->HasKey(historyContainerKey))
{
historyContainer = localSettings->Containers->Lookup(historyContainerKey);
}
else
{
// create container for adding data
historyContainer = localSettings->CreateContainer(historyContainerKey, ApplicationDataCreateDisposition::Always);
int initialHistoryVectorLength = 0;
historyContainer->Values->Insert(HistoryVectorLengthKey, initialHistoryVectorLength);
}
return historyContainer;
}
void HistoryViewModel::ClearHistoryContainer(_In_ CalculationManager::CALCULATOR_MODE cMode)
{
ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
localSettings->DeleteContainer(GetHistoryContainerKey(cMode));
}
// this method will be used to update the history item length
void HistoryViewModel::UpdateHistoryVectorLength(_In_ int newValue, _In_ CalculationManager::CALCULATOR_MODE cMode)
{
ApplicationDataContainer^ historyContainer = GetHistoryContainer(cMode);
historyContainer->Values->Remove(HistoryVectorLengthKey);
historyContainer->Values->Insert(HistoryVectorLengthKey, newValue);
}
void HistoryViewModel::ClearHistory()
{
ClearHistoryContainer(CalculationManager::CALCULATOR_MODE::CM_STD);
ClearHistoryContainer(CalculationManager::CALCULATOR_MODE::CM_SCI);
}
void HistoryViewModel::SaveHistory()
{
ApplicationDataContainer^ historyContainer = GetHistoryContainer(m_currentMode);
auto currentHistoryVector = m_calculatorManager->GetHistoryItems(m_currentMode);
bool failure = false;
int index = 0;
Platform::String^ serializedHistoryItem;
for (auto iter = currentHistoryVector.begin(); iter != currentHistoryVector.end(); ++iter)
{
try
{
serializedHistoryItem = SerializeHistoryItem(*iter);
historyContainer->Values->Insert(index.ToString(), serializedHistoryItem);
}
catch (Platform::Exception^)
{
failure = true;
break;
}
++index;
}
if (!failure)
{
// insertion is successful
UpdateHistoryVectorLength(static_cast<int>(currentHistoryVector.size()), m_currentMode);
}
else
{
UpdateHistoryVectorLength(0, m_currentMode);
}
}
// this serializes a history item into a base64 encoded string
Platform::String^ HistoryViewModel::SerializeHistoryItem(_In_ std::shared_ptr<CalculationManager::HISTORYITEM> const &item)
{
DataWriter^ writer = ref new DataWriter();
auto expr = item->historyItemVector.expression;
auto result = item->historyItemVector.result;
auto platformExpr = ref new Platform::String(expr.c_str());
writer->WriteUInt32(writer->MeasureString(platformExpr));
writer->WriteString(platformExpr);
auto platformResult = ref new Platform::String(result.c_str());
writer->WriteUInt32(writer->MeasureString(platformResult));
writer->WriteString(platformResult);
Utils::SerializeCommandsAndTokens(item->historyItemVector.spTokens, item->historyItemVector.spCommands, writer);
IBuffer^ buffer = writer->DetachBuffer();
if (buffer == nullptr)
{
throw ref new Platform::Exception(E_POINTER, ref new Platform::String(L"History Item is NULL"));
}
return CryptographicBuffer::EncodeToBase64String(buffer);
}
CalculationManager::HISTORYITEM HistoryViewModel::DeserializeHistoryItem(_In_ Platform::String^ historyItemKey, _In_ ApplicationDataContainer^ historyContainer)
{
CalculationManager::HISTORYITEM historyItem;
if (historyContainer->Values->HasKey(historyItemKey))
{
Object^ historyItemValues = historyContainer->Values->Lookup(historyItemKey);
if (historyItemValues == nullptr)
{
throw ref new Platform::Exception(E_POINTER, ref new Platform::String(L"History Item is NULL"));
}
String^ historyData = safe_cast<Platform::String^>(historyItemValues);
IBuffer^ buffer = CryptographicBuffer::DecodeFromBase64String(historyData);
if (buffer == nullptr)
{
throw ref new Platform::Exception(E_POINTER, ref new Platform::String(L"History Item is NULL"));
}
DataReader^ reader = DataReader::FromBuffer(buffer);
auto exprLen = reader->ReadUInt32();
auto expression = reader->ReadString(exprLen);
historyItem.historyItemVector.expression = expression->Data();
auto resultLen = reader->ReadUInt32();
auto result = reader->ReadString(resultLen);
historyItem.historyItemVector.result = result->Data();
historyItem.historyItemVector.spCommands = Utils::DeserializeCommands(reader);
historyItem.historyItemVector.spTokens = Utils::DeserializeTokens(reader);
}
else
{
throw ref new Platform::Exception(E_ACCESSDENIED, ref new Platform::String(L"History Item not found"));
}
return historyItem;
}
bool HistoryViewModel::IsValid(_In_ CalculationManager::HISTORYITEM item)
{
return (!item.historyItemVector.expression.empty() &&
!item.historyItemVector.result.empty() &&
(bool)item.historyItemVector.spCommands &&
(bool)item.historyItemVector.spTokens);
}
void HistoryViewModel::UpdateItemSize()
{
ItemSize = Items->Size;
}
void HistoryViewModel::MakeHistoryClearedNarratorAnnouncement(String^ resourceKey, String^& formatVariable)
{
String^ announcement = LocalizationStringUtil::GetLocalizedNarratorAnnouncement(resourceKey, formatVariable);
HistoryAnnouncement = CalculatorAnnouncement::GetHistoryClearedAnnouncement(announcement);
}