forked from Cinchoo/ChoEazyCopy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
874 lines (772 loc) · 31.2 KB
/
MainWindow.xaml.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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
using Cinchoo.Core;
using Cinchoo.Core.Configuration;
using Cinchoo.Core.Diagnostics;
using Cinchoo.Core.Win32.Dialogs;
using Cinchoo.Core.WPF;
using MahApps.Metro.Controls;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
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.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
namespace ChoEazyCopy
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow, INotifyPropertyChanged
{
#region Instance Members (Private)
internal static string Caption;
private DispatcherTimer _dispatcherTimer;
private Thread _mainUIThread;
private Thread _fileNameProcessThread;
private ChoAppSettings _appSettings;
private bool _isRunning = false;
public bool IsRunning
{
get { return _isRunning; }
set
{
_isRunning = value;
RaisePropertyChanged(nameof(IsRunning));
}
}
private bool _wndLoaded = false;
private bool _isNewFileOp = false;
private bool _isDirty = false;
private bool IsDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
private string _settingsFilePath = null;
public string SettingsFilePath
{
get { return _settingsFilePath; }
private set
{
_settingsFilePath = value;
IsDirty = false;
}
}
ChoRoboCopyManager _roboCopyManager = null;
ChoWPFBindableConfigObject<ChoAppSettings> _bindObj;
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
#endregion Instance Members (Private)
private bool _scrollOutput = true;
public bool ScrollOutput
{
get { return _scrollOutput; }
set
{
_scrollOutput = value;
RaisePropertyChanged(nameof(ScrollOutput));
}
}
private bool _rememberWindowSizeAndPosition = true;
public bool RememberWindowSizeAndPosition
{
get { return _rememberWindowSizeAndPosition; }
set
{
_rememberWindowSizeAndPosition = value;
RaisePropertyChanged(nameof(RememberWindowSizeAndPosition));
}
}
public ChoAppSettings AppSettings
{
get { return _appSettings; }
set
{
_appSettings = value;
RaisePropertyChanged(nameof(AppSettings));
}
}
public MainWindow() :
this(null)
{
}
public MainWindow(string settingsFilePath)
{
SettingsFilePath = settingsFilePath;
InitializeComponent();
Caption = Title;
Title = "{0} (v{1})".FormatString(Title, Assembly.GetEntryAssembly().GetName().Version);
var up = new ChoUserPreferences();
RememberWindowSizeAndPosition = up.RememberWindowSizeAndPosition;
ScrollOutput = up.ScrollOutput;
if (up.RememberWindowSizeAndPosition)
{
this.Height = up.WindowHeight;
this.Width = up.WindowWidth;
this.Top = up.WindowTop;
this.Left = up.WindowLeft;
this.WindowState = up.WindowState;
}
}
private void MyWindow_Loaded(object sender1, RoutedEventArgs e1)
{
_bindObj = new ChoWPFBindableConfigObject<ChoAppSettings>();
_appSettings = _bindObj.UnderlyingSource;
_appSettings.Init();
if (!SettingsFilePath.IsNullOrWhiteSpace() && File.Exists(SettingsFilePath))
_appSettings.LoadXml(File.ReadAllText(SettingsFilePath));
else
_appSettings.Reset();
DataContext = this;
_mainUIThread = Thread.CurrentThread;
btnNewFile_Click(null, null);
_dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
_dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
_dispatcherTimer.Start();
string x = _appSettings.SourceDirectory;
ChoShellExtCmdLineArgs cmdLineArgs = new ChoShellExtCmdLineArgs();
if (!cmdLineArgs.Directory.IsNullOrWhiteSpace())
_appSettings.SourceDirectory = cmdLineArgs.Directory;
IsDirty = false;
}
private void RegisterEvents()
{
_appSettings.BeforeConfigurationObjectLoaded += _appSettings_BeforeConfigurationObjectLoaded;
_appSettings.AfterConfigurationObjectMemberSet += _appSettings_AfterConfigurationObjectMemberSet;
_appSettings.ConfigurationObjectMemberLoadError += _appSettings_ConfigurationObjectMemberLoadError;
_appSettings.AfterConfigurationObjectPersisted += _appSettings_AfterConfigurationObjectPersisted;
_appSettings.AfterConfigurationObjectLoaded += _appSettings_AfterConfigurationObjectLoaded;
}
private void UnregisterEvents()
{
_appSettings.BeforeConfigurationObjectLoaded -= _appSettings_BeforeConfigurationObjectLoaded;
_appSettings.AfterConfigurationObjectMemberSet -= _appSettings_AfterConfigurationObjectMemberSet;
_appSettings.ConfigurationObjectMemberLoadError -= _appSettings_ConfigurationObjectMemberLoadError;
_appSettings.AfterConfigurationObjectPersisted -= _appSettings_AfterConfigurationObjectPersisted;
_appSettings.AfterConfigurationObjectLoaded -= _appSettings_AfterConfigurationObjectLoaded;
}
private void _appSettings_BeforeConfigurationObjectLoaded(object sender, ChoPreviewConfigurationObjectEventArgs e)
{
e.Cancel = (bool)this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Func<bool>(() =>
{
if (IsDirty)
{
if (MessageBox.Show("Configuration settings has been modified outside of the tool. {0}Do you want to reload it and lose the changes made in the tool?".FormatString(Environment.NewLine),
Title, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
return false;
else
return true;
}
return false;
}));
}
private void _appSettings_AfterConfigurationObjectMemberSet(object sender, ChoConfigurationObjectMemberEventArgs e)
{
if (_wndLoaded)
{
//IsDirty = true;
}
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
txtRoboCopyCmd.Text = _appSettings.GetCmdLineText();
txtRoboCopyCmdEx.Text = _appSettings.GetCmdLineTextEx();
}));
}
private void _appSettings_AfterConfigurationObjectLoaded(object sender, ChoConfigurationObjectEventArgs e)
{
if (_wndLoaded)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
this.DataContext = null;
this.DataContext = this;
txtRoboCopyCmd.Text = _appSettings.GetCmdLineText();
txtRoboCopyCmdEx.Text = _appSettings.GetCmdLineTextEx();
IsDirty = false;
}));
}
else
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
txtRoboCopyCmd.Text = _appSettings.GetCmdLineText();
txtRoboCopyCmdEx.Text = _appSettings.GetCmdLineTextEx();
IsDirty = false;
}));
}
}
private void MyWindow_ContentRendered(object sender, EventArgs e)
{
_wndLoaded = true;
}
private void SaveDirectories()
{
StringBuilder msg = new StringBuilder();
//foreach (string folder in lstFolders.Items)
//{
// if (msg.Length == 0)
// msg.Append(folder);
// else
// msg.AppendFormat(";{0}", folder);
//}
//_appSettings.Directories = msg.ToString();
}
private void _appSettings_AfterConfigurationObjectPersisted(object sender, ChoConfigurationObjectEventArgs e)
{
//SaveSettings();
}
private void _appSettings_ConfigurationObjectMemberLoadError(object sender, Cinchoo.Core.Configuration.ChoConfigurationObjectMemberErrorEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
e.Handled = true;
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
grpFolders.IsEnabled = !IsRunning;
if (IsRunning)
btnRun.IsEnabled = false;
else
{
if (!txtSourceDirectory.Text.IsNullOrWhiteSpace()
&& Directory.Exists(txtSourceDirectory.Text)
&& !txtDestDirectory.Text.IsNullOrWhiteSpace()
)
btnRun.IsEnabled = true;
else
btnRun.IsEnabled = false;
}
btnStop.IsEnabled = IsRunning;
btnNewFile.IsEnabled = !IsRunning;
btnOpenFile.IsEnabled = !IsRunning;
btnSaveFile.IsEnabled = !IsRunning && IsDirty;
btnSaveAsFile.IsEnabled = !IsRunning;
if (SettingsFilePath.IsNullOrWhiteSpace())
{
this.ToolTip = null;
tbSettingsName.Text = "<NEW>";
tbSettingsName.ToolTip = "New File";
}
else
{
this.ToolTip = SettingsFilePath;
tbSettingsName.Text = Path.GetFileNameWithoutExtension(SettingsFilePath);
tbSettingsName.ToolTip = SettingsFilePath;
}
btnClear.IsEnabled = !IsRunning && txtStatus.Text.Length > 0;
if (_fileNameProcessThread != null && _fileNameProcessThread.IsAlive)
{
}
else
{
}
// Forcing the CommandManager to raise the RequerySuggested event
CommandManager.InvalidateRequerySuggested();
}
private void btnSourceDirBrowse_Click(object sender, RoutedEventArgs e)
{
ChoFolderBrowserDialog dlg1 = new ChoFolderBrowserDialog
{
Description = "Choose source folder...",
ShowNewFolderButton = true,
ShowEditBox = true,
ShowBothFilesAndFolders = false,
NewStyle = true,
SelectedPath = (System.IO.Directory.Exists(txtSourceDirectory.Text)) ? txtSourceDirectory.Text : "",
ShowFullPathInEditBox = false,
};
dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;
var result = dlg1.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
if (Directory.Exists(dlg1.SelectedPath))
txtSourceDirectory.Text = dlg1.SelectedPath;
else
txtSourceDirectory.Text = System.IO.Path.GetDirectoryName(dlg1.SelectedPath);
}
}
private void btnDestDirBrowse_Click(object sender, RoutedEventArgs e)
{
ChoFolderBrowserDialog dlg1 = new ChoFolderBrowserDialog
{
Description = "Choose copy/move folder to...",
ShowNewFolderButton = true,
ShowEditBox = true,
ShowBothFilesAndFolders = false,
NewStyle = true,
SelectedPath = (System.IO.Directory.Exists(txtDestDirectory.Text)) ? txtDestDirectory.Text : "",
ShowFullPathInEditBox = false,
};
dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;
var result = dlg1.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
if (Directory.Exists(dlg1.SelectedPath))
txtDestDirectory.Text = dlg1.SelectedPath;
else
txtDestDirectory.Text = System.IO.Path.GetDirectoryName(dlg1.SelectedPath);
}
}
private void Window_Closed(object sender, EventArgs e)
{
ChoFramework.Shutdown();
}
private void ProcessFiles(object cmd)
{
ChoAppSettings appSettings = cmd as ChoAppSettings; // cmd.ToString();
if (appSettings == null)
return;
try
{
IsRunning = true;
_roboCopyManager = new ChoRoboCopyManager();
_roboCopyManager.Status += (sender, e) => SetStatusMsg(e.Message);
_roboCopyManager.AppStatus += (sender, e) => UpdateStatus(e.Message, e.Tag.ToNString());
_roboCopyManager.Process(appSettings.RoboCopyFilePath, appSettings.GetCmdLineParams(), appSettings);
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
SetStatusMsg(ex.ToString());
}
finally
{
IsRunning = false;
_roboCopyManager = null;
}
}
private void SetStatusMsg(string msg)
{
if (msg != Environment.NewLine && msg.IsNullOrWhiteSpace()) return;
if (Thread.CurrentThread != _mainUIThread)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => SetStatusMsg(msg)));
}
else
{
Debug.WriteLine(msg);
//while (txtStatus.Items.Count > _appSettings.MaxStatusMsgSize)
//{
// txtStatus.Items.RemoveAt(0);
//}
txtStatus.AppendText(msg);
if (ScrollOutput)
txtStatus.ScrollToEnd();
}
}
private void UpdateStatus(string text, string toolTipText)
{
sbAppStatus.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
sbAppStatus.Text = text;
if (!toolTipText.IsNullOrWhiteSpace())
ShowBalloonTipText(toolTipText);
}));
}
private void ShowBalloonTipText(string msg)
{
if (ChoApplication.NotifyIcon != null)
{
ChoApplication.NotifyIcon.BalloonTipText = msg;
ChoApplication.NotifyIcon.ShowBalloonTip(500);
}
}
private void tbrMain_Loaded(object sender, RoutedEventArgs e)
{
ToolBar toolBar = sender as ToolBar;
var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;
if (overflowGrid != null)
{
overflowGrid.Visibility = Visibility.Collapsed;
}
var mainPanelBorder = toolBar.Template.FindName("MainPanelBorder", toolBar) as FrameworkElement;
if (mainPanelBorder != null)
{
mainPanelBorder.Margin = new Thickness();
}
}
private void btnRun_Click(object sender, RoutedEventArgs e)
{
ChoFileMoveAttributes value = ChoFileMoveAttributes.None;
if (Enum.TryParse<ChoFileMoveAttributes>(_appSettings.MoveFilesAndDirectories.ToNString(), out value))
{
switch (value)
{
case ChoFileMoveAttributes.MoveFilesOnly:
if (MessageBox.Show("Are you sure you wish to remove original file{s}? This CANNOT be undone!", Caption, MessageBoxButton.YesNo, MessageBoxImage.Stop) == MessageBoxResult.No)
return;
break;
case ChoFileMoveAttributes.MoveDirectoriesAndFiles:
if (MessageBox.Show("Are you sure you wish to remove original file{s} / folder(s)? This CANNOT be undone!", Caption, MessageBoxButton.YesNo, MessageBoxImage.Stop) == MessageBoxResult.No)
return;
break;
default:
break;
}
}
_fileNameProcessThread = new Thread(new ParameterizedThreadStart(ProcessFiles));
_fileNameProcessThread.IsBackground = true;
_fileNameProcessThread.Start(_appSettings);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show(@"Are you sure you want to stop the operation?", Caption, MessageBoxButton.YesNo, MessageBoxImage.Stop, MessageBoxResult.No)
== MessageBoxResult.No)
return;
using (new ChoWPFWaitCursor())
{
Thread.Sleep(1000);
ChoRoboCopyManager roboCopyManager = _roboCopyManager;
if (roboCopyManager != null)
roboCopyManager.Cancel();
Thread fileNameProcessorThread = _fileNameProcessThread;
if (fileNameProcessorThread != null)
{
try
{
fileNameProcessorThread.Abort();
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
}
_fileNameProcessThread = null;
}
}
}
private void btnSaveAsFile_Click(object sender, RoutedEventArgs e)
{
SaveSettings(true);
}
private void btnSaveFile_Click(object sender, RoutedEventArgs e)
{
SaveSettings(false);
}
private bool SaveSettings()
{
if (IsDirty)
{
string msg;
if (SettingsFilePath.IsNullOrWhiteSpace())
msg = "Do you want to save settings changes to untitled?";
else
msg = "Do you want to save settings changes to '{0}'?".FormatString(Path.GetFileName(SettingsFilePath));
MessageBoxResult r = MessageBox.Show(msg, Caption, MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
if (r == MessageBoxResult.Cancel)
return true;
else if (r == MessageBoxResult.No)
{
IsDirty = false;
return false;
}
else
return !SaveSettings(false);
}
return false;
}
private bool SaveSettings(bool newFile)
{
SaveDirectories();
if (newFile || SettingsFilePath.IsNullOrWhiteSpace())
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = AppHost.AppFileExt;
dlg.Filter = "EazyCopy files|*{0}".FormatString(AppHost.AppFileExt);
var result = dlg.ShowDialog();
if (result == true)
SettingsFilePath = dlg.FileName;
else
return false;
}
try
{
if (SettingsFilePath.IsNullOrWhiteSpace()) return true;
File.WriteAllText(SettingsFilePath, _appSettings.ToXml());
IsDirty = false;
return true;
}
catch (Exception ex)
{
MessageBox.Show("Failed saving settings to file. {0}".FormatString(ex.Message), Caption, MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
if (SaveSettings())
return;
OpenFileDialog dlg = new OpenFileDialog();
dlg.DefaultExt = AppHost.AppFileExt;
dlg.Filter = "EazyCopy files|*{0}".FormatString(AppHost.AppFileExt);
var result = dlg.ShowDialog();
if (result == true)
{
using (var x = new ChoWPFWaitCursor())
{
_isNewFileOp = true;
SettingsFilePath = dlg.FileName;
UnregisterEvents();
_appSettings.LoadXml(File.ReadAllText(SettingsFilePath));
RegisterEvents();
this.DataContext = null;
this.DataContext = this;
IsDirty = false;
_isNewFileOp = false;
}
}
}
private void btnNewFile_Click(object sender, RoutedEventArgs e)
{
if (SaveSettings())
return;
using (var x = new ChoWPFWaitCursor())
{
_isNewFileOp = true;
SettingsFilePath = null;
txtSourceDirectory.Text = String.Empty;
txtDestDirectory.Text = String.Empty;
UnregisterEvents();
_appSettings.Reset();
RegisterEvents();
this.DataContext = null;
this.DataContext = this;
IsDirty = false;
_isNewFileOp = false;
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtStatus.Text = String.Empty;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//_wndClosing = true;
if (IsRunning)
{
if (MessageBox.Show("File operation is in progress. Are you sure want to close the application?", Caption, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
return;
}
e.Cancel = SaveSettings();
if (!e.Cancel)
{
var up = new ChoUserPreferences();
if (RememberWindowSizeAndPosition)
{
up.WindowHeight = this.Height;
up.WindowWidth = this.Width;
up.WindowTop = this.Top;
up.WindowLeft = this.Left;
up.WindowState = this.WindowState;
}
up.RememberWindowSizeAndPosition = RememberWindowSizeAndPosition;
up.ScrollOutput = ScrollOutput;
up.Save();
}
}
private void txtRoboCopyCmd_TextChanged(object sender, TextChangedEventArgs e)
{
if (!_isNewFileOp)
IsDirty = true;
}
private void txtRoboCopyCmdEx_TextChanged(object sender, TextChangedEventArgs e)
{
if (!_isNewFileOp)
IsDirty = true;
}
private void RibbonWin_Loaded(object sender, RoutedEventArgs e)
{
Grid child = VisualTreeHelper.GetChild((DependencyObject)sender, 0) as Grid;
if (child != null)
{
child.RowDefinitions[0].Height = new GridLength(0);
child.RowDefinitions[1].Height = new GridLength(0);
}
}
private void BtnDonate_Click(object sender, RoutedEventArgs e)
{
string url = "https://www.paypal.com/cgi-bin/webscr" +
"?cmd=" + "_donations" +
"&business=" + "[email protected]" +
"&lc=" + "US" +
"&item_name=" + "ChoEazyCopy Donation" +
"¤cy_code=" + "USD" +
"&bn=" + "PP%2dDonationsBF";
System.Diagnostics.Process.Start(url);
}
}
public class BoolInverterConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
#endregion
}
public class MathConverter : IValueConverter
{
private static readonly char[] _allOperators = new[] { '+', '-', '*', '/', '%', '(', ')' };
private static readonly List<string> _grouping = new List<string> { "(", ")" };
private static readonly List<string> _operators = new List<string> { "+", "-", "*", "/", "%" };
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Parse value into equation and remove spaces
var mathEquation = parameter as string;
mathEquation = mathEquation.Replace(" ", "");
mathEquation = mathEquation.Replace("@VALUE", value.ToString());
// Validate values and get list of numbers in equation
var numbers = new List<double>();
double tmp;
foreach (string s in mathEquation.Split(_allOperators))
{
if (s != string.Empty)
{
if (double.TryParse(s, out tmp))
{
numbers.Add(tmp);
}
else
{
// Handle Error - Some non-numeric, operator, or grouping character found in string
throw new InvalidCastException();
}
}
}
// Begin parsing method
EvaluateMathString(ref mathEquation, ref numbers, 0);
// After parsing the numbers list should only have one value - the total
return numbers[0];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
// Evaluates a mathematical string and keeps track of the results in a List<double> of numbers
private void EvaluateMathString(ref string mathEquation, ref List<double> numbers, int index)
{
// Loop through each mathemtaical token in the equation
string token = GetNextToken(mathEquation);
while (token != string.Empty)
{
// Remove token from mathEquation
mathEquation = mathEquation.Remove(0, token.Length);
// If token is a grouping character, it affects program flow
if (_grouping.Contains(token))
{
switch (token)
{
case "(":
EvaluateMathString(ref mathEquation, ref numbers, index);
break;
case ")":
return;
}
}
// If token is an operator, do requested operation
if (_operators.Contains(token))
{
// If next token after operator is a parenthesis, call method recursively
string nextToken = GetNextToken(mathEquation);
if (nextToken == "(")
{
EvaluateMathString(ref mathEquation, ref numbers, index + 1);
}
// Verify that enough numbers exist in the List<double> to complete the operation
// and that the next token is either the number expected, or it was a ( meaning
// that this was called recursively and that the number changed
if (numbers.Count > (index + 1) &&
(double.Parse(nextToken) == numbers[index + 1] || nextToken == "("))
{
switch (token)
{
case "+":
numbers[index] = numbers[index] + numbers[index + 1];
break;
case "-":
numbers[index] = numbers[index] - numbers[index + 1];
break;
case "*":
numbers[index] = numbers[index] * numbers[index + 1];
break;
case "/":
numbers[index] = numbers[index] / numbers[index + 1];
break;
case "%":
numbers[index] = numbers[index] % numbers[index + 1];
break;
}
numbers.RemoveAt(index + 1);
}
else
{
// Handle Error - Next token is not the expected number
throw new FormatException("Next token is not the expected number");
}
}
token = GetNextToken(mathEquation);
}
}
// Gets the next mathematical token in the equation
private string GetNextToken(string mathEquation)
{
// If we're at the end of the equation, return string.empty
if (mathEquation == string.Empty)
{
return string.Empty;
}
// Get next operator or numeric value in equation and return it
string tmp = "";
foreach (char c in mathEquation)
{
if (_allOperators.Contains(c))
{
return (tmp == "" ? c.ToString() : tmp);
}
else
{
tmp += c;
}
}
return tmp;
}
}
}