forked from amrali-eg/EncodingChecker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
637 lines (555 loc) · 24.2 KB
/
MainForm.cs
File metadata and controls
637 lines (555 loc) · 24.2 KB
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
using EncodingUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace EncodingChecker
{
public partial class MainForm : Form
{
private sealed class WorkerArgs
{
internal CurrentAction Action;
internal string BaseDirectory;
internal bool IncludeSubdirectories;
internal string FileMasks;
internal List<string> ValidCharsets;
}
private sealed class WorkerProgress
{
internal string FileName;
internal string DirectoryName;
internal string Charset;
}
private enum CurrentAction
{
View,
Validate,
Convert,
}
private readonly ListViewColumnSorter _lvwColumnSorter;
private readonly BackgroundWorker _actionWorker;
private CurrentAction _currentAction;
private Settings _settings;
private const int RESULTS_COLUMN_CHARSET = 0;
private const int RESULTS_COLUMN_FILE_NAME = 1;
private const int RESULTS_COLUMN_DIRECTORY = 2;
public MainForm()
{
InitializeComponent();
_lvwColumnSorter = new ListViewColumnSorter();
lstResults.ListViewItemSorter = _lvwColumnSorter;
_actionWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
_actionWorker.DoWork += ActionWorkerDoWork;
_actionWorker.ProgressChanged += ActionWorkerProgressChanged;
_actionWorker.RunWorkerCompleted += ActionWorkerCompleted;
}
#region Form events
private void OnFormLoad(object sender, EventArgs e)
{
lstConvert.BeginUpdate();
IEnumerable<string> validCharsets = GetSupportedCharsets();
foreach (string validCharset in validCharsets)
{
try
{ // add only those charsets which are supported by .NET
Encoding encoding = Encoding.GetEncoding(validCharset);
lstValidCharsets.Items.Add(encoding.WebName);
lstConvert.Items.Add(encoding.WebName);
// add UTF-8 with BOM, right after UTF-8
if (encoding.WebName == "utf-8") lstConvert.Items.Add("utf-8-bom");
}
catch
{
// ignored charsets
}
}
if (lstConvert.Items.Count > 0)
lstConvert.SelectedIndex = 0;
lstConvert.EndUpdate();
btnView.Tag = CurrentAction.View;
btnValidate.Tag = CurrentAction.Validate;
btnConvert.Tag = CurrentAction.Convert;
LoadSettings();
//Size the result list columns based on the initial size of the window
lstResults.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
int remainingWidth = lstResults.Width - lstResults.Columns[0].Width;
lstResults.Columns[1].Width = (30 * remainingWidth) / 100;
lstResults.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
}
private void OnBrowseDirectories(object sender, EventArgs e)
{
dlgBrowseDirectories.SelectedPath = lstBaseDirectory.Text;
if (dlgBrowseDirectories.ShowDialog(this) == DialogResult.OK)
{
lstBaseDirectory.Text = dlgBrowseDirectories.SelectedPath;
lstBaseDirectory.Items.Add(dlgBrowseDirectories.SelectedPath);
}
}
private void OnSelectDeselectAll(object sender, EventArgs e)
{
lstResults.ItemChecked -= OnResultItemChecked;
try
{
bool isChecked = chkSelectDeselectAll.Checked;
foreach (ListViewItem item in lstResults.Items)
item.Checked = isChecked;
}
finally
{
lstResults.ItemChecked += OnResultItemChecked;
}
}
private void OnResultItemChecked(object sender, ItemCheckedEventArgs e)
{
chkSelectDeselectAll.CheckedChanged -= OnSelectDeselectAll;
try
{
if (lstResults.CheckedItems.Count == 0)
chkSelectDeselectAll.CheckState = CheckState.Unchecked;
else if (lstResults.CheckedItems.Count == lstResults.Items.Count)
chkSelectDeselectAll.CheckState = CheckState.Checked;
else
chkSelectDeselectAll.CheckState = CheckState.Indeterminate;
}
finally
{
chkSelectDeselectAll.CheckedChanged += OnSelectDeselectAll;
}
}
private void OnResultColumnClick(object o, ColumnClickEventArgs e)
{
if (e.Column == _lvwColumnSorter.SortColumn)
{
_lvwColumnSorter.Order = _lvwColumnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
}
else
{
_lvwColumnSorter.SortColumn = e.Column;
_lvwColumnSorter.Order = SortOrder.Ascending;
}
lstResults.Sort();
}
private void OnHelp(object sender, EventArgs e)
{
ProcessStartInfo psi =
new ProcessStartInfo("http://encodingchecker.codeplex.com/documentation") { UseShellExecute = true };
Process.Start(psi);
}
private void OnAbout(object sender, EventArgs e)
{
using (AboutForm aboutForm = new AboutForm())
aboutForm.ShowDialog(this);
}
private void OnExport(object sender, EventArgs e)
{
if (lstResults.CheckedItems.Count <= 0)
{
ShowWarning("Select one or more files to export");
return;
}
string filename1 = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog
{
Title = "Export to a Text File",
Filter = "txt files (*.txt)|*.txt",
RestoreDirectory = true
};
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filename1 = saveFileDialog1.FileName;
}
if (filename1 != "")
{
try
{
using (StreamWriter sw = new StreamWriter(filename1))
{
foreach (ListViewItem item in lstResults.CheckedItems)
{
string charset = item.SubItems[RESULTS_COLUMN_CHARSET].Text;
string fileName = item.SubItems[RESULTS_COLUMN_FILE_NAME].Text;
string directory = item.SubItems[RESULTS_COLUMN_DIRECTORY].Text;
sw.WriteLine("{0}\t{1}\\{2}", charset, directory, fileName);
}
}
}
catch
{
// do nothing
}
}
}
#endregion
#region Action button handling
private void OnAction(object sender, EventArgs e)
{
CurrentAction action = (CurrentAction)((Button)sender).Tag;
StartAction(action);
}
private void StartAction(CurrentAction action)
{
string directory = lstBaseDirectory.Text;
if (string.IsNullOrEmpty(directory))
{
ShowWarning("Please specify a directory to check");
return;
}
if (!Directory.Exists(directory))
{
ShowWarning("The directory you specified '{0}' does not exist", directory);
return;
}
if (action == CurrentAction.Validate && lstValidCharsets.CheckedItems.Count == 0)
{
ShowWarning("Select one or more valid character sets to proceed with validation");
return;
}
_currentAction = action;
if (_settings == null)
_settings = new Settings();
_settings.RecentDirectories.Add(directory);
UpdateControlsOnActionStart();
List<string> validCharsets = new List<string>(lstValidCharsets.CheckedItems.Count);
foreach (string validCharset in lstValidCharsets.CheckedItems)
validCharsets.Add(validCharset);
WorkerArgs args = new WorkerArgs
{
Action = action,
BaseDirectory = directory,
IncludeSubdirectories = chkIncludeSubdirectories.Checked,
FileMasks = txtFileMasks.Text,
ValidCharsets = validCharsets
};
_actionWorker.RunWorkerAsync(args);
}
private void OnConvert(object sender, EventArgs e)
{
if (lstResults.CheckedItems.Count == 0)
{
ShowWarning("Select one or more files to convert");
return;
}
// stop drawing of the results list view control
lstResults.BeginUpdate();
lstResults.ItemChecked -= OnResultItemChecked;
foreach (ListViewItem item in lstResults.CheckedItems)
{
string charset = item.SubItems[RESULTS_COLUMN_CHARSET].Text;
if (charset == "(Unknown)")
continue;
string fileName = item.SubItems[RESULTS_COLUMN_FILE_NAME].Text;
string directory = item.SubItems[RESULTS_COLUMN_DIRECTORY].Text;
string filePath = Path.Combine(directory, fileName);
FileAttributes attributes = File.GetAttributes(filePath);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
attributes ^= FileAttributes.ReadOnly;
File.SetAttributes(filePath, attributes);
}
if (!Encoding.GetEncoding(charset).Validate(File.ReadAllBytes(filePath)))
{
Debug.WriteLine("Decoding error. " + filePath);
continue;
}
string content;
using (StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding(charset)))
content = reader.ReadToEnd();
string targetCharset = (string)lstConvert.SelectedItem;
Encoding encoding;
// handle UTF-8 and UTF-8 with BOM
if (targetCharset == "utf-8")
{
encoding = new UTF8Encoding(false);
}
else if (targetCharset == "utf-8-bom")
{
encoding = new UTF8Encoding(true);
}
else
{
encoding = Encoding.GetEncoding(targetCharset);
}
using (StreamWriter writer = new StreamWriter(filePath, append: false, encoding))
{
// TODO: catch exceptions
writer.Write(content);
writer.Flush();
}
item.Checked = false;
item.ImageIndex = 0;
item.SubItems[RESULTS_COLUMN_CHARSET].Text = targetCharset;
}
// resume drawing of the results list view control
lstResults.ItemChecked += OnResultItemChecked;
lstResults.EndUpdate();
// execute handler of the 'ItemChecked' event
OnResultItemChecked(lstResults, new ItemCheckedEventArgs(lstResults.Items[0]));
}
private void OnCancelAction(object sender, EventArgs e)
{
if (_actionWorker.IsBusy)
{
btnCancel.Visible = false;
_actionWorker.CancelAsync();
}
}
#endregion
#region Background worker event handlers and helper methods
private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e)
{
const int progressBufferSize = 5;
BackgroundWorker worker = (BackgroundWorker)sender;
WorkerArgs args = (WorkerArgs)e.Argument;
string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*",
args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize];
int reportBufferCounter = 1;
IEnumerable<Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks);
for (int i = 0; i < allFiles.Length; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
string path = allFiles[i];
string fileName = Path.GetFileName(path);
if (!SatisfiesMaskPatterns(fileName, maskPatterns))
continue;
Encoding encoding = TextEncoding.GetFileEncoding(path);
string charset = encoding?.WebName ?? "(Unknown)";
if (args.Action == CurrentAction.Validate)
{
if (args.ValidCharsets.Contains(charset))
continue;
}
string directoryName = Path.GetDirectoryName(path);
progressBuffer[reportBufferCounter - 1] = new WorkerProgress
{
Charset = charset,
FileName = fileName,
DirectoryName = directoryName
};
reportBufferCounter++;
if (reportBufferCounter > progressBufferSize)
{
reportBufferCounter = 1;
int percentageCompleted = (i * 100) / allFiles.Length;
WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize];
Array.Copy(progressBuffer, reportProgress, progressBufferSize);
worker.ReportProgress(percentageCompleted, reportProgress);
Array.Clear(progressBuffer, 0, progressBufferSize);
}
}
// Copy remaining results from buffer, if any.
if (reportBufferCounter > 1)
{
reportBufferCounter--;
const int percentageCompleted = 100;
WorkerProgress[] reportProgress = new WorkerProgress[reportBufferCounter];
Array.Copy(progressBuffer, reportProgress, reportBufferCounter);
worker.ReportProgress(percentageCompleted, reportProgress);
Array.Clear(progressBuffer, 0, reportBufferCounter);
}
}
private static IEnumerable<Regex> GenerateMaskPatterns(string fileMaskString)
{
string[] fileMasks = fileMaskString.Split(new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
string[] processedFileMasks = Array.FindAll(fileMasks, mask => mask.Trim().Length > 0);
if (processedFileMasks.Length == 0)
processedFileMasks = new[] { "*.*" };
List<Regex> maskPatterns = new List<Regex>(processedFileMasks.Length);
foreach (string fileMask in processedFileMasks)
{
if (string.IsNullOrEmpty(fileMask))
continue;
Regex maskPattern =
new Regex("^" + fileMask.Replace(".", "[.]").Replace("*", ".*").Replace("?", ".") + "$",
RegexOptions.IgnoreCase);
maskPatterns.Add(maskPattern);
}
return maskPatterns;
}
private static bool SatisfiesMaskPatterns(string fileName, IEnumerable<Regex> maskPatterns)
{
foreach (Regex maskPattern in maskPatterns)
{
if (maskPattern.IsMatch(fileName))
return true;
}
return false;
}
private void ActionWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
WorkerProgress[] progresses = (WorkerProgress[])e.UserState;
foreach (WorkerProgress progress in progresses)
{
if (progress == null)
break;
ListViewItem resultItem = new ListViewItem(new[] { progress.Charset, progress.FileName, progress.DirectoryName }, -1);
lstResults.Items.Add(resultItem);
actionStatus.Text = progress.FileName;
}
actionProgress.Value = e.ProgressPercentage;
}
private void ActionWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (lstResults.Items.Count > 0)
{
foreach (ColumnHeader columnHeader in lstResults.Columns)
columnHeader.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
}
UpdateControlsOnActionDone();
}
#endregion
#region Loading and saving of settings
private void LoadSettings()
{
string settingsFileName = GetSettingsFileName();
if (!File.Exists(settingsFileName))
return;
using (FileStream settingsFile = new FileStream(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
object settingsInstance = formatter.Deserialize(settingsFile);
_settings = (Settings)settingsInstance;
}
if (_settings.RecentDirectories?.Count > 0)
{
foreach (string recentDirectory in _settings.RecentDirectories)
lstBaseDirectory.Items.Add(recentDirectory);
lstBaseDirectory.SelectedIndex = 0;
}
else
lstBaseDirectory.Text = Environment.CurrentDirectory;
chkIncludeSubdirectories.Checked = _settings.IncludeSubdirectories;
txtFileMasks.Text = _settings.FileMasks;
if (_settings.ValidCharsets?.Length > 0)
{
for (int i = 0; i < lstValidCharsets.Items.Count; i++)
if (Array.Exists(_settings.ValidCharsets,
charset => charset.Equals((string)lstValidCharsets.Items[i])))
lstValidCharsets.SetItemChecked(i, true);
}
_settings.WindowPosition?.ApplyTo(this);
}
private void SaveSettings()
{
if (_settings == null)
_settings = new Settings();
_settings.IncludeSubdirectories = chkIncludeSubdirectories.Checked;
_settings.FileMasks = txtFileMasks.Text;
_settings.ValidCharsets = new string[lstValidCharsets.CheckedItems.Count];
for (int i = 0; i < lstValidCharsets.CheckedItems.Count; i++)
_settings.ValidCharsets[i] = (string)lstValidCharsets.CheckedItems[i];
_settings.WindowPosition = new WindowPosition { Left = Left, Top = Top, Width = Width, Height = Height };
string settingsFileName = GetSettingsFileName();
using (
FileStream settingsFile = new FileStream(settingsFileName, FileMode.Create, FileAccess.Write,
FileShare.None))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(settingsFile, _settings);
settingsFile.Flush();
}
}
private static string GetSettingsFileName()
{
string dataDirectory = ApplicationDeployment.IsNetworkDeployed
? ApplicationDeployment.CurrentDeployment.DataDirectory
: Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (string.IsNullOrEmpty(dataDirectory) || !Directory.Exists(dataDirectory))
dataDirectory = Environment.CurrentDirectory;
dataDirectory = Path.Combine(dataDirectory, "EncodingChecker");
if (!Directory.Exists(dataDirectory))
Directory.CreateDirectory(dataDirectory);
return Path.Combine(dataDirectory, "Settings.bin");
}
#endregion
private void UpdateControlsOnActionStart()
{
btnView.Enabled = false;
btnValidate.Enabled = false;
lblConvert.Enabled = false;
lstConvert.Enabled = false;
btnConvert.Enabled = false;
chkSelectDeselectAll.Enabled = false;
chkSelectDeselectAll.CheckState = CheckState.Unchecked;
btnCancel.Visible = true;
// stop drawing of the results list view control
lstResults.BeginUpdate();
lstResults.ListViewItemSorter = null;
lstResults.ItemChecked -= OnResultItemChecked;
lstResults.Items.Clear();
actionProgress.Value = 0;
actionProgress.Visible = true;
actionStatus.Text = string.Empty;
}
private void UpdateControlsOnActionDone()
{
btnView.Enabled = true;
btnValidate.Enabled = true;
if (lstResults.Items.Count > 0)
{
lblConvert.Enabled = true;
lstConvert.Enabled = true;
btnConvert.Enabled = true;
chkSelectDeselectAll.Enabled = true;
if (_currentAction == CurrentAction.Validate && lstValidCharsets.CheckedItems.Count > 0)
{
string firstValidCharset = (string)lstValidCharsets.CheckedItems[0];
for (int i = 0; i < lstConvert.Items.Count; i++)
{
string convertCharset = (string)lstConvert.Items[i];
if (firstValidCharset.Equals(convertCharset, StringComparison.OrdinalIgnoreCase))
{
lstConvert.SelectedIndex = i;
break;
}
}
}
}
btnCancel.Visible = false;
// resume drawing of the results list view control
lstResults.ListViewItemSorter = _lvwColumnSorter;
lstResults.ItemChecked += OnResultItemChecked;
lstResults.Sort();
lstResults.EndUpdate();
actionProgress.Visible = false;
string statusMessage = _currentAction == CurrentAction.View
? "{0} files processed" : "{0} files do not have the correct encoding";
actionStatus.Text = string.Format(statusMessage, lstResults.Items.Count);
}
private static IEnumerable<string> GetSupportedCharsets()
{
//Using reflection, figure out all the charsets that the UtfUnknown framework supports by reflecting
//over all the strings constants in the UtfUnknown.Core.CodepageName class. These represent all the encodings
//that can be detected by the program.
Assembly assembly = Assembly.LoadFrom("EncodingUtils.dll");
Type codepageName = assembly.GetType("UtfUnknown.Core.CodepageName");
FieldInfo[] charsetConstants = codepageName.GetFields(BindingFlags.GetField | BindingFlags.Static | BindingFlags.NonPublic);
foreach (FieldInfo charsetConstant in charsetConstants)
{
if (charsetConstant.FieldType == typeof(string))
yield return (string)charsetConstant.GetValue(null);
}
}
private void ShowWarning(string message, params object[] args)
{
MessageBox.Show(this, string.Format(message, args), @"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}