-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
MainViewModel.cs
378 lines (312 loc) · 11.4 KB
/
MainViewModel.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
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Common.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.UI;
using Hosts.Helpers;
using Hosts.Models;
using Hosts.Settings;
using ManagedCommon;
using Microsoft.UI.Dispatching;
namespace Hosts.ViewModels
{
public partial class MainViewModel : ObservableObject, IDisposable
{
private readonly IHostsService _hostsService;
private readonly IUserSettings _userSettings;
private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
private readonly string[] _loopbackAddresses =
{
"127.0.0.1",
"::1",
"0:0:0:0:0:0:0:1",
};
private bool _readingHosts;
private bool _disposed;
private CancellationTokenSource _tokenSource;
[ObservableProperty]
private Entry _selected;
[ObservableProperty]
private bool _error;
[ObservableProperty]
private bool _fileChanged;
[ObservableProperty]
private string _addressFilter;
[ObservableProperty]
private string _hostsFilter;
[ObservableProperty]
private string _commentFilter;
[ObservableProperty]
private string _additionalLines;
[ObservableProperty]
private bool _isLoading;
[ObservableProperty]
private bool _filtered;
private bool _showOnlyDuplicates;
public bool ShowOnlyDuplicates
{
get => _showOnlyDuplicates;
set
{
SetProperty(ref _showOnlyDuplicates, value);
ApplyFilters();
}
}
private ObservableCollection<Entry> _entries;
public AdvancedCollectionView Entries { get; set; }
public int NextId => _entries.Max(e => e.Id) + 1;
public MainViewModel(IHostsService hostService, IUserSettings userSettings)
{
_hostsService = hostService;
_userSettings = userSettings;
_hostsService.FileChanged += (s, e) => _dispatcherQueue.TryEnqueue(() => FileChanged = true);
_userSettings.LoopbackDuplicatesChanged += (s, e) => ReadHosts();
}
public void Add(Entry entry)
{
entry.PropertyChanged += Entry_PropertyChanged;
_entries.Add(entry);
FindDuplicates(entry.Address, entry.SplittedHosts);
}
public void Update(int index, Entry entry)
{
var existingEntry = Entries[index] as Entry;
var oldAddress = existingEntry.Address;
var oldHosts = existingEntry.SplittedHosts;
existingEntry.Address = entry.Address;
existingEntry.Comment = entry.Comment;
existingEntry.Hosts = entry.Hosts;
existingEntry.Active = entry.Active;
FindDuplicates(oldAddress, oldHosts);
FindDuplicates(entry.Address, entry.SplittedHosts);
}
public void DeleteSelected()
{
var address = Selected.Address;
var hosts = Selected.SplittedHosts;
_entries.Remove(Selected);
FindDuplicates(address, hosts);
}
public void UpdateAdditionalLines(string lines)
{
_additionalLines = lines;
Task.Run(async () =>
{
var error = !await _hostsService.WriteAsync(_additionalLines, _entries);
await _dispatcherQueue.EnqueueAsync(() => Error = error);
});
}
public void Move(int oldIndex, int newIndex)
{
if (Filtered)
{
return;
}
// Swap the IDs
var entry1 = _entries[oldIndex];
var entry2 = _entries[newIndex];
(entry2.Id, entry1.Id) = (entry1.Id, entry2.Id);
// Move entries in the UI
_entries.Move(oldIndex, newIndex);
}
[RelayCommand]
public void ReadHosts()
{
if (_readingHosts)
{
return;
}
_dispatcherQueue.TryEnqueue(() =>
{
FileChanged = false;
IsLoading = true;
});
Task.Run(async () =>
{
_readingHosts = true;
(_additionalLines, var entries) = await _hostsService.ReadAsync();
await _dispatcherQueue.EnqueueAsync(() =>
{
_entries = new ObservableCollection<Entry>(entries);
foreach (var e in _entries)
{
e.PropertyChanged += Entry_PropertyChanged;
}
_entries.CollectionChanged += Entries_CollectionChanged;
Entries = new AdvancedCollectionView(_entries, true);
Entries.SortDescriptions.Add(new SortDescription(nameof(Entry.Id), SortDirection.Ascending));
ApplyFilters();
OnPropertyChanged(nameof(Entries));
IsLoading = false;
});
_readingHosts = false;
_tokenSource?.Cancel();
_tokenSource = new CancellationTokenSource();
FindDuplicates(_tokenSource.Token);
});
}
[RelayCommand]
public void ApplyFilters()
{
var expressions = new List<Expression<Func<object, bool>>>(4);
if (!string.IsNullOrWhiteSpace(_addressFilter))
{
expressions.Add(e => ((Entry)e).Address.Contains(_addressFilter, StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrWhiteSpace(_hostsFilter))
{
expressions.Add(e => ((Entry)e).Hosts.Contains(_hostsFilter, StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrWhiteSpace(_commentFilter))
{
expressions.Add(e => ((Entry)e).Comment.Contains(_commentFilter, StringComparison.OrdinalIgnoreCase));
}
if (_showOnlyDuplicates)
{
expressions.Add(e => ((Entry)e).Duplicate);
}
Expression<Func<object, bool>> filterExpression = null;
foreach (var e in expressions)
{
filterExpression = filterExpression == null ? e : filterExpression.And(e);
}
Filtered = filterExpression != null;
Entries.Filter = Filtered ? filterExpression.Compile().Invoke : null;
Entries.RefreshFilter();
}
[RelayCommand]
public void ClearFilters()
{
AddressFilter = null;
HostsFilter = null;
CommentFilter = null;
ShowOnlyDuplicates = false;
Entries.Filter = null;
Entries.RefreshFilter();
}
public async Task PingSelectedAsync()
{
var selected = _selected;
selected.Ping = null;
selected.Pinging = true;
selected.Ping = await _hostsService.PingAsync(_selected.Address);
selected.Pinging = false;
}
[RelayCommand]
public void OpenSettings()
{
SettingsDeepLink.OpenSettings(SettingsDeepLink.SettingsWindow.Hosts);
}
[RelayCommand]
public void OpenHostsFile()
{
_hostsService.OpenHostsFile();
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private void Entry_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (Filtered && (e.PropertyName == nameof(Entry.Hosts)
|| e.PropertyName == nameof(Entry.Address)
|| e.PropertyName == nameof(Entry.Comment)
|| e.PropertyName == nameof(Entry.Duplicate)))
{
Entries.RefreshFilter();
}
// Ping and duplicate should't trigger a file save
if (e.PropertyName == nameof(Entry.Ping)
|| e.PropertyName == nameof(Entry.Pinging)
|| e.PropertyName == nameof(Entry.Duplicate))
{
return;
}
Task.Run(async () =>
{
var error = !await _hostsService.WriteAsync(_additionalLines, _entries);
await _dispatcherQueue.EnqueueAsync(() => Error = error);
});
}
private void Entries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Task.Run(async () =>
{
var error = !await _hostsService.WriteAsync(_additionalLines, _entries);
await _dispatcherQueue.EnqueueAsync(() => Error = error);
});
}
private void FindDuplicates(CancellationToken cancellationToken)
{
foreach (var entry in _entries)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
if (!_userSettings.LoopbackDuplicates && _loopbackAddresses.Contains(entry.Address))
{
continue;
}
SetDuplicate(entry);
}
catch (OperationCanceledException)
{
Logger.LogInfo("FindDuplicates cancelled");
return;
}
}
}
private void FindDuplicates(string address, IEnumerable<string> hosts)
{
var entries = _entries.Where(e =>
string.Equals(e.Address, address, StringComparison.OrdinalIgnoreCase)
|| hosts.Intersect(e.SplittedHosts, StringComparer.OrdinalIgnoreCase).Any());
foreach (var entry in entries)
{
SetDuplicate(entry);
}
}
private void SetDuplicate(Entry entry)
{
if (!_userSettings.LoopbackDuplicates && _loopbackAddresses.Contains(entry.Address))
{
_dispatcherQueue.TryEnqueue(() =>
{
entry.Duplicate = false;
});
return;
}
var hosts = entry.SplittedHosts;
var duplicate = _entries.FirstOrDefault(e => e != entry
&& e.Type == entry.Type
&& (string.Equals(e.Address, entry.Address, StringComparison.OrdinalIgnoreCase)
|| hosts.Intersect(e.SplittedHosts, StringComparer.OrdinalIgnoreCase).Any())) != null;
_dispatcherQueue.TryEnqueue(() =>
{
entry.Duplicate = duplicate;
});
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_hostsService?.Dispose();
_disposed = true;
}
}
}
}
}