-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
621 lines (539 loc) · 23.9 KB
/
MainWindow.xaml.cs
File metadata and controls
621 lines (539 loc) · 23.9 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Forms;
//using System.Windows.Forms.dll; //FOR THE folder browser I REFUSE TO USE IT ...
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.Xml.XPath;
using static System.Net.Mime.MediaTypeNames;
namespace LAVtechQuickRecover
{
public partial class MainWindow : Window
{
private const char DEFAULT_DRIVE_LETTER = 'E';
private string destinationFolderName = "LAVTechRecovery";
private string[] fileOptions = { "Pictures", "Videos","Audio", "Documents", "Misc", "All" };
string[] pictureExtensions = { ".png", ".jpg", ".jpeg", ".gif", "tiff", ".tif", ".bmp" };
string[] vectorGraphicsExtentions = { ".EPS", ".AI", ".psd",".indd", ".raw", ".svg", ".cdr" };
string[] audioExtensions = {".AIF", ".IFF", ".M3U", ".M4A", ".MID", ".MP3", ".MPA", ".WAV", ".WMA" };
string[] videoExtensions = { ".3G2", ".3GP", ".ASF", ".AVI", ".FLV", ".M4V", ".MOV", ".MP4", ".MPG", ".RM", ".SRT", ".SWF", ".VOB", ".WMV" };
string[] documentExtensions = { ".PDF", ".doc",".xlsx", "docx", ".xls",".html",".htm", ".ODT", ".ODS", ".PPT", ".PPTX", ".TXT" };
string[] programmingExtentions = {".sln",".js", ".html", ".css", ".json", ".c", ".cpp", "cs", ".py", ".pyc", ".pyw", ".pyx", ".class" /*, "", "", "", "", "", "", ""*/ };
/// <summary>
/// Program to quickly extract selected file types from a drive to another drive. Specifically useful when upgrading your computer and just want to keep photos, documents or videos.
///
/// </summary>
///
//string[] miscExtensions = { ".", ".blend"};
//private Thread processingThread;
private bool preserveFileStructure = false;
private bool testing=false;
private char driveLetter = 'E';
private char destinationDriveLetter = 'E';
private bool operationInProgress = false;
List<char> driveOptionsList = new List<char>();
List<string> extensions = new List<string>();
//Window Dragging Variables
private const int DragStartDelayMilliseconds = 500; // Adjust the duration as needed
private bool isDragging = false;
private Point dragStartPosition;
private DispatcherTimer dragTimer;
private IntPtr hookHandle;
private LowLevelMouseProc hookProc;
public MainWindow()
{
InitializeComponent();
LoadDrives();
LoadDriveOptions();
LoadFileOptions();
customFolderNameTB.Text = destinationFolderName;
//Add the window dragging functionality
MouseLeftButtonDown += Window_MouseLeftButtonDown;
MouseLeftButtonUp += Window_MouseLeftButtonUp;
MouseMove += Window_MouseMove;
dragTimer = new DispatcherTimer();
dragTimer.Interval = TimeSpan.FromMilliseconds(DragStartDelayMilliseconds);
dragTimer.Tick += DragTimer_Tick;
Loaded += Window_Loaded;
Closing += Window_Closing;
AboutLink.PreviewMouseLeftButtonDown += ShowAbout;
// moved to seperate view, utilized only when explicitly requested
//PopulateInputTreeView($"{driveLetter}:"); //will either be drive E:/ by now or the first other drive.
}
private void ShowAbout(Object sender, EventArgs e) {
Window aboutWindow = new about();
aboutWindow.Show();
}
//INITIALIZATION EVENTS
private void LoadFileOptions()
{
foreach(string file in fileOptions) {
fileTypeCB.Items.Add(file);
}
//set default.
fileTypeCB.SelectedIndex = 0;
extensions.AddRange(pictureExtensions);
extensions.AddRange(vectorGraphicsExtentions);
}
private void LoadDriveOptions()
{
int index = 0;
foreach (char _drive in driveOptionsList)
{
sourceFileCB.Items.Add(_drive + ":\\");
destinationFolderCB.Items.Add(_drive + ":\\");
if (_drive.Equals(DEFAULT_DRIVE_LETTER)) //because they are char could use char1==char2 ;)
{
sourceFileCB.SelectedIndex = index;
destinationFolderCB.SelectedIndex = index;
}
index++;
}
//Set default to first drive should E drive be unavalable.
if (sourceFileCB.SelectedIndex < 0)
sourceFileCB.SelectedIndex = 0;
if (destinationFolderCB.SelectedIndex < 0)
destinationFolderCB.SelectedIndex = 0;
}
// EVENT LISTENERS
private async void Copy_Click(object sender, RoutedEventArgs e)
{
if (operationInProgress)
return;
toggleControls(operationInProgress); //set them not enabled -> Show Loading
string sourcePath = driveLetter + ":\\";
string destinationPath = destinationDriveLetter + $":\\{destinationFolderName}\\";
string[] allExtensions = extensions.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();//ImageExtensions.Concat(DocumentExtensions);
try
{
await CopyFilesRecursively(sourcePath, destinationPath, allExtensions);// doesnt want to happy async ... yet
}
catch (Exception ex) { LogError($"An error occurred: {ex.Message}"); }
finally {
toggleControls(operationInProgress);
}
}
private void Done_Click(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
private void FileTypeCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
extensions.Clear();
int choice = fileTypeCB.SelectedIndex;
switch (choice) { //I could've made an enum .. or finished this section before load shedding, I chose the latter
case 0: //0 Pictures
extensions.AddRange(pictureExtensions);
extensions.AddRange(vectorGraphicsExtentions);
break;
case 1: //1 videos
extensions.AddRange(videoExtensions);
break;
case 2: //2 Audio
extensions.AddRange(audioExtensions);
break;
case 3: //3 Documents
extensions.AddRange(documentExtensions);
break;
case 4: //4 Misc //programming, blend, unreal, git....
//throws unimplemented exception ;)
extensions.AddRange(programmingExtentions);
break;
case 5:
default:
extensions.AddRange(pictureExtensions);
extensions.AddRange(documentExtensions);
extensions.AddRange(videoExtensions);
extensions.AddRange(programmingExtentions);
extensions.AddRange(vectorGraphicsExtentions);
extensions.AddRange(audioExtensions);
//do everything ;) that's why the last option is always all.
break;
}
if (testing)
{
extensions.Clear();
extensions.Add(".txt");
}
}
private void LoadDrives()
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.IsReady && (drive.DriveType == DriveType.Removable || drive.DriveType == DriveType.Fixed))
{
string driveName = drive.Name;
string driveLabel = string.IsNullOrEmpty(drive.VolumeLabel) ? driveName : drive.VolumeLabel;
driveOptionsList.Add(driveName[0]);//takes the first char as char.... ;) because string= char[];
}
}
}
private void toggleControls(bool to = false) //disables ui for the duration of execution (also shows loading log :D)
{
operationInProgress = !operationInProgress;
fileTypeCB.IsEnabled = to;
doneBtn.IsEnabled = to;
copyBtn.IsEnabled = to;
copiedFeedback.Content = "";
if (operationInProgress)
{
showLoading();
}
else
{
hideLoading();
}
}
private int showLoading() {
copiedFeedback.Visibility = Visibility.Visible;
loadingIndicator.Visibility = Visibility.Visible;
return 0;
}
private int hideLoading()
{
copiedFeedback.Visibility = Visibility.Hidden;
loadingIndicator.Visibility = Visibility.Hidden;
return 0;
}
private void CustomFolderNameTB_TextChanged(object sender, TextChangedEventArgs e)
{
destinationFolderName = customFolderNameTB.Text;
}
//LOGIC & EXECUTION EVENTS.
private async Task CopyFilesRecursively(string sourceDirectory, string destinationDirectory, IEnumerable<string> extensions)
{
if (preserveFileStructure)
{
Directory.CreateDirectory(destinationDirectory);
await Task.Run(async () =>
{
try
{
foreach (string file in Directory.EnumerateFiles(sourceDirectory))
{
string extension = Path.GetExtension(file);
if (extensions.Contains(extension))
{
string fileName = Path.GetFileName(file);
string destinationFile = Path.Combine(destinationDirectory, fileName);
try
{
File.Copy(file, destinationFile, true);
}
catch (IOException ex)
{
LogError($"Failed to copy file: {fileName}\n\nError: {ex.Message}");
}
}
}
}
catch (Exception ex) {
LogError($"ERROR WITH MESSAGE {ex}");
return;
}
foreach (string subdirectory in Directory.EnumerateDirectories(sourceDirectory))
{
// Skip the destination directory
if (subdirectory.Equals(destinationDirectory, StringComparison.OrdinalIgnoreCase))
continue;
// Prompt the user for permission to access protected directories
if (!HasAccessToDirectory(subdirectory))
{
LogError($"Skipped accessing the protected directory: {subdirectory}");
continue;
}
string directoryName = Path.GetFileName(subdirectory);
string newDestinationDirectory = Path.Combine(destinationDirectory, directoryName);
//CopyFilesRecursively(subdirectory, newDestinationDirectory, extensions);
try
{
await Task.Run(() => { Task recursionTask = CopyFilesRecursively(subdirectory, newDestinationDirectory, extensions); });
}
catch (UnauthorizedAccessException e) {
LogError($"ERROR WITH MESSAGE {e}");
continue; }
}
}).ContinueWith(task =>
{
if (task.Exception != null)
{
// Handle any exceptions occurred in the task
foreach (var ex in task.Exception.InnerExceptions)
{
LogError($"An exception occurred: {ex.Message}");
}
}
}, TaskContinuationOptions.OnlyOnFaulted); ;
}
else
{
Directory.CreateDirectory(destinationDirectory);
await Task.Run(async () =>
{
try
{
foreach (string file in Directory.EnumerateFiles(sourceDirectory))
{
string extension = Path.GetExtension(file);
//inputFileFeedback.Content = $"{file}"; //UI ITEMS ON MAIN UI THREAD!S
if (extensions.Contains(extension))
{
string fileName = Path.GetFileName(file);
string destinationFile = Path.Combine(destinationDirectory, fileName);
try
{
File.Copy(file, destinationFile, true);
//copiedFeedback.Content = $"{file}";//file doesn't show the folder directory
}
catch (Exception ex)
{
// Handle file copying error
LogError($"Failed to copy file: {file}\n\nError: {ex.Message}");
}
}
}
}
catch (Exception ex) {
LogError($"ERROR WITH MESSAGE {ex}");
return;
}
foreach (string subdirectory in Directory.EnumerateDirectories(sourceDirectory))
{
// Skip the destination directory
if (subdirectory.Equals(destinationDirectory, StringComparison.OrdinalIgnoreCase))
continue;
try
{
await Task.Run(() => { Task recursionTask = CopyFilesRecursively(subdirectory, destinationDirectory, extensions); });
}
catch (Exception e) {
LogError($"An exception occurred: {e.Message}");
continue; }
}
}).ContinueWith(task =>
{
if (task.Exception != null)
{
// Handle any exceptions occurred in the task
foreach (var ex in task.Exception.InnerExceptions)
{
LogError($"An exception occurred: {ex.Message}");
}
}
}, TaskContinuationOptions.OnlyOnFaulted); ;
}
}
private bool HasAccessToDirectory(string directory)
{
try
{
// Attempt to get the directory info to check if it is accessible
DirectoryInfo dirInfo = new DirectoryInfo(directory);
_ = dirInfo.GetFiles(); // This will throw an exception if the directory is not accessible
return true;
}
catch
{
return false;
}
}
private void LogError(string errorMessage)
{
//string executableDirectory = AppDomain.CurrentDomain.BaseDirectory;
//string logFilePath = Path.Combine(executableDirectory, "error.log");
//File.AppendAllText(logFilePath, $"{errorMessage}\n");
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
preserveFileStructure = (bool)preserveFileStructureCB.IsChecked; //ignore warning (bool)null = false ;)
}
private void SourceFileCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
driveLetter = driveOptionsList[sourceFileCB.SelectedIndex]; //the first character // because we're working with drives.
}
private void DestinationFolderCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
destinationDriveLetter= driveOptionsList[destinationFolderCB.SelectedIndex]; //first character because ... drive letter.
}
///???????????????/ WINDOW DRAGGING LOGIC
private void Window_Loaded(object sender, RoutedEventArgs e)
{
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
hookProc = MouseHookCallback;
hookHandle = SetMouseHook(hookProc, source.Handle);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
UnhookMouseHook();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
dragStartPosition = e.GetPosition(this);
CaptureMouse();
dragTimer.Start();
}
private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
dragTimer.Stop();
isDragging = false;
ReleaseMouseCapture();
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
Point currentPosition = e.GetPosition(this);
Vector dragDelta = currentPosition - dragStartPosition;
Left += dragDelta.X;
Top += dragDelta.Y;
}
}
private void Window_LostMouseCapture(object sender, MouseEventArgs e)
{
if (isDragging)
{
dragTimer.Stop();
isDragging = false;
}
}
private void DragTimer_Tick(object sender, EventArgs e)
{
dragTimer.Stop();
isDragging = true;
}
private IntPtr SetMouseHook(LowLevelMouseProc proc, IntPtr handle)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private void UnhookMouseHook()
{
if (hookHandle != IntPtr.Zero)
{
UnhookWindowsHookEx(hookHandle);
hookHandle = IntPtr.Zero;
}
}
private IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_LBUTTONUP)
{
if (isDragging)
{
isDragging = false;
ReleaseMouseCapture();
}
}
return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
private const int WH_MOUSE_LL = 14;
private const int WM_LBUTTONUP = 0x0202;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private void Adv_Input_Button_Click(object sender, RoutedEventArgs e)
{
ChooseFolderWindow chooseInputFolderWindow = new ChooseFolderWindow();
if (chooseInputFolderWindow.ShowDialog() == true)
{
// The user selected a folder, and the selected path is in chooseInputFolderWindow.SelectedFolder
string selectedInputFolder = chooseInputFolderWindow.SelectedFolder;
Console.WriteLine(selectedInputFolder);
// Use the selectedInputFolder as needed in your main window logic
}
//Window chooseFolderWindow = new ChooseFolderWindow("Choose Input Folder");
//chooseFolderWindow.Show();
}
private void Adv_Dest_Button_Click(object sender, RoutedEventArgs e)
{
Window chooseFolderWindow = new ChooseFolderWindow("Choose Destination Folder");
chooseFolderWindow.Show();
}
///////////// CODE FOR USING FOLDERBROWSERDIALOG //// WIN FORMS -> REPLACE WITH TREEVIEW*
//private void if_selector_button_Click(object sender, RoutedEventArgs e)
//{
/////todo: implement
//}
// string txtPath = $"{driveLetter}";
// System.Windows.Forms.FolderBrowserDialog openFileDlg = new System.Windows.Forms.FolderBrowserDialog();
// var result = openFileDlg.ShowDialog();
// if (result.ToString() != string.Empty)
// {
// txtPath.Text = openFileDlg.SelectedPath;
// }
// root = txtPath.Text;
//}
//THIS CODE WORKS -> MOVE TO SEPERATE WINDOW.
/*
private void PopulateInputTreeView(string rootDirectory)
{
Console.WriteLine($"Currently your root directory is: {rootDirectory}");
inputFolderTreeView.Items.Clear();
var rootItem = new TreeViewItem
{
Header = rootDirectory,
Tag = rootDirectory
};
inputFolderTreeView.Items.Add(rootItem);
PopulateInputTreeViewRecursively(rootItem, rootDirectory);
}
private void PopulateInputTreeViewRecursively(TreeViewItem parentItem, string parentDirectory)
{
try
{
foreach (string directory in Directory.GetDirectories(parentDirectory))
{
try
{
var item = new TreeViewItem
{
Header = Path.GetFileName(directory),
Tag = directory
};
parentItem.Items.Add(item);
PopulateInputTreeViewRecursively(item, directory);
} catch {
continue; // ;) expert level warning and error supression ;)
}
}
}
catch (UnauthorizedAccessException)
{
// Handle unauthorized access if needed
} catch (Exception ex)
{
Console.WriteLine(ex.Message); // will give the file not found error
}
}
*/
}
}