-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
406 lines (342 loc) · 18.3 KB
/
MainForm.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
using Aga.Controls.Tree;
using Squirrel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using VigilantCupcake.ExtensionMethods;
using VigilantCupcake.Models;
using VigilantCupcake.OperatingSystemUtilities;
using VigilantCupcake.SubForms;
using VigilantCupcake.ViewExtensions;
namespace VigilantCupcake {
public partial class MainForm : Form {
AboutBox _aboutBox = new AboutBox();
readonly ActualHostsFile _currentHostsForm = new ActualHostsFile();
HostfileRecordCombiner _hostfileRecordCombiner = new HostfileRecordCombiner();
Fragment _newHostsFile = new Fragment() { IsHostsFile = true };
bool _reallyClose = false;
Fragment _selectedFragment = null;
Label loadingLabel = new Label() {
AutoSize = false,
TextAlign = ContentAlignment.MiddleCenter,
Dock = DockStyle.Fill,
Font = new Font("Segoe UI", 36F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))),
Text = "Loading..."
};
public MainForm() {
InitializeComponent();
components.Add(loadingLabel);
loadUserSettings();
currentFragmentView.TextChanged += FastColoredTextBoxUtility.FastColoredTextBoxTextChanged;
hostsFileView.TextChanged += FastColoredTextBoxUtility.FastColoredTextBoxTextChanged;
enabledToolStripMenuItem_CheckedChanged(null, null);
fragmentTreeView.SelectionChanged += triStateTreeView1_SelectionChanged;
_newHostsFile.PropertyChanged += fragmentPropertyChanged;
fragmentTreeView.Model.NodesInserted += Model_NodesInserted;
}
protected override void WndProc(ref Message m) {
if (m.Msg == SingleInstance.WM_SHOWFIRSTINSTANCE) {
ShowWindow();
}
base.WndProc(ref m);
}
void aboutToolStripMenuItem_Click(object sender, EventArgs e) => _aboutBox.ShowDialog();
private void allowInvalidCertToolStripMenuItem_CheckedChanged(object sender, EventArgs e) {
UserConfig.Instance.AllowInvalidCertificates = allowInvalidCertToolStripMenuItem.Checked;
updateHostsFileView();
updateCurrentFragmentView();
}
void backgroundDownloadTimer_Tick(object sender, EventArgs e) {
fragmentTreeView.Model.Fragments.AsParallel().ForAll(y => y.DownloadFile());
saveAll();
}
void closeToTrayToolStripMenuItem_CheckedChanged(object sender, EventArgs e) => UserConfig.Instance.CloseToTray = closeToTrayToolStripMenuItem.Checked;
void enabledToolStripMenuItem_CheckedChanged(object sender, EventArgs e) {
UserConfig.Instance.DownloadInBackground = syncEnabledToolStripMenuItem.Checked;
backgroundDownloadTimer.Enabled = UserConfig.Instance.DownloadInBackground;
foreach (var menuItem in syncronizeFragmentsToolStripMenuItem.DropDownItems.OfType<ToolStripMenuItem>().Where(i => i.Tag != null)) {
menuItem.Enabled = syncEnabledToolStripMenuItem.Checked;
menuItem.Checked = (int.Parse(menuItem.Tag.ToString()) == UserConfig.Instance.SecondsBetweenBackgroundDownloads);
}
}
void exit_Click(object sender, EventArgs e) {
_reallyClose = true;
Close();
}
void flushDns_Click(object sender, EventArgs e) => DnsUtility.FlushDns();
void fragmentDownloadEnding(object sender, EventArgs e) {
var fragment = (Fragment)sender;
if (fragment == _selectedFragment && !fragment.DownloadPending) {
tableLayoutPanel2.BeginInvokeIfRequired(() => {
tableLayoutPanel2.Controls.Remove(loadingLabel);
tableLayoutPanel2.Controls.Add(currentFragmentView, 0, 2);
tableLayoutPanel2.SetColumnSpan(loadingLabel, 2);
});
}
downloadingLabel.BeginInvokeIfRequired(() => downloadingLabel.Visible = (fragmentTreeView.Model.Fragments.Any(f => f.DownloadPending)));
}
void fragmentDownloadStarting(object sender, EventArgs e) {
var fragment = (Fragment)sender;
if (fragment == _selectedFragment && fragment.DownloadPending) {
tableLayoutPanel2.BeginInvokeIfRequired(() => {
tableLayoutPanel2.Controls.Add(loadingLabel, 0, 2);
tableLayoutPanel2.Controls.Remove(currentFragmentView);
tableLayoutPanel2.SetColumnSpan(loadingLabel, 2);
});
}
downloadingLabel.BeginInvokeIfRequired(() => downloadingLabel.Visible = (fragmentTreeView.Model.Fragments.Any(f => f.DownloadPending)));
}
void fragmentPropertyChanged(object sender, PropertyChangedEventArgs e) {
var fragment = (Fragment)sender;
switch (e.PropertyName) {
case "RemoteLocation":
if (fragment == _selectedFragment) updateCurrentFragmentView();
break;
case "FileContents":
if (fragment.Enabled) updateHostsFileView();
break;
case "Enabled":
updateHostsFileView();
if (fragment == _selectedFragment)
updateCurrentFragmentView();
break;
case "Dirty":
if (fragment.Enabled || fragment == _newHostsFile)
updateHostsFileView();
if (fragment == _selectedFragment)
updateCurrentFragmentView();
break;
}
}
void fragmentSearchTextChanged(object sender, EventArgs e) {
fragmentTreeView.Model.Filter = fragmentFilter.Text;
fragmentTreeView.ExpandAll();
}
void loadFragments() {
if (fragmentTreeView.Model.Fragments.Count() == 0) {
var treeNode = new FragmentNode() { Text = "Existing Hosts" };
var currentHosts = new Fragment() { Name = treeNode.Text };
treeNode.Fragment = currentHosts;
fragmentTreeView.Model.FragmentNodes.First(x => x != null && x.Parent != null).Nodes.Add(treeNode);
treeNode.CheckState = CheckState.Checked;
currentHosts.FileContents = _newHostsFile.FileContents;
currentHosts.Save();
_selectedFragment = currentHosts;
}
hostsFileBindingSource.DataSource = _newHostsFile;
updateCurrentFragmentView();
fragmentTreeView.Model.Fragments.AsParallel().ForAll(x => {
x.PropertyChanged += fragmentPropertyChanged;
x.DownloadStarting += fragmentDownloadStarting;
x.ContentsDownloaded += fragmentDownloadEnding;
});
}
void loadUserSettings() {
saveOnProgramStartToolStripMenuItem.Checked = UserConfig.Instance.AutoSaveOnStartup;
closeToTrayToolStripMenuItem.Checked = UserConfig.Instance.CloseToTray;
syncEnabledToolStripMenuItem.Checked = UserConfig.Instance.DownloadInBackground;
newHostsAnalysisToolStripMenuItem.Checked = UserConfig.Instance.NewHostsAnalysis;
_hostfileRecordCombiner.Filter = UserConfig.Instance.NewHostsFilter;
backgroundDownloadTimer.Interval = UserConfig.Instance.SecondsBetweenBackgroundDownloads;
}
void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
savePreferences();
DnsUtility.FlushDns();
}
void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
if (UserConfig.Instance.CloseToTray && !_reallyClose) {
notifyIcon1.Visible = true;
Hide();
e.Cancel = true;
return;
}
if (fragmentTreeView.Model.Fragments.Any(x => x.DownloadPending)) {
DialogResult result = MessageBox.Show("There are still downloads pending, do you really want to exit?", "Downloads Pending", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
e.Cancel = true;
}
if (!e.Cancel && (fragmentTreeView.Model.Fragments.Any(x => x.Dirty) || _newHostsFile.Dirty)) {
DialogResult result = MessageBox.Show("Would you like to save your changes?", "Unsaved Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
switch (result) {
case DialogResult.Yes:
saveAll();
break;
case DialogResult.No:
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
}
void MainForm_Load(object sender, EventArgs e) {
loadFragments();
if (UserConfig.Instance.AutoSaveOnStartup) saveAll();
updateCheckTimer_Tick(null, null);
}
void menuNewFolder_Click(object sender, EventArgs e) => fragmentTreeView.createNewDirectory();
void menuNewFragment_Click(object sender, EventArgs e) => fragmentTreeView.createNewFragment();
void Model_NodesInserted(object sender, TreeModelEventArgs e) {
var changedNode = fragmentTreeView.Model.FindNode(e.Path);
if (changedNode?.Fragment != null) {
changedNode.Fragment.PropertyChanged += fragmentPropertyChanged;
changedNode.Fragment.DownloadStarting += fragmentDownloadStarting;
changedNode.Fragment.ContentsDownloaded += fragmentDownloadEnding;
}
}
void newHostFilterBox_TextChanged(object sender, EventArgs e) {
UserConfig.Instance.NewHostsFilter = newHostFilterBox.Text;
_hostfileRecordCombiner.Filter = UserConfig.Instance.NewHostsFilter;
updateHostsFileView();
updateCurrentFragmentView();
}
void newHostsAnalysisToolStripMenuItem_CheckedChanged(object sender, EventArgs e) {
UserConfig.Instance.NewHostsAnalysis = newHostsAnalysisToolStripMenuItem.Checked;
newHostFilterBox.Enabled = newHostsAnalysisToolStripMenuItem.Checked;
updateHostsFileView();
updateCurrentFragmentView();
}
void remoteUrlView_TextChanged(object sender, EventArgs e) {
if (_selectedFragment != null) {
_selectedFragment.RemoteLocation = remoteUrlView.Text;
}
}
void save_Click(object sender, EventArgs e) => saveAll();
void saveAll() {
try {
fragmentTreeView.Model.SaveAll();
_newHostsFile.Save();
DnsUtility.FlushDns();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void saveOnProgramStartToolStripMenuItem_CheckedChanged(object sender, EventArgs e) => UserConfig.Instance.AutoSaveOnStartup = saveOnProgramStartToolStripMenuItem.Checked;
void savePreferences() {
UserConfig.Instance.SelectedFiles = new List<string>();
if (fragmentTreeView.Model != null && fragmentTreeView.Model.Root.Nodes.Count() > 0) {
var paths = fragmentTreeView.Model.Fragments.Where(x => x.Enabled).Select(x => x.FullPath).ToArray();
UserConfig.Instance.SelectedFiles.AddRange(paths);
}
UserConfig.Instance.Save();
}
void showMainForm(object sender, EventArgs e) => ShowWindow();
void ShowWindow() {
notifyIcon1.Visible = false;
NativeMethods.ShowToFront(this.Handle);
}
void syncDuration_CheckedChanged(object sender, EventArgs e) {
var item = (ToolStripMenuItem)sender;
if (item.Checked) {
UserConfig.Instance.SecondsBetweenBackgroundDownloads = int.Parse(item.Tag.ToString());
backgroundDownloadTimer.Interval = UserConfig.Instance.SecondsBetweenBackgroundDownloads;
enabledToolStripMenuItem_CheckedChanged(null, null);
}
}
void triStateTreeView1_SelectionChanged(object sender, EventArgs e) {
_selectedFragment = null;
if (fragmentTreeView.SelectedNode != null && fragmentTreeView.SelectedNode.Tag is FragmentNode) {
var node = (FragmentNode)fragmentTreeView.SelectedNode.Tag;
if (node != null && node.Fragment != null) {
currentFragmentView.Enabled = true;
remoteUrlView.Enabled = true;
_selectedFragment = node.Fragment;
}
}
if (_selectedFragment == null) {
selectedFragmentBindingSource.DataSource = typeof(VigilantCupcake.Models.Fragment);
currentFragmentView.Enabled = false;
currentFragmentView.Text = string.Empty;
remoteUrlView.Text = string.Empty;
remoteUrlView.Enabled = false;
}
else {
selectedFragmentBindingSource.DataSource = _selectedFragment;
remoteUrlView.Text = _selectedFragment.RemoteLocation;
if (_selectedFragment.DownloadPending) {
tableLayoutPanel2.Controls.Add(loadingLabel, 0, 2);
tableLayoutPanel2.Controls.Remove(currentFragmentView);
tableLayoutPanel2.SetColumnSpan(loadingLabel, 2);
}
else if (!_selectedFragment.DownloadPending) {
tableLayoutPanel2.BeginInvokeIfRequired(() => {
tableLayoutPanel2.Controls.Remove(loadingLabel);
tableLayoutPanel2.Controls.Add(currentFragmentView, 0, 2);
tableLayoutPanel2.SetColumnSpan(loadingLabel, 2);
});
}
currentFragmentView.ReadOnly = !string.IsNullOrEmpty(_selectedFragment.RemoteLocation);
currentFragmentView.BackColor = (currentFragmentView.ReadOnly) ? SystemColors.Control : Color.White;
}
updateCurrentFragmentView();
}
async void updateCheckTimer_Tick(object sender, EventArgs e) {
await Task.Factory.StartNew(async () => {
try {
using (var mgr = await UpdateManager.GitHubUpdateManager(Properties.Settings.Default.ReleasesUrl)) {
bool ignoreDeltaUpdates = true;
retry:
var updateInfo = default(UpdateInfo);
try {
updateInfo = await mgr.CheckForUpdate(ignoreDeltaUpdates);
await mgr.DownloadReleases(updateInfo.ReleasesToApply);
await mgr.ApplyReleases(updateInfo);
await mgr.CreateUninstallerRegistryEntry();
}
catch (Exception) {
if (ignoreDeltaUpdates == false) {
ignoreDeltaUpdates = true;
goto retry;
}
throw;
}
if (updateInfo != null && updateInfo.FutureReleaseEntry != null && updateInfo.FutureReleaseEntry.Version != null && updateInfo.CurrentlyInstalledVersion != null) {
var showNotification = (updateInfo.FutureReleaseEntry.Version > updateInfo.CurrentlyInstalledVersion.Version);
toolStripContainer2.BeginInvokeIfRequired(() => updateNotification.Visible = showNotification);
_aboutBox.BeginInvokeIfRequired(() => _aboutBox.LatestVersionText = updateInfo.FutureReleaseEntry.Version.ToString());
}
}
}
catch (Exception) {
_aboutBox.BeginInvokeIfRequired(() => _aboutBox.LatestVersionText = "Error finding latest version");
}
});
}
void updateCurrentFragmentView() {
currentFragmentView.Enabled = _selectedFragment != null;
remoteUrlView.Enabled = _selectedFragment != null;
if (_selectedFragment != null) {
selectedFragmentLabel.BeginInvokeIfRequired(() => selectedFragmentLabel.Text = $"Selected Fragment{(_selectedFragment.Dirty ? "*" : "")}");
}
}
void updateHostsFileView() {
var text = new List<string>();
if (fragmentTreeView.Model.Fragments.Count() > 0) {
fragmentTreeView.Model.Fragments.Where(x => x.Enabled).ToList().ForEach(y => text.Add(y.FileContents));
//TODO: More efficient????
var newHosts = string.Empty;
FastColoredTextBoxUtility.Collisions = null;
if (UserConfig.Instance.NewHostsAnalysis) {
// Join then split then join to normalize line endings etc, I don't really like it but it works
var blob = string.Join(Environment.NewLine, text);
var result = _hostfileRecordCombiner.GenerateOutput(blob.Split(Environment.NewLine.ToArray()));
newHosts = string.Join(Environment.NewLine, result);
FastColoredTextBoxUtility.Collisions = _hostfileRecordCombiner.Collisions;
}
else {
newHosts = (text.Count() > 0) ? text.Aggregate((agg, val) => agg + Environment.NewLine + val) : "";
}
_newHostsFile.FileContents = newHosts;
hostsFileView.BeginInvokeIfRequired(hostsFileView.RefreshStyles);
newHostsLabel.BeginInvokeIfRequired(() =>
newHostsLabel.Text = $"New Hosts{(_newHostsFile.Dirty ? "*" : "")} {(_hostfileRecordCombiner.Collisions != null && _hostfileRecordCombiner.Collisions.Keys.Count > 0 ? " (Conflicts in red)" : "")}");
}
}
void viewCurrentHostsToolStripMenuItem_Click(object sender, EventArgs e) => _currentHostsForm.ShowDialog();
}
}