-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMainWindow.axaml.cs
537 lines (502 loc) · 20.9 KB
/
MainWindow.axaml.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
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
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Media;
using Microsoft.Win32;
using robocopy_gui.Classes;
using robocopy_gui.UI;
using System;
using System.Collections.Generic;
using System.IO;
namespace robocopy_gui;
public partial class MainWindow : Window {
public static List<Operation> OperationsList { get; set; } = new List<Operation>();
private static RegistryKey Regkey =
#pragma warning disable CS8601 // Possible null reference assignment.
//Yes, the key is possibly null here. This is handled later, in initializations.
//So later on, this key is not null and all other checks should reflect that.
Registry.CurrentUser.OpenSubKey("Software\\Stormbase\\robocopy-ui", RegistryKeyPermissionCheck.ReadWriteSubTree);
#pragma warning restore CS8601
private string currentFile = string.Empty;
private string scriptTitle = "Backup";
private bool pathAsOperationName = true;
public MainWindow() {
InitializeComponent();
try {
var version = System.Reflection.Assembly.GetExecutingAssembly()?.GetName()?.Version?.ToString();
if (version is not null) {
TitleLabel.Content = "Robocopy GUI " + version;
}
string lastFile = "";
if (Regkey != null) {
string? lastFileValue = Regkey.GetValue("lastFile") as string;
if (lastFileValue is not null) {
lastFile = lastFileValue;
}
var lastWidth = Regkey.GetValue("Width");
var lastHeight = Regkey.GetValue("Height");
if (lastHeight is not null && lastWidth is not null) {
MainWindow1.Width = Convert.ToInt32(lastWidth);
MainWindow1.Height = Convert.ToInt32(lastHeight);
}
var pathAsNameValue = Regkey.GetValue("PathAsOperationName");
if (pathAsNameValue is not null) {
pathAsOperationName = Convert.ToBoolean(pathAsNameValue);
}
CheckOperationName.IsChecked = pathAsOperationName;
} else {
RegistryKey? key = Registry.CurrentUser.OpenSubKey("Software\\Stormbase", RegistryKeyPermissionCheck.ReadWriteSubTree);
if (key == null) {
Registry.CurrentUser.OpenSubKey("Software", RegistryKeyPermissionCheck.ReadWriteSubTree)?.CreateSubKey("Stormbase", true);
key = Registry.CurrentUser.OpenSubKey("Software\\Stormbase", RegistryKeyPermissionCheck.ReadWriteSubTree);
}
key = key?.OpenSubKey("robocopy-ui");
if (key == null) {
Registry.CurrentUser.OpenSubKey("Software\\Stormbase", RegistryKeyPermissionCheck.ReadWriteSubTree)?.CreateSubKey("robocopy-ui", true);
}
Regkey = Registry.CurrentUser.OpenSubKey("Software\\Stormbase\\robocopy-ui", RegistryKeyPermissionCheck.ReadWriteSubTree)
?? throw new Exception("Couldn't open registry key after creation");
}
if (!string.IsNullOrWhiteSpace(lastFile)) {
if (File.Exists(lastFile)) {
InputFilePath.Text = lastFile;
currentFile = lastFile;
ButtonCommit.IsEnabled = true;
ButtonRun.IsEnabled = true;
ReadFile();
}
}
} catch (Exception e) {
DialogMessage dialog = new DialogMessage(e.Message, "Error");
dialog.ShowDialog(MainWindow1);
throw;
}
}
/* UI ELEMENTS
* ===============================================================================
* ===============================================================================
*/
private async void ButtonPickFile_Click(object sender, RoutedEventArgs e) {
OpenFileDialog openFileDialog = new OpenFileDialog {
Filters = new List<FileDialogFilter> { new FileDialogFilter { Extensions = new List<string> { "bat" }, Name = "Batch Files" } },
AllowMultiple = false
};
var result = await openFileDialog.ShowAsync(MainWindow1);
if (result is not null && result.Length > 0) {
string fileName = result[0];
currentFile = fileName;
InputFilePath.Text = currentFile;
if (File.Exists(fileName)) {
ReadFile();
} else {
File.CreateText(fileName).Dispose();
//show operations group with empty list to allow adding of new operations
ClearOperationsList();
RenderList();
}
ButtonCommit.IsEnabled = true;
ButtonRun.IsEnabled = true;
}
}
private async void ButtonReloadFile_Click(object sender, RoutedEventArgs e) {
if (File.Exists(currentFile)) {
ReadFile();
} else {
DialogMessage message = new DialogMessage(
"The file / path you've entered does not exist.\nDo you want to create it?",
"File doesn't exist"
);
message.SetButtons(new string[] { "Yes", "Cancel" });
await message.ShowDialog(MainWindow1);
if (message.ReturnValue == "Yes") {
File.CreateText(currentFile).Dispose();
//show operations group with empty list to allow adding of new operations
ClearOperationsList();
RenderList();
ButtonCommit.IsEnabled = true;
ButtonRun.IsEnabled = true;
} else {
InputFilePath.Text = currentFile;
}
message.Close();
}
}
private async void InputFilePath_LostFocus(object? sender, RoutedEventArgs e) {
InputFilePath.LostFocus -= InputFilePath_LostFocus; //necessary, because on Enter this procedure would then fire again
if (currentFile != InputFilePath.Text) {
string fileName = InputFilePath.Text;
if (File.Exists(fileName)) {
currentFile = fileName;
ReadFile();
ButtonCommit.IsEnabled = true;
ButtonRun.IsEnabled = true;
} else {
DialogMessage message = new DialogMessage(
"The file / path you've entered does not exist.\nDo you want to create it?",
"File doesn't exist"
);
message.SetButtons(new string[] { "Yes", "Cancel" });
await message.ShowDialog(MainWindow1);
if (message.ReturnValue == "Yes") {
File.CreateText(fileName).Dispose();
currentFile = fileName;
//show operations group with empty list to allow adding of new operations
ClearOperationsList();
RenderList();
ButtonCommit.IsEnabled = true;
ButtonRun.IsEnabled = true;
} else {
InputFilePath.Text = currentFile;
}
message.Close();
}
}
InputFilePath.LostFocus += InputFilePath_LostFocus; //see above
}
private void InputFilePath_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Enter) {
InputFilePath_LostFocus(sender, e);
}
}
private void InputScriptTitle_LostFocus(object sender, RoutedEventArgs e) {
scriptTitle = InputScriptTitle.Text;
}
private void InputScriptTitle_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Enter) {
InputScriptTitle_LostFocus(sender, e);
}
}
private void CheckOperationName_Checked(object sender, RoutedEventArgs e) {
pathAsOperationName = true;
Regkey.SetValue("PathAsOperationName", true);
}
private void CheckOperationName_Unchecked(object sender, RoutedEventArgs e) {
pathAsOperationName = false;
Regkey.SetValue("PathAsOperationName", false);
}
private async void CheckStartup_Checked(object sender, RoutedEventArgs e) {
if (!await new StartupTask(currentFile, scriptTitle).Register()) {
CheckStartup.IsChecked = false;
}
}
private void CheckStartup_Unchecked(object sender, RoutedEventArgs e) {
new StartupTask(currentFile, scriptTitle).Unregister();
}
/* ROUTINES FOR GENERATED OPERATION ROW UI ELEMENTS
* ===============================================================================
* ===============================================================================
*/
private async void OperationButtonSearchSource_Click(object? sender, RoutedEventArgs e) {
Button s = sender as Button ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OpenFolderDialog dialog = new OpenFolderDialog {
Directory = Path.GetDirectoryName(OperationsList[index].SourceFolder)
};
string? result = await dialog.ShowAsync(MainWindow1);
if (result is not null) {
OperationsList[index].SourceFolder = result;
OperationsList[index].Name = OperationsList[index].CreateName();
foreach (Control control in GridOperations.Children) {
if (control.Name == "source" && Convert.ToInt32(control.Tag) == index) {
((TextBox)control).Text = result;
}
}
}
}
private async void OperationButtonSearchDest_Click(object? sender, RoutedEventArgs args) {
Button s = sender as Button ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OpenFolderDialog dialog = new OpenFolderDialog {
Directory = Path.GetDirectoryName(OperationsList[index].DestinationFolder)
};
string? result = await dialog.ShowAsync(MainWindow1);
if (result is not null) {
OperationsList[index].DestinationFolder = result;
OperationsList[index].Name = OperationsList[index].CreateName();
foreach (Control control in GridOperations.Children) {
if (control.Name == "dest" && Convert.ToInt32(control.Tag) == index) {
((TextBox)control).Text = result;
}
}
}
}
private void OperationTextBoxSource_LostFocus(object? sender, RoutedEventArgs e) {
TextBox s = sender as TextBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].SourceFolder = s.Text;
OperationsList[index].Name = OperationsList[index].CreateName();
}
private void OperationTextBoxDest_LostFocus(object? sender, RoutedEventArgs e) {
TextBox s = sender as TextBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].DestinationFolder = s.Text;
OperationsList[index].Name = OperationsList[index].CreateName();
}
private void OperationTextBoxCommand_LostFocus(object? sender, RoutedEventArgs e) {
TextBox s = sender as TextBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].Command = s.Text;
}
private void OperationCheckMirror_enable(object? sender, RoutedEventArgs e) {
CheckBox s = sender as CheckBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].IsMirror = true;
foreach (Control control in GridOperations.Children) {
if (control.Name == "move" && Convert.ToInt32(control.Tag) == index) {
((CheckBox)control).IsChecked = false;
}
}
}
private void OperationCheckMove_enable(object? sender, RoutedEventArgs e) {
CheckBox s = sender as CheckBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].IsMove = true;
foreach (Control control in GridOperations.Children) {
if (control.Name == "mirror" && Convert.ToInt32(control.Tag) == index) {
((CheckBox)control).IsChecked = false;
}
}
}
/* ROUTINES FOR READING AND PARSING FILE
* ===============================================================================
* ===============================================================================
*/
private void ClearOperationsList() {
OperationsList.Clear();
foreach (Control control in GridOperations.Children) {
if (control is TextBox) // this prevents LostFocus events from firing for non-existing elements after the list is cleared or re-populated
{
control.LostFocus -= OperationTextBoxSource_LostFocus;
control.LostFocus -= OperationTextBoxDest_LostFocus;
}
}
GridOperations.Children.Clear();
GridOperations.RowDefinitions.Clear();
}
private void ReadFile() {
ClearOperationsList();
//read lines in file
List<string> operationStrings = new List<string>();
using (StreamReader reader = File.OpenText(currentFile)) {
while (!reader.EndOfStream) {
var readLine = reader.ReadLine();
if (readLine != null && !string.IsNullOrWhiteSpace(readLine) && readLine != "echo off") {
operationStrings.Add(readLine);
}
}
reader.Close();
}
//interpret all read lines as operations
foreach (string operation in operationStrings) {
if (operation.ToLower().StartsWith("robocopy") || operation.ToLower().StartsWith("rem robocopy")) {
OperationsList.Add(new Operation(operation));
} else if (operation.ToLower().StartsWith("title ")) {
scriptTitle = operation.Substring(6);
} else if (operation.ToLower().StartsWith("rem ") && !operation.ToLower().StartsWith("rem echo")) {
OperationsList.Add(new Operation(true, false, operation.Substring(3)));
} else if (!operation.ToLower().StartsWith("echo")) {
OperationsList.Add(new Operation(true, true, operation));
}
}
InputScriptTitle.Text = scriptTitle;
if (new StartupTask(currentFile, scriptTitle).CheckRegistration()) {
CheckStartup.IsChecked = true;
} else {
CheckStartup.IsChecked = false;
}
RenderList();
}
private void AddOperationRow(Operation operation, int operationIndex) {
RowDefinition newRow = new RowDefinition {
Height = new GridLength(42)
};
GridOperations.RowDefinitions.Add(newRow);
if (!operation.IsArbitrary) {
RowOperationRobocopy row = new RowOperationRobocopy(operationIndex);
row.SearchSourceButton.Click += OperationButtonSearchSource_Click;
row.SearchDestButton.Click += OperationButtonSearchDest_Click;
row.SourceText.LostFocus += OperationTextBoxSource_LostFocus;
row.DestText.LostFocus += OperationTextBoxDest_LostFocus;
row.Mirror.Checked += OperationCheckMirror_enable;
row.Move.Checked += OperationCheckMove_enable;
Grid.SetRow(row.SearchSourceButton, operationIndex);
Grid.SetRow(row.SourceText, operationIndex);
Grid.SetRow(row.SearchDestButton, operationIndex);
Grid.SetRow(row.DestText, operationIndex);
Grid.SetRow(row.ExclFilesButton, operationIndex);
Grid.SetRow(row.ExclFoldersButton, operationIndex);
Grid.SetRow(row.Mirror, operationIndex);
Grid.SetRow(row.Move, operationIndex);
Grid.SetRow(row.SettingsButton, operationIndex);
GridOperations.Children.Add(row.SearchSourceButton);
GridOperations.Children.Add(row.SourceText);
GridOperations.Children.Add(row.SearchDestButton);
GridOperations.Children.Add(row.DestText);
GridOperations.Children.Add(row.ExclFilesButton);
GridOperations.Children.Add(row.ExclFoldersButton);
GridOperations.Children.Add(row.Mirror);
GridOperations.Children.Add(row.Move);
GridOperations.Children.Add(row.SettingsButton);
} else {
RowOperationArbitrary row = new RowOperationArbitrary(operationIndex);
row.Command.LostFocus += OperationTextBoxCommand_LostFocus;
Grid.SetColumn(row.Command, 1);
Grid.SetColumnSpan(row.Command, 9);
Grid.SetRow(row.Command, operationIndex);
GridOperations.Children.Add(row.Command);
}
CheckBox enabled = new CheckBox {
Content = "Enabled",
IsChecked = operation.IsEnabled,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
Tag = operationIndex
};
enabled.Checked += (sender, e) => {
CheckBox s = sender as CheckBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].IsEnabled = true;
};
enabled.Unchecked += (sender, e) => {
CheckBox s = sender as CheckBox ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(s.Tag);
OperationsList[index].IsEnabled = false;
};
Grid.SetColumn(enabled, 0);
Grid.SetRow(enabled, operationIndex);
PathIcon removeIcon = new PathIcon {
Data = Geometry.Parse(Icons.Delete)
};
Button remove = new Button {
Content = removeIcon,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
Width = 60,
Tag = operationIndex,
HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center
};
remove.Click += (s, e) => {
Button sender = s as Button ?? throw new Exception("Sender is null");
int index = Convert.ToInt32(sender.Tag);
OperationsList.RemoveAt(index);
List<Control> toDelete = new List<Control>();
foreach (Control control in GridOperations.Children) {
if ((int)control.GetValue(Grid.RowProperty) == index) {
toDelete.Add(control); //the separate list is needed to not modify the collection that drives the foreach
}
if ((int)control.GetValue(Grid.RowProperty) > index) {
Grid.SetRow(control, (int)control.GetValue(Grid.RowProperty) - 1);
control.Tag = Convert.ToInt32(control.Tag) - 1;
}
}
foreach (Control control in toDelete) {
GridOperations.Children.Remove(control);
}
GridOperations.RowDefinitions.RemoveAt(index);
};
Grid.SetColumn(remove, 11);
Grid.SetRow(remove, operationIndex);
GridOperations.Children.Add(enabled);
GridOperations.Children.Add(remove);
}
public void RenderList() {
Regkey.SetValue("lastFile", currentFile);
int operationIndex = 0;
foreach (Operation operation in OperationsList) {
AddOperationRow(operation, operationIndex);
operationIndex++;
}
RowDefinition addRow = new RowDefinition {
Height = new GridLength(42)
};
GridOperations.RowDefinitions.Add(addRow);
Button add = new Button {
Name = "ButtonAddRobocopy",
Content = "+ Operation",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
Width = 240
};
add.Click += (s, e) => {
Operation newOp = new Operation(string.Empty, string.Empty);
OperationsList.Add(newOp);
int currentAddRow = 0;
foreach (Control control in GridOperations.Children) {
if (control.Name == "ButtonAddArbitrary") {
currentAddRow = (int)control.GetValue(Grid.RowProperty);
Grid.SetRow(control, currentAddRow + 1);
Grid.SetRow(s as Control, currentAddRow + 1);
}
}
AddOperationRow(newOp, currentAddRow);
};
Button addArbitrary = new Button {
Name = "ButtonAddArbitrary",
Content = "+ Arbitrary Command",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
Width = 240
};
addArbitrary.Click += (s, e) => {
Operation newOp = new Operation(true, true, string.Empty);
OperationsList.Add(newOp);
int currentAddRow = 0;
foreach (Control control in GridOperations.Children) {
if (control.Name == "ButtonAddRobocopy") {
currentAddRow = (int)control.GetValue(Grid.RowProperty);
Grid.SetRow(control, currentAddRow + 1);
Grid.SetRow(s as Control, currentAddRow + 1);
}
}
AddOperationRow(newOp, currentAddRow);
};
Grid.SetColumn(add, 7);
Grid.SetColumnSpan(add, 4);
Grid.SetRow(add, operationIndex);
Grid.SetColumn(addArbitrary, 4);
Grid.SetColumnSpan(addArbitrary, 3);
Grid.SetRow(addArbitrary, operationIndex);
GridOperations.Children.Add(add);
GridOperations.Children.Add(addArbitrary);
}
private void ButtonCommit_Click(object? sender, RoutedEventArgs e) {
// MessageBox.Show("Inspect!"); // set breakpoint here for convenient variable inspection
StreamWriter file;
if (!File.Exists(currentFile)) {
file = File.CreateText(currentFile);
} else {
file = new StreamWriter(currentFile);
}
file.WriteLine("echo off");
file.WriteLine("title " + scriptTitle);
foreach (Operation item in OperationsList) {
if ((item.IsArbitrary && !string.IsNullOrWhiteSpace(item.Command)) ||
(!string.IsNullOrWhiteSpace(item.SourceFolder) && !string.IsNullOrWhiteSpace(item.DestinationFolder))) {
file.WriteLine();
if (!item.IsEnabled) {
file.Write("REM ");
}
if (!item.IsArbitrary) {
if (!pathAsOperationName) {
file.WriteLine("echo \"" + item.Name + "\"");
} else {
file.WriteLine("echo \"" + item.SourceFolder + " -> " + item.DestinationFolder + "\"");
}
} else {
file.WriteLine("echo \"" + item.Command + "\"");
}
file.WriteLine(item.GetCommand());
}
}
file.Close();
}
private void ButtonRun_Click(object? sender, RoutedEventArgs e) {
ButtonCommit_Click(sender, e);
System.Diagnostics.Process.Start(currentFile);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
Regkey.SetValue("Width", MainWindow1.Width);
Regkey.SetValue("Height", MainWindow1.Height);
}
}