-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathMainWindow.xaml.cs
1395 lines (1204 loc) · 54.3 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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace RoliSoft.TVShowTracker
{
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;
using TaskDialogInterop;
using RoliSoft.TVShowTracker.Remote;
using RoliSoft.TVShowTracker.Remote.Objects;
using RoliSoft.TVShowTracker.Dependencies.StartScreenColors;
using Drawing = System.Drawing;
using NotifyIcon = System.Windows.Forms.NotifyIcon;
using ContextMenu = System.Windows.Forms.ContextMenu;
using WinMenuItem = System.Windows.Forms.MenuItem;
using Timer = System.Timers.Timer;
using Application = System.Windows.Application;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
/// <summary>
/// Gets or sets the active main window.
/// </summary>
/// <value>The active main window.</value>
public static MainWindow Active { get; set; }
/// <summary>
/// Gets or sets the notify icon.
/// </summary>
/// <value>The notify icon.</value>
public static NotifyIcon NotifyIcon { get; set; }
public static readonly int WM_SHOWFIRSTINSTANCE = Utils.Interop.RegisterWindowMessage("WM_SHOWFIRSTINSTANCE|{0}", Signature.Software);
private Timer _statusTimer;
private static bool _initialized;
private bool _hideOnStart, _dieOnStart, _askUpdate, _askErrorUpdate, _isNightlyUpdate;
private Mutex _mutex;
private static ConcurrentDictionary<string, int> _exCnt = new ConcurrentDictionary<string, int>();
private static TaskScheduler _tssc;
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
// set global language and unhandled exception handler
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
Dispatcher.UnhandledException += (s, e) => { HandleUnexpectedException(e.Exception); e.Handled = true; };
AppDomain.CurrentDomain.UnhandledException += (s, e) => HandleUnexpectedException(e.ExceptionObject as Exception, e.IsTerminating);
TaskScheduler.UnobservedTaskException += (s, e) => { HandleUnexpectedException(e.Exception); e.SetObserved(); };
_tssc = TaskScheduler.FromCurrentSynchronizationContext();
// set up mutex so only one instance will run
var uniq = false;
_mutex = new Mutex(true, "Local\\" + Signature.Software, out uniq);
if (!uniq)
{
Utils.Interop.PostMessage((IntPtr)Utils.Interop.HWND_BROADCAST, WM_SHOWFIRSTINSTANCE, IntPtr.Zero, IntPtr.Zero);
Process.GetCurrentProcess().Kill();
return;
}
// check if the database is user writable
if (!Utils.IsUserWritable(Signature.InstallPath))
{
if (!Utils.IsAdmin)
{
// if not admin, elevate
_mutex.ReleaseMutex();
Utils.RunElevated(Assembly.GetExecutingAssembly().Location);
Process.GetCurrentProcess().Kill();
return;
}
else
{
// if admin, add permissions
if (!Utils.MakeUserWritable(Signature.InstallPath) || !Utils.IsUserWritable(Signature.InstallPath))
{
MessageBox.Show("Failed to add permissions to the database. You will most likely experience issues later during the execution of the software.", "Permission error", MessageBoxButton.OK, MessageBoxImage.Stop);
}
}
}
// if old database exists somewhere, update
if (File.Exists(Path.Combine(Signature.InstallPath, "TVShows.db3")) || File.Exists(Path.Combine(Signature.UACVirtualPath, "TVShows.db3")))
{
new TaskDialogs.DatabaseUpdateTaskDialog().Ask();
_dieOnStart = true;
}
// live a long and fulfilling life! unless told not to.
if (_dieOnStart)
{
Visibility = Visibility.Hidden;
return;
}
// handle command line arguments, if there are any
var args = Environment.GetCommandLineArgs();
if (args.Length != 1)
{
if (args.Contains("-hide"))
{
_hideOnStart = true;
}
if (args.Length == 2 && args[1][0] != '-' && File.Exists(args[1]))
{
var fid = FileNames.Parser.ParseFile(Path.GetFileName(args[1]), Path.GetDirectoryName(args[1]).Split(Path.DirectorySeparatorChar));
if (fid.Success)
{
TaskDialog.Show(new TaskDialogOptions
{
MainIcon = VistaTaskDialogIcon.Information,
Title = Signature.Software + " " + Signature.Version,
MainInstruction = Path.GetFileNameWithoutExtension(args[1]),
Content = fid + " – " + ShowNames.Regexes.PartText.Replace(fid.Title, string.Empty) + " – " + fid.Quality,
CustomButtons = new[] { "OK" }
});
}
else
{
TaskDialog.Show(new TaskDialogOptions
{
MainIcon = VistaTaskDialogIcon.Error,
Title = Signature.Software + " " + Signature.Version,
MainInstruction = Path.GetFileNameWithoutExtension(args[1]),
Content = "Couldn't identify the specified file.",
CustomButtons = new[] { "OK" }
});
}
Process.GetCurrentProcess().Kill();
}
}
// init interface
InitializeComponent();
}
/// <summary>
/// Runs the specified action in the UI thread.
/// </summary>
/// <param name="func">The action.</param>
public void Run(Action func)
{
Dispatcher.Invoke(func);
}
#region Window events
/// <summary>
/// Handles the SourceInitialized event of the Window control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void WindowSourceInitialized(object sender, EventArgs e)
{
HwndSource.FromHwnd((new WindowInteropHelper(this)).Handle).AddHook(new HwndSourceHook(WndProc));
if (_dieOnStart)
{
Visibility = Visibility.Hidden;
return;
}
if (Settings.Get("Enable Aero", true) && SystemParameters.IsGlassEnabled)
{
ActivateAero();
}
else
{
ActivateNonAero();
}
SystemParameters.StaticPropertyChanged += AeroChanged;
if (Settings.Get("Enable Animations", true))
{
ActivateAnimation();
}
else
{
DeactivateAnimation();
}
}
/// <summary>
/// Processes Windows messages.
/// </summary>
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_SHOWFIRSTINSTANCE)
{
Log.Debug("Received Windows message 0x{0:X}", new object[] { msg });
ShowMenuClick();
handled = true;
}
return IntPtr.Zero;
}
/// <summary>
/// Handles the Loaded event of the Window control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void WindowLoaded(object sender, RoutedEventArgs e)
{
if (_dieOnStart)
{
Visibility = Visibility.Hidden;
return;
}
Active = this;
BackgroundTasks.Start();
SetLastUpdated();
LoadNotifyIcon();
if (_hideOnStart)
{
// hiding the window when it isn't even visible is a tricky thing :]
// we wait for the next event, until then we make it inactive and -999px off the screen
var top = Top;
Top = -999;
ShowInTaskbar = ShowActivated = false;
ContentRendered += (s, r) =>
{
ShowMenuClick(s, r);
ShowInTaskbar = ShowActivated = true;
var t = new Timer { Interval = 1000, AutoReset = false, Enabled = true };
t.Elapsed += (d, y) => Run(() => { Top = top; });
};
}
Task.Factory.StartNew(() =>
{
var uf = Directory.GetFiles(Signature.InstallPath).Where(f => Path.GetFileName(f).StartsWith("update_") && f.EndsWith(".exe")).ToList();
if (uf.Count != 0)
{
var ver = Path.GetFileNameWithoutExtension(uf[0]).Replace("update_", string.Empty);
if (Version.Parse(ver) <= Version.Parse(Signature.Version) || new FileInfo(Path.Combine(Signature.InstallPath, uf[0])).Length == 0)
{
try { File.Delete(Path.Combine(Signature.InstallPath, uf[0])); } catch { }
}
else
{
Run(() => UpdateDownloaded(ver, true));
return;
}
}
Thread.Sleep(5000);
CheckForUpdate();
});
Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
Signature.ActivationTask.Wait();
if (Signature.IsActivated)
{
Run(() =>
{
ReindexDownloadPaths.IsEnabled = false;
if (_statusTimer != null)
{
_statusTimer.Stop();
}
lastUpdatedLabel.Content = "indexing download paths";
});
try
{
Library.Initialize();
}
catch (Exception ex)
{
HandleUnexpectedException(ex);
}
}
if (Signature.IsActivated && Settings.Get<bool>("Enable UPnP AV Media Server"))
{
try
{
UPnP.Start();
}
catch (Exception ex)
{
HandleUnexpectedException(ex);
}
}
Run(() =>
{
if (Signature.IsActivated)
{
ReindexDownloadPaths.IsEnabled = true;
}
SetLastUpdated();
});
});
_initialized = true;
foreach (var plugin in Extensibility.GetNewInstances<StartupPlugin>())
{
plugin.Run();
}
}
/// <summary>
/// This method is called when a system parameter from <c>SystemParameters2</c> is changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
public void AeroChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsGlassEnabled" && Settings.Get("Enable Aero", true))
{
Run(() =>
{
if (SystemParameters.IsGlassEnabled)
{
ActivateAero();
}
else
{
ActivateNonAero();
}
});
}
}
/// <summary>
/// Activates the aero interface.
/// </summary>
public void ActivateAero()
{
WindowChrome.SetWindowChrome(this, new WindowChrome { GlassFrameThickness = new Thickness(-1) });
Background = Brushes.Transparent;
logoImage.Source = new BitmapImage(new Uri("/RSTVShowTracker;component/Images/tv.png", UriKind.Relative));
logoLabel.Content = "RS TV Show Tracker v2";
logoMenu.Width = 157;
logo.Width = 160;
logo.CornerRadius = new CornerRadius(0, 0, 4, 4);
lastUpdatedLabel.Margin = new Thickness(165, -6, 0, 0);
}
/// <summary>
/// Activates the non-aero interface.
/// </summary>
public void ActivateNonAero()
{
WindowChrome.SetWindowChrome(this, null);
if (Utils.IsMetro)
{
Background = new SolidColorBrush(StarScreenColorsHelper.GetColor(ImmersiveColors.ImmersiveStartBackground));
}
else
{
Background = new SolidColorBrush(Color.FromArgb(Drawing.SystemColors.ControlDark.A, Drawing.SystemColors.ControlDark.R, Drawing.SystemColors.ControlDark.G, Drawing.SystemColors.ControlDark.B));
}
logoImage.Source = new BitmapImage(new Uri("/RSTVShowTracker;component/Images/list.png", UriKind.Relative));
logoLabel.Content = "Main Menu";
logoMenu.Width = 97;
logo.Width = 100;
logo.CornerRadius = new CornerRadius(3, 3, 4, 4);
lastUpdatedLabel.Margin = new Thickness(105, -6, 0, 0);
}
/// <summary>
/// Activates the animation of tab controls.
/// </summary>
public void ActivateAnimation()
{
tabControl.ContentTemplate = activeGuidesPage.tabControl.ContentTemplate = (DataTemplate)FindResource("TabTemplate");
}
/// <summary>
/// Deactivates the animation of tab controls.
/// </summary>
public void DeactivateAnimation()
{
tabControl.ContentTemplate = activeGuidesPage.tabControl.ContentTemplate = null;
}
/// <summary>
/// Handles the KeyUp event of the Window control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
private void WindowKeyUp(object sender, KeyEventArgs e)
{
// on F5 refresh the current user control
if (e.Key == Key.F5)
{
DataChanged();
}
// if the overview page is selected, send any keys to the listview
if (tabControl.SelectedIndex == 0)
{
activeOverviewPage.ListViewKeyUp(sender, e);
}
}
/// <summary>
/// Handles the IsVisibleChanged event of the Window control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private void WindowIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (IsVisible && _askUpdate && updateOuter.Visibility == Visibility.Visible)
{
_askUpdate = false;
UpdateDownloaded((string)update.Tag, true);
}
else if (IsVisible && _askErrorUpdate && updateOuter.Visibility == Visibility.Visible)
{
_askErrorUpdate = false;
UpdateIOError((string)update.Tag);
}
}
/// <summary>
/// Handles the Closing event of the Window control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="CancelEventArgs"/> instance containing the event data.</param>
private void WindowClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
ShowMenuClick(null, e);
}
#endregion
#region Miscellaneous
/// <summary>
/// Called when data is changed in the database.
/// </summary>
/// <param name="invokeRefresh">if set to <c>true</c> it will try to invoke the <c>Refresh()</c> method of the active user control.</param>
public void DataChanged(bool invokeRefresh = true)
{
Database.DataChange = DateTime.Now;
Log.Debug("Invalidating data caches" + (invokeRefresh ? " and requesting refresh" : string.Empty) + ".");
if (invokeRefresh)
{
Run(() =>
{
if (tabControl.SelectedContent is IRefreshable)
{
(tabControl.SelectedContent as IRefreshable).Refresh();
}
});
}
}
/// <summary>
/// Restarts the application. Microsoft forgot to implement <c>Application.Restart()</c> for WPF...
/// </summary>
public void Restart()
{
Log.Info("The application is silently restarting.");
Application.Current.Dispatcher.Invoke((Action)(() =>
{
NotifyIcon.Visible = false;
Application.Current.Exit += (sender, e) => Process.Start(Application.ResourceAssembly.Location, "-hide");
Application.Current.Shutdown();
}));
}
#endregion
#region Notify icon
/// <summary>
/// Loads the notify icon.
/// </summary>
private void LoadNotifyIcon()
{
var menu = new ContextMenu();
NotifyIcon = new NotifyIcon
{
Text = "RS TV Show Tracker",
Icon = new Drawing.Icon(Application.GetResourceStream(new Uri("pack://application:,,,/RSTVShowTracker;component/tv.ico")).Stream),
Visible = true,
ContextMenu = menu
};
var showMenu = new WinMenuItem { Text = "Hide" };
showMenu.Click += ShowMenuClick;
var exitMenu = new WinMenuItem { Text = "Exit" };
exitMenu.Click += (s, r) =>
{
NotifyIcon.Visible = false;
//Application.Current.Shutdown();
Process.GetCurrentProcess().Kill(); // this would be more *aggressive* I guess
};
menu.MenuItems.Add(showMenu);
menu.MenuItems.Add(exitMenu);
NotifyIcon.DoubleClick += (s, e) => showMenu.PerformClick();
}
/// <summary>
/// Handles the Click event of the showMenu control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public void ShowMenuClick(object sender = null, EventArgs e = null)
{
if (Visibility == Visibility.Visible)
{
Hide();
NotifyIcon.ContextMenu.MenuItems[0].Text = "Show";
}
else if (NotifyIcon.Visible && !(e is CancelEventArgs))
{
Show();
Activate();
NotifyIcon.ContextMenu.MenuItems[0].Text = "Hide";
}
}
#endregion
#region Logo
/// <summary>
/// Sets the status to the last updated time.
/// </summary>
public void SetLastUpdated(object sender = null, System.Timers.ElapsedEventArgs e = null)
{
if (_statusTimer == null)
{
_statusTimer = new Timer();
_statusTimer.Elapsed += SetLastUpdated;
}
else
{
_statusTimer.Stop();
}
var last = Database.Setting("update");
if (string.IsNullOrEmpty(last))
{
Run(() => { lastUpdatedLabel.Content = string.Empty; });
return;
}
var ts = DateTime.Now - last.ToDouble().GetUnixTimestamp();
Run(() => { lastUpdatedLabel.Content = "last updated " + ts.ToShortRelativeTime() + " ago"; });
if (ts.TotalMinutes < 1) // if under a minute, update by seconds
{
_statusTimer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
}
else if (ts.TotalHours < 1) // if under an hour, update by minutes
{
_statusTimer.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds;
}
else // if more than an hour, update by hours
{
_statusTimer.Interval = TimeSpan.FromHours(1).TotalMilliseconds;
}
_statusTimer.Start();
}
/// <summary>
/// Sets the width of the progress bar in the header.
/// </summary>
/// <param name="value">The value.</param>
public void SetHeaderProgress(double value)
{
progressRectangle.BeginAnimation(OpacityProperty, new DoubleAnimation
{
To = value / 100,
Duration = TimeSpan.FromMilliseconds(500),
AccelerationRatio = 1
});
}
/// <summary>
/// Handles the MouseEnter event of the logo control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Input.MouseEventArgs"/> instance containing the event data.</param>
private void LogoMouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
logo.Background = (Brush)FindResource("HeadGradientHover");
logo.BorderBrush = Brushes.Gray;
}
/// <summary>
/// Handles the MouseLeave event of the logo control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Input.MouseEventArgs"/> instance containing the event data.</param>
private void LogoMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
logo.Background = (Brush)FindResource("HeadGradient" + (logoMenuItem.IsSubmenuOpen ? "Hover" : string.Empty));
logo.BorderBrush = logoMenuItem.IsSubmenuOpen ? Brushes.Gray : Brushes.DimGray;
}
/// <summary>
/// Handles the MouseLeftButtonUp event of the logo control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
private void LogoMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
logoMenuItem.IsSubmenuOpen = true;
}
private CancellationTokenSource _supportArrowCts = null;
/// <summary>
/// Handles the SubmenuClosed event of the logoMenuItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void LogoMenuItemSubmenuClosed(object sender, RoutedEventArgs e)
{
logo.Background = (Brush)FindResource("HeadGradient");
logo.BorderBrush = Brushes.DimGray;
if (_supportArrowCts != null && !_supportArrowCts.IsCancellationRequested)
{
_supportArrowCts.Cancel();
}
}
/// <summary>
/// Handles the SubmenuOpened event of the logoMenuItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void LogoMenuItemSubmenuOpened(object sender, RoutedEventArgs e)
{
supportArrow.Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/" + (Signature.IsActivated ? "smiley-cool" : "smiley") + ".png"));
if (_supportArrowCts != null && !_supportArrowCts.IsCancellationRequested)
{
_supportArrowCts.Cancel();
}
_supportArrowCts = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
start:
if (_supportArrowCts.IsCancellationRequested) return;
_supportArrowCts.Token.WaitHandle.WaitOne(1000);
if (_supportArrowCts.IsCancellationRequested) return;
Dispatcher.Invoke((Action)(() =>
{
if (logoMenuItem.IsSubmenuOpen)
{
supportArrow.Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/" + (Signature.IsActivated ? "thumb-up" : "smiley-wink") + ".png"));
}
else
{
if (_supportArrowCts != null && !_supportArrowCts.IsCancellationRequested)
{
_supportArrowCts.Cancel();
}
}
}));
if (_supportArrowCts.IsCancellationRequested) return;
_supportArrowCts.Token.WaitHandle.WaitOne(1000);
if (_supportArrowCts.IsCancellationRequested) return;
Dispatcher.Invoke((Action)(() =>
{
if (logoMenuItem.IsSubmenuOpen)
{
supportArrow.Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/" + (Signature.IsActivated ? "smiley-cool" : "smiley") + ".png"));
}
else
{
if (_supportArrowCts != null && !_supportArrowCts.IsCancellationRequested)
{
_supportArrowCts.Cancel();
}
}
}));
if (_supportArrowCts.IsCancellationRequested) return;
_supportArrowCts.Token.WaitHandle.WaitOne(5000);
if (_supportArrowCts.IsCancellationRequested) return;
var jump = false;
Dispatcher.Invoke((Action)(() => jump = logoMenuItem.IsSubmenuOpen));
if (jump)
{
goto start;
}
else
{
if (_supportArrowCts != null && !_supportArrowCts.IsCancellationRequested)
{
_supportArrowCts.Cancel();
}
}
}, _supportArrowCts.Token);
}
#endregion
#region Main menu
/// <summary>
/// Handles the Click event of the ReindexDownloadPaths control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
public void ReindexDownloadPathsClick(object sender = null, RoutedEventArgs e = null)
{
if (!Signature.IsActivated || !ReindexDownloadPaths.IsEnabled)
{
return;
}
if (_statusTimer != null)
{
_statusTimer.Stop();
}
lastUpdatedLabel.Content = "indexing download paths";
ReindexDownloadPaths.IsEnabled = false;
new Task(() =>
{
Library.Initialize();
Run(() =>
{
ReindexDownloadPaths.IsEnabled = true;
SetLastUpdated();
});
}).Start();
}
/// <summary>
/// Handles the Click event of the UpdateDatabase control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
public void UpdateDatabaseClick(object sender = null, RoutedEventArgs e = null)
{
_statusTimer.Stop();
UpdateDatabase.IsEnabled = false;
var updater = new Updater();
updater.UpdateProgressChanged += UpdateProgressChanged;
updater.UpdateDone += UpdateDone;
updater.UpdateError += UpdateError;
updater.UpdateAsync();
}
private LogWindow _logWnd;
/// <summary>
/// Handles the Click event of the ViewSoftwareLogs control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void ViewSoftwareLogsClick(object sender, RoutedEventArgs e)
{
if (_logWnd == null || !_logWnd.IsVisible)
{
_logWnd = new LogWindow();
_logWnd.Show();
}
else
{
_logWnd.Activate();
}
}
/// <summary>
/// Handles the Click event of the MinimizeToTray control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void MinimizeToTrayClick(object sender, RoutedEventArgs e)
{
ShowMenuClick(null, null);
}
/// <summary>
/// Handles the Click event of the OpenHelpPage control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void OpenHelpPageClick(object sender, RoutedEventArgs e)
{
Utils.Run("http://lab.rolisoft.net/tvshowtracker/help.html");
}
/// <summary>
/// Handles the Click event of the SupportSoftware control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void SupportSoftwareClick(object sender, RoutedEventArgs e)
{
//Utils.Run("http://lab.rolisoft.net/tvshowtracker/donate.html");
new SupportWindow().ShowDialog();
}
/// <summary>
/// Handles the Click event of the AboutSoftware control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void AboutSoftwareClick(object sender, RoutedEventArgs e)
{
new AboutWindow().ShowDialog();
}
/// <summary>
/// Handles the Click event of the ConfigureSoftware control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void ConfigureSoftwareClick(object sender, RoutedEventArgs e)
{
new SettingsWindow().ShowDialog();
}
/// <summary>
/// Handles the Click event of the AddNewTVShow control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void AddNewTVShowClick(object sender, RoutedEventArgs e)
{
new AddNewWindow().ShowDialog();
}
/// <summary>
/// Handles the Click event of the RenamerSoftware control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void RenameVideoFilesClick(object sender, RoutedEventArgs e)
{
new RenamerWindow().Show();
}
/// <summary>
/// Handles the Click event of the SocialNetworks control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void SocialNetworksClick(object sender, RoutedEventArgs e)
{
new SocialWindow().Show();
}
/// <summary>
/// Handles the Click event of the SendFeedback control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void SendFeedbackClick(object sender, RoutedEventArgs e)
{
new SendFeedbackWindow().ShowDialog();
}
/// <summary>
/// Handles the Click event of the ExitSoftware control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void ExitSoftwareClick(object sender, RoutedEventArgs e)
{
NotifyIcon.ContextMenu.MenuItems[1].PerformClick();
}
#endregion
#region Database update
/// <summary>
/// Called when the update is done.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public void UpdateDone(object sender, EventArgs e)
{
Utils.Win7Taskbar(state: TaskbarProgressBarState.NoProgress);
Run(() =>
{
UpdateDatabase.IsEnabled = true;
SetLastUpdated();
SetHeaderProgress(0);
});
}
/// <summary>
/// Called when the update has encountered an error.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
public void UpdateError(object sender, EventArgs<string, Exception, bool, bool> e)
{
if (e.Second != null && !(e.Second is WebException))
{
HandleUnexpectedException(e.Second);
}
if (e.Fourth) // fatal to whole update
{
Utils.Win7Taskbar(state: TaskbarProgressBarState.NoProgress);
Run(() =>
{
UpdateDatabase.IsEnabled = true;
lastUpdatedLabel.Content = "update failed";
SetHeaderProgress(0);
});
}
}
/// <summary>
/// Called when the progress has changed on the update.
/// </summary>
public void UpdateProgressChanged(object sender, EventArgs<string, double> e)
{
Utils.Win7Taskbar((int)e.Second, TaskbarProgressBarState.Normal);