forked from OutSystems/WebView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindowV1ViewModel.cs
419 lines (319 loc) · 13.3 KB
/
MainWindowV1ViewModel.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Threading.Tasks;
using ReactiveUI;
using WebViewControl;
namespace SampleWebView.Avalonia;
public class MainWindowV1ViewModel : ReactiveObject {
#region Fields
private readonly Dictionary<string, DownloadItemModel> downloads = new();
private readonly WebView webView;
private readonly ReactiveCommand<Unit, Unit> navigateCommand;
private readonly ReactiveCommand<Unit, Unit> showDevToolsCommand;
private readonly ReactiveCommand<Unit, Unit> cutCommand;
private readonly ReactiveCommand<Unit, Unit> copyCommand;
private readonly ReactiveCommand<Unit, Unit> pasteCommand;
private readonly ReactiveCommand<Unit, Unit> undoCommand;
private readonly ReactiveCommand<Unit, Unit> redoCommand;
private readonly ReactiveCommand<Unit, Unit> selectAllCommand;
private readonly ReactiveCommand<Unit, Unit> deleteCommand;
private readonly ReactiveCommand<Unit, Unit> backCommand;
private readonly ReactiveCommand<Unit, Unit> forwardCommand;
private readonly ReactiveCommand<Unit, Unit> getSourceCommand;
private readonly ReactiveCommand<Unit, Unit> getTextCommand;
private string address;
private string currentAddress;
private bool isDownloading;
private bool isDownloadDeterminate;
private double downloadPercentage;
private string downloadMessage;
private string downloadProgress;
private string source;
private bool sourceAvailable;
private string text;
private bool textAvailable;
#endregion Fields
public MainWindowV1ViewModel(WebView webview) {
Address = CurrentAddress = "http://www.google.com/";
//Address = CurrentAddress = "http://www.testfile.org/";
webView = webview;
webview.AllowDeveloperTools = true;
webview.Navigated += OnNavigated;
webview.DownloadCancelled += OnDownloadCancelled;
webview.DownloadCompleted += OnDownloadCompleted;
webview.DownloadProgressChanged += OnDownloadProgressChanged;
navigateCommand = ReactiveCommand.Create(() => {
CurrentAddress = Address;
});
showDevToolsCommand = ReactiveCommand.Create(webview.ShowDeveloperTools);
cutCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Cut();
});
copyCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Copy();
});
pasteCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Paste();
});
undoCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Undo();
});
redoCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Redo();
});
selectAllCommand = ReactiveCommand.Create(() => {
webview.EditCommands.SelectAll();
});
deleteCommand = ReactiveCommand.Create(() => {
webview.EditCommands.Delete();
});
backCommand = ReactiveCommand.Create(webview.GoBack);
forwardCommand = ReactiveCommand.Create(webview.GoForward);
getTextCommand = ReactiveCommand.Create(() => {
webview.GetText(OnTextAvailable);
});
getSourceCommand = ReactiveCommand.Create(() => {
webview.GetSource(OnSourceAvailable);
});
PropertyChanged += OnPropertyChanged;
}
public ReactiveCommand<Unit, Unit> NavigateCommand => navigateCommand;
public ReactiveCommand<Unit, Unit> ShowDevToolsCommand => showDevToolsCommand;
public ReactiveCommand<Unit, Unit> CutCommand => cutCommand;
public ReactiveCommand<Unit, Unit> CopyCommand => copyCommand;
public ReactiveCommand<Unit, Unit> PasteCommand => pasteCommand;
public ReactiveCommand<Unit, Unit> UndoCommand => undoCommand;
public ReactiveCommand<Unit, Unit> RedoCommand => redoCommand;
public ReactiveCommand<Unit, Unit> SelectAllCommand => selectAllCommand;
public ReactiveCommand<Unit, Unit> DeleteCommand => deleteCommand;
public ReactiveCommand<Unit, Unit> BackCommand => backCommand;
public ReactiveCommand<Unit, Unit> ForwardCommand => forwardCommand;
public ReactiveCommand<Unit, Unit> GetSourceCommand => getSourceCommand;
public ReactiveCommand<Unit, Unit> GetTextCommand => getTextCommand;
public string Address {
get => address;
set => this.RaiseAndSetIfChanged(ref address, value);
}
public string CurrentAddress {
get => currentAddress;
set => this.RaiseAndSetIfChanged(ref currentAddress, value);
}
public bool IsDownloading {
get => isDownloading;
set => this.RaiseAndSetIfChanged(ref isDownloading, value);
}
public bool IsDownloadDeterminate {
get => isDownloadDeterminate;
set => this.RaiseAndSetIfChanged(ref isDownloadDeterminate, value);
}
public double DownloadPercentage {
get => downloadPercentage;
set => this.RaiseAndSetIfChanged(ref downloadPercentage, value);
}
public string DownloadMessage {
get => downloadMessage;
set => this.RaiseAndSetIfChanged(ref downloadMessage, value);
}
public string DownloadProgress {
get => downloadProgress;
set => this.RaiseAndSetIfChanged(ref downloadProgress, value);
}
public string Source {
get => source;
set => this.RaiseAndSetIfChanged(ref source, value);
}
public bool SourceAvailable {
get => sourceAvailable;
set => this.RaiseAndSetIfChanged(ref sourceAvailable, value);
}
public string Text {
get => text;
set => this.RaiseAndSetIfChanged(ref text, value);
}
public bool TextAvailable {
get => textAvailable;
set => this.RaiseAndSetIfChanged(ref textAvailable, value);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(CurrentAddress)) {
Address = CurrentAddress;
}
}
private void OnNavigated(string url, string frameName) {
if (!string.IsNullOrWhiteSpace(frameName)) {
return;
}
Text = "";
TextAvailable = false;
webView.GetText(OnTextAvailable);
Source = "";
SourceAvailable = false;
}
private void OnSourceAvailable(string str) {
Source = str;
SourceAvailable = true;
}
private void OnTextAvailable(string str) {
Text = str;
TextAvailable = true;
}
#region Download V1 Event Implementation
private void OnDownloadProgressChanged(string resourcePath, long receivedBytes, long totalBytes) {
// Tracking multiple file downloads at once is potentially wonky due to not being given the downloadItem.Id
// Download Started
if (receivedBytes == 0) {
// Since the File Dialog is Modal we know that there can only ever be one downloadItem = "" at a time
downloads.Add("", new DownloadItemModel("", receivedBytes, totalBytes));
}
// Progress Changed
DownloadItemModel downloadItem;//= new DownloadItem(resourcePath, receivedBytes, totalBytes);
// The download proceeds in the background while waiting for the resourcePath from the user
if (!string.IsNullOrWhiteSpace(resourcePath)) {
// Try to get the downloadItem by resourcePath
if (!downloads.TryGetValue(resourcePath, out downloadItem)) {
// Not found, so get the downloadItem = ""
if (downloads.TryGetValue("", out downloadItem)) {
// Now we need to first remove it from the collection as "", then put it back in the collection as resourcePath
downloads.Remove("");
downloadItem.FullPath = resourcePath;
downloads.Add(resourcePath, downloadItem);
}
}
} else {
// Get the downloadItem = ""
downloads.TryGetValue("", out downloadItem);
}
// Now update the downloadItem...
downloadItem?.Update(resourcePath, receivedBytes, totalBytes);
UpdateDownloadPanel();
// Download Completed
if (receivedBytes == totalBytes && !string.IsNullOrWhiteSpace(resourcePath)) {
// We have to stop tracking here because the resourcePath could change between now and the DownloadCompleted firing
// the PropertyChanged Event will fire two more time after this???, so rather than remove it now we flag it for removal by the Completed Event
downloadItem?.SetCompleted();
}
//Debug.WriteLine($"{nameof(OnDownloadProgressChanged)}( count: {downloads.Count}, downloadItem: ( fullPath: {downloadItem.FullPath}, receivedBytes: {downloadItem.ReceivedBytes}, totalBytes {downloadItem.TotalBytes}, percentage {downloadItem.PercentComplete}, isCompleted {downloadItem.IsCompleted} ))");
}
private void OnDownloadCompleted(string resourcePath) {
// Here the resourcePath may be different from the resourcePath passed to PropertyChanged
// Remove the Completed DownloadItems
var completed = downloads.Values
.Where(x => x.IsCompleted)
.ToList();
if (completed.Count == 1) {
var downloadItem = completed[0];
downloadItem.Update(resourcePath);
downloads.Remove(downloadItem.FullPath);
completed.Add(downloadItem);
}
foreach (var item in completed) {
downloads.Remove(item.FullPath);
}
DownloadMessage = $"Download Completed: {Path.GetFileName(resourcePath)}";
DownloadPercentage = 100.0;
IsDownloadDeterminate = true;
CloseDownloadPanel();
}
private void OnDownloadCancelled(string resourcePath) {
// Here the resourcePath probably will be null
DownloadItemModel downloadItem;
if (string.IsNullOrWhiteSpace(resourcePath)) {
downloads.Remove("", out downloadItem);
} else {
downloads.Remove(resourcePath, out downloadItem);
}
downloadItem?.SetCancelled(resourcePath);
DownloadMessage = "Download Cancelled";
IsDownloadDeterminate = false;
CloseDownloadPanel();
}
private void CloseDownloadPanel() {
Debug.WriteLine($"{nameof(CloseDownloadPanel)}: ({downloads.Count})");
if (downloads.Count != 0) {
return;
}
Task.Delay(2000)
.ContinueWith(t => {
if (downloads.Count != 0) {
return;
}
IsDownloading = false;
});
}
private void UpdateDownloadPanel() {
var downloadItem = downloads.Values
.OrderByDescending(x => x.PercentComplete)
.First();
IsDownloading = true;
IsDownloadDeterminate = true;
DownloadPercentage = downloadItem.PercentComplete;
DownloadMessage = $"Downloading: {downloadItem.FullPath}";
var estimated = downloadItem.CurrentSpeed == 0 ?
"Unknown" : downloadItem.RemainingBytes == 0 ?
"None" :
$"{downloadItem.EstimatedTimeRemaining} sec.";
DownloadProgress = $"{downloadItem.ReceivedBytes}/{downloadItem.TotalBytes} bytes, Time Remaining: {estimated}";
}
private class DownloadItemModel(string fullPath, long receivedBytes, long totalBytes) {
private readonly Stopwatch elapsedTime = Stopwatch.StartNew();
public string FullPath { get; set; } = fullPath;
public string FileName {
get {
return Path.GetFileName(FullPath);
}
}
public long ReceivedBytes { get; set; } = receivedBytes;
public long TotalBytes { get; set; } = totalBytes;
public double PercentComplete {
get {
return (double)ReceivedBytes / TotalBytes * 100.0;
}
}
public long RemainingBytes {
get {
return TotalBytes - ReceivedBytes;
}
}
public long CurrentSpeed {
get {
return (ReceivedBytes / elapsedTime.Elapsed.Seconds);
}
} // BytesPerSecond
public long EstimatedTimeRemaining {
get;
set;
} // Seconds
public string StoppedReason { get; set; }
public bool IsCompleted { get; set; }
public void Update(string fullPath, long receivedBytes, long totalBytes) {
FullPath = fullPath;
ReceivedBytes = receivedBytes;
TotalBytes = totalBytes;
if (RemainingBytes == 0) {
elapsedTime.Stop();
}
if (CurrentSpeed > 0) {
EstimatedTimeRemaining = (long)((double)RemainingBytes / CurrentSpeed);
}
}
public void Update(string fullPath) {
FullPath = fullPath;
}
public void SetCompleted() {
elapsedTime.Stop();
IsCompleted = true;
}
public void SetCancelled(string fullPath) {
elapsedTime.Stop();
FullPath = fullPath;
StoppedReason = "UserCancelled";
ReceivedBytes = 0;
}
}
#endregion Download V1 Event Implementation
}