-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathMainWindow.xaml.cs
1390 lines (1213 loc) · 49.7 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
/**
* Copyright (C) 2023 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XiboClient.Action;
using XiboClient.Adspace;
using XiboClient.Error;
using XiboClient.Log;
using XiboClient.Logic;
using XiboClient.Rendering;
using XiboClient.Stats;
namespace XiboClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// Schedule Class
/// </summary>
private Schedule _schedule;
/// <summary>
/// Schedule Change Lock
/// </summary>
public static object _scheduleLocker = new object();
/// <summary>
/// Overlay Regions
/// </summary>
private Collection<Layout> _overlays;
/// <summary>
/// The Currently Running Layout
/// </summary>
private Layout currentLayout;
/// <summary>
/// Are we in screensaver mode?
/// </summary>
private bool _screenSaver = false;
/// <summary>
/// Splash Screen Logic
/// </summary>
private bool _showingSplash = false;
private System.Windows.Controls.Image splashScreen;
/// <summary>
/// The InfoScreen
/// </summary>
private InfoScreen infoScreen;
#region DLL Imports
[FlagsAttribute]
enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
#endregion
/// <summary>
/// Initialise Player
/// </summary>
/// <param name="screenSaver"></param>
public MainWindow(bool screenSaver)
{
// Set the Cache Manager
CacheManager.Instance.SetCacheManager();
InitializeComponent();
if (screenSaver)
{
InitializeScreenSaver();
}
InitializeXibo();
}
/// <summary>
/// Initialise Xibo
/// </summary>
private void InitializeXibo()
{
// Set the title
Title = ApplicationSettings.GetProductNameFromAssembly();
// Check the directories exist
if (!Directory.Exists(ApplicationSettings.Default.LibraryPath + @"\backgrounds\"))
{
// Will handle the create of everything here
Directory.CreateDirectory(ApplicationSettings.Default.LibraryPath + @"\backgrounds");
}
// Default the XmdsConnection
ApplicationSettings.Default.XmdsLastConnection = DateTime.MinValue;
// Bind to the resize event
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
// Show in taskbar
ShowInTaskbar = ApplicationSettings.Default.ShowInTaskbar;
// Events
Loaded += MainWindow_Loaded;
Closing += MainForm_FormClosing;
ContentRendered += MainForm_Shown;
MouseInterceptor.Instance.MouseClickEvent += MouseInterceptor_MouseClickEvent;
// Trace listener for Client Info
ClientInfoTraceListener clientInfoTraceListener = new ClientInfoTraceListener
{
Name = "ClientInfo TraceListener"
};
Trace.Listeners.Add(clientInfoTraceListener);
// Log to disk?
if (!string.IsNullOrEmpty(ApplicationSettings.Default.LogToDiskLocation))
{
TextWriterTraceListener listener = new TextWriterTraceListener(ApplicationSettings.Default.LogToDiskLocation);
Trace.Listeners.Add(listener);
}
#if !DEBUG
// Initialise the watchdog
if (!_screenSaver)
{
try
{
// Update/write the status.json file
ClientInfo.Instance.UpdateStatusMarkerFile();
// Start watchdog
XiboClient.Control.WatchDogManager.Start();
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("MainForm - InitializeXibo", "Cannot start watchdog. E = " + e.Message), LogType.Error.ToString());
}
}
#endif
// An empty set of overlays
_overlays = new Collection<Layout>();
// Switch to TLS 2.1
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
// Initialise the database
StatManager.Instance.InitDatabase();
Trace.WriteLine(new LogMessage("MainForm", "Player Initialised"), LogType.Info.ToString());
}
/// <summary>
/// Initialise the Screen Saver
/// </summary>
private void InitializeScreenSaver()
{
_screenSaver = true;
// Indicate to the KeyStore that we are a scrensaver
KeyStore.Instance.ScreenSaver = true;
// Mouse Move
MouseInterceptor.Instance.MouseMoveEvent += MouseInterceptor_MouseMoveEvent;
}
/// <summary>
/// Mouse Move Event
/// </summary>
private void MouseInterceptor_MouseMoveEvent()
{
if (_screenSaver)
{
if (System.Windows.Application.Current != null)
{
System.Windows.Application.Current.Shutdown();
}
}
}
/// <summary>
/// Mouse Click Event
/// </summary>
/// <param name="point"></param>
private void MouseInterceptor_MouseClickEvent(System.Drawing.Point point)
{
if (_screenSaver)
{
System.Windows.Application.Current.Shutdown();
}
else if (!(point.X < Left || point.X > Width + Left || point.Y < Top || point.Y > Height + Top))
{
Debug.WriteLine("Inside Player: " + point.X + "," + point.Y
+ ". Player: " + Left + "," + Top + ". " + Width + "x" + Height, "MouseInterceptor_MouseClickEvent");
// Rebase to Player dimensions and pass to Handle
HandleActionTrigger("touch", "", 0, new Point
{
X = point.X - Left,
Y = point.Y - Top
});
}
}
/// <summary>
/// Handle the Key Event
/// </summary>
/// <param name="name"></param>
void Instance_KeyPress(string name)
{
Debug.WriteLine("KeyPress " + name);
if (name == "ClientInfo")
{
if (this.infoScreen == null)
{
#if !DEBUG
// Make our window not topmost so that we can see the info screen
if (!_screenSaver)
{
Topmost = false;
}
#endif
this.infoScreen = new InfoScreen();
this.infoScreen.Closed += InfoScreen_Closed;
this.infoScreen.Show();
}
else
{
this.infoScreen.Close();
#if !DEBUG
// Bring the window back to Topmost if we need to
if (!_screenSaver)
{
Topmost = true;
}
#endif
}
}
else if (name == "ScreenSaver")
{
Debug.WriteLine("Closing due to ScreenSaver key press");
if (!_screenSaver)
return;
System.Windows.Application.Current.Shutdown();
}
}
/// <summary>
/// InfoScreen Closed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void InfoScreen_Closed(object sender, EventArgs e)
{
this.infoScreen.Closed -= InfoScreen_Closed;
this.infoScreen = null;
}
/// <summary>
/// main window loding event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// Set the Main Window Size
SetMainWindowSize();
// Is the mouse enabled?
if (!ApplicationSettings.Default.EnableMouse)
{
// Hide the cursor
Mouse.OverrideCursor = System.Windows.Input.Cursors.None;
}
// Move the cursor to the starting place
if (!_screenSaver)
{
SetCursorStartPosition();
}
// Show the splash screen
ShowSplashScreen(0);
// Change the default Proxy class
OptionsForm.SetGlobalProxy();
// Define the hotkey
Keys key;
try
{
key = (Keys)Enum.Parse(typeof(Keys), ApplicationSettings.Default.ClientInformationKeyCode.ToUpper());
}
catch
{
// Default back to I
key = Keys.I;
}
KeyStore.Instance.AddKeyDefinition("ClientInfo", key, ((ApplicationSettings.Default.ClientInfomationCtrlKey) ? Keys.Control : Keys.None));
// Register a handler for the key event
KeyStore.Instance.KeyPress += Instance_KeyPress;
// UserApp data
Debug.WriteLine(new LogMessage("MainForm_Load", "User AppData Path: " + ApplicationSettings.Default.LibraryPath), LogType.Info.ToString());
// Initialise CEF
CefSharp.CefSharpSettings.SubprocessExitIfParentProcessClosed = true;
// Settings for Init
CefSharp.Wpf.CefSettings settings = new CefSharp.Wpf.CefSettings
{
RootCachePath = ApplicationSettings.Default.LibraryPath + @"\CEF",
CachePath = ApplicationSettings.Default.LibraryPath + @"\CEF",
LogFile = ApplicationSettings.Default.LibraryPath + @"\CEF\cef.log",
LogSeverity = CefSharp.LogSeverity.Fatal,
};
settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";
settings.CefCommandLineArgs["disable-pinch"] = "1";
settings.CefCommandLineArgs["disable-usb-keyboard-detect"] = "1";
CefSharp.Cef.Initialize(settings);
}
/// <summary>
/// Called after the form has been shown
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void MainForm_Shown(object sender, EventArgs e)
{
try
{
// Create the Schedule
_schedule = new Schedule(ApplicationSettings.Default.LibraryPath + @"\" + ApplicationSettings.Default.ScheduleFile);
// Bind to the schedule change event - notifys of changes to the schedule
_schedule.ScheduleChangeEvent += ScheduleChangeEvent;
// Bind to the overlay change event
_schedule.OverlayChangeEvent += ScheduleOverlayChangeEvent;
// Bind to the trigger received event
_schedule.OnTriggerReceived += HandleActionTrigger;
// Initialize the other schedule components
_schedule.InitializeComponents();
// Set this form to topmost
#if !DEBUG
if (!_screenSaver)
Topmost = true;
#endif
}
catch (Exception ex)
{
LogMessage.Error("MainForm", "MainForm_Shown", "Cannot initialise the application, unexpected exception." + ex.Message);
LogMessage.Error("MainForm", "MainForm_Shown", ex.StackTrace.ToString());
System.Windows.MessageBox.Show("Fatal Error initialising the application. " + ex.Message + ", " + ex.StackTrace.ToString(), "Fatal Error");
Close();
}
}
/// <summary>
/// Called as the Main Form starts to close
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_FormClosing(object sender, CancelEventArgs e)
{
// We want to tidy up some stuff as this form closes.
Trace.Listeners.Remove("ClientInfo TraceListener");
try
{
// Close the client info screen
if (this.infoScreen != null)
{
this.infoScreen.Close();
}
// Stop the schedule object
if (_schedule != null)
{
_schedule.Stop();
_schedule.OnTriggerReceived -= HandleActionTrigger;
}
// Write the CacheManager to disk
CacheManager.Instance.WriteCacheManager();
}
catch (NullReferenceException)
{
// Stopped before we really started, nothing to do
}
// Flush the logs
Trace.Flush();
}
/// <summary>
/// Handles the ScheduleChange event
/// </summary>
/// <param name="nextLayout"></param>
void ScheduleChangeEvent(ScheduleItem nextLayout)
{
// We can only process 1 schedule change at a time.
lock (_scheduleLocker)
{
Trace.WriteLine(new LogMessage("MainForm",
string.Format("ScheduleChangeEvent: Schedule Changing to Schedule {0}, Layout {1}", nextLayout.scheduleid, nextLayout.id)), LogType.Audit.ToString());
// Issue a change to the next Layout
Dispatcher.Invoke(new Action<ScheduleItem>(ChangeToNextLayout), nextLayout);
}
}
/// <summary>
/// Change to the next layout
/// <param name="scheduleItem"></param>
/// </summary>
private void ChangeToNextLayout(ScheduleItem scheduleItem)
{
Debug.WriteLine("ChangeToNextLayout: called", "MainWindow");
if (ApplicationSettings.Default.PreventSleep)
{
try
{
SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
}
catch
{
Trace.WriteLine(new LogMessage("MainForm - ChangeToNextLayout", "Unable to set Thread Execution state"), LogType.Info.ToString());
}
}
try
{
// Stop the Current Layout
try
{
if (this.currentLayout != null)
{
// Check to see if this Layout was a Layout Change Action that we can mark as being played
if (this.currentLayout.ScheduleItem.Override)
{
if (_schedule.NotifyLayoutActionFinished(this.currentLayout.ScheduleItem))
{
Debug.WriteLine("ChangeToNextLayout: not changing this time, because the current layout finishing will result in a schedule change.", "MainWindow");
return;
}
}
Debug.WriteLine("ChangeToNextLayout: stopping the current Layout", "MainWindow");
this.currentLayout.Stop();
Debug.WriteLine("ChangeToNextLayout: stopped and removed the current Layout: " + this.currentLayout.UniqueId, "MainWindow");
this.currentLayout = null;
}
}
catch (Exception e)
{
// Force collect all controls
this.Scene.Children.Clear();
Trace.WriteLine(new LogMessage("MainForm", "ChangeToNextLayout: Destroy Layout Failed. Exception raised was: " + e.Message), LogType.Info.ToString());
}
// Prepare the next layout
try
{
this.currentLayout = PrepareLayout(scheduleItem);
// We have loaded a layout background and therefore are no longer showing the splash screen
// Remove the Splash Screen Image
RemoveSplashScreen();
// Start the Layout.
StartLayout(this.currentLayout);
}
catch (ShowSplashScreenException)
{
// Pass straight out to show the splash screen
throw;
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("MainForm", "ChangeToNextLayout: Prepare/Start Layout Failed. Exception raised was: " + e.Message), LogType.Info.ToString());
// Remove the Layout again
if (this.currentLayout != null)
{
DestroyLayout(this.currentLayout);
}
// Pass out
throw;
}
}
catch (ShowSplashScreenException)
{
// Specifically asked to show the splash screen.
if (!_showingSplash)
{
ShowSplashScreen(10);
}
}
catch (Exception ex)
{
// Store the active layout count, so that we can remove this one that failed and still see if there is another to try
int activeLayouts = _schedule.ActiveLayouts;
if (scheduleItem.IsAdspaceExchange)
{
LogMessage.Audit("MainForm", "ChangeToNextLayout", "No ad to show, e: " + ex.Message);
}
else
{
LogMessage.Info("MainForm", "ChangeToNextLayout", "Layout Change to " + scheduleItem.layoutFile + " failed. Exception raised was: " + ex.Message);
// We could not prepare or start this Layout, so we ought to remove it from the Schedule.
_schedule.RemoveLayout(scheduleItem);
}
// Do we have more than one Layout in our Schedule which we can try?
// and make sure they aren't solely AXE
if (activeLayouts > 1 && activeLayouts > _schedule.ActiveAdspaceExchangeEvents)
{
_schedule.NextLayout();
}
else if (scheduleItem != _schedule.GetDefaultLayout() && !_schedule.GetDefaultLayout().IsSplash())
{
// Can we show the default layout?
try
{
currentLayout = PrepareLayout(_schedule.GetDefaultLayout());
// We have loaded a layout background and therefore are no longer showing the splash screen
// Remove the Splash Screen Image
RemoveSplashScreen();
// Start the Layout.
StartLayout(this.currentLayout);
}
catch
{
Trace.WriteLine(new LogMessage("MainForm", "ChangeToNextLayout: Failed to show the default layout. Exception raised was: " + ex.Message), LogType.Error.ToString());
ShowSplashScreen(10);
}
}
else
{
ShowSplashScreen(10);
}
}
}
/// <summary>
/// Start a Layout
/// </summary>
/// <param name="layout"></param>
private void StartLayout(Layout layout)
{
Debug.WriteLine("StartLayout: Starting...", "MainWindow");
// Bind to Layout finished
layout.OnLayoutStopped += Layout_OnLayoutStopped;
// Match Background Colors
this.Background = layout.BackgroundColor;
// Add this Layout to our controls
this.Scene.Children.Add(layout);
// Start
if (!layout.IsRunning)
{
Debug.WriteLine("StartLayout: Starting Layout", "MainWindow");
layout.Start();
}
else
{
Trace.WriteLine(new LogMessage("MainForm", "StartLayout: Layout already running."), LogType.Error.ToString());
return;
}
Debug.WriteLine("StartLayout: Started Layout", "MainWindow");
// Update client info
ClientInfo.Instance.CurrentLayoutId = layout.ScheduleItem.id;
ClientInfo.Instance.CurrentlyPlaying = layout.ScheduleItem.layoutFile;
ClientInfo.Instance.ControlCount = this.Scene.Children.Count;
// Do we need to notify?
try
{
if (ApplicationSettings.Default.SendCurrentLayoutAsStatusUpdate)
{
using (xmds.xmds statusXmds = new xmds.xmds())
{
statusXmds.Url = ApplicationSettings.Default.XiboClient_xmds_xmds + "&method=notifyStatus";
statusXmds.NotifyStatusAsync(ApplicationSettings.Default.ServerKey, ApplicationSettings.Default.HardwareKey, "{\"currentLayoutId\":" + this.currentLayout.ScheduleItem.id + "}");
}
}
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("MainForm", "StartLayout: Notify Status Failed. Exception raised was: " + e.Message), LogType.Info.ToString());
throw;
}
}
/// <summary>
/// Expire the Splash Screen
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void splashScreenTimer_Tick(object sender, EventArgs e)
{
DispatcherTimer timer = (DispatcherTimer)sender;
timer.Stop();
if (_showingSplash)
{
Debug.WriteLine(new LogMessage("timer_Tick", "Loading next layout after splashscreen"));
// Put the next Layout up
_schedule.NextLayout();
}
}
/// <summary>
/// Prepares the Layout.. rendering all the necessary controls
/// </summary>
/// <param name="scheduleItem"></param>
/// <returns></returns>
private Layout PrepareLayout(ScheduleItem scheduleItem)
{
// Default or not
if (scheduleItem.IsSplash() || string.IsNullOrEmpty(scheduleItem.layoutFile))
{
throw new ShowSplashScreenException();
}
else if (CacheManager.Instance.IsUnsafeLayout(scheduleItem.id))
{
throw new LayoutInvalidException("Unsafe Layout");
}
else
{
try
{
// Construct a new Current Layout
Layout layout = new Layout
{
Width = Width,
Height = Height,
Schedule = _schedule
};
// Is this an Adspace Exchange Layout?
if (scheduleItem.IsAdspaceExchange)
{
// Get an ad
Ad ad = _schedule.GetAd(Width, Height, false, null);
if (ad == null)
{
throw new LayoutInvalidException("No ad to play");
}
layout.LoadFromAd(scheduleItem, ad);
}
else
{
layout.LoadFromFile(scheduleItem);
}
return layout;
}
catch (IOException)
{
if (!scheduleItem.IsAdspaceExchange)
{
CacheManager.Instance.Remove(scheduleItem.layoutFile);
}
throw new LayoutInvalidException("IO Exception");
}
}
}
/// <summary>
/// Shows the splash screen (set the background to the embedded resource)
/// <paramref name="timeout"/>
/// </summary>
private void ShowSplashScreen(int timeout)
{
_showingSplash = true;
if (!string.IsNullOrEmpty(ApplicationSettings.Default.SplashOverride))
{
try
{
System.Windows.Controls.Image img = new System.Windows.Controls.Image()
{
Name = "Splash"
};
img.Source = new BitmapImage(new Uri(ApplicationSettings.Default.SplashOverride));
this.Scene.Children.Add(img);
}
catch
{
Trace.WriteLine(new LogMessage("ShowSplashScreen", "Unable to load user splash screen"), LogType.Error.ToString());
ShowDefaultSplashScreen();
}
}
else
{
ShowDefaultSplashScreen();
}
if (timeout > 0)
{
// In "timeout" seconds fire the next layout
DispatcherTimer timer = new DispatcherTimer()
{
Interval = new TimeSpan(0, 0, timeout)
};
timer.Tick += new EventHandler(splashScreenTimer_Tick);
timer.Start();
}
}
/// <summary>
/// Show the Default Splash Screen
/// </summary>
private void ShowDefaultSplashScreen()
{
Uri path = new Uri("pack://application:,,,/Resources/splash.jpg");
this.splashScreen = new System.Windows.Controls.Image()
{
Name = "Splash",
Source = new BitmapImage(path)
};
this.Scene.Children.Add(this.splashScreen);
}
/// <summary>
/// Remove the Splash Screen
/// </summary>
private void RemoveSplashScreen()
{
if (this.splashScreen != null)
{
this.Scene.Children.Remove(this.splashScreen);
}
// We've removed it
this._showingSplash = false;
}
/// <summary>
/// Event called when a Layout has been stopped
/// </summary>
private void Layout_OnLayoutStopped(Layout layout)
{
Debug.WriteLine("Layout_OnLayoutStopped: Layout completely stopped", "MainWindow");
DestroyLayout(layout);
}
/// <summary>
/// Disposes Layout - removes the controls
/// </summary>
private void DestroyLayout(Layout layout)
{
Debug.WriteLine("DestroyLayout: Destroying Layout", "MainWindow");
layout.Remove();
layout.OnLayoutStopped -= Layout_OnLayoutStopped;
this.Scene.Children.Remove(layout);
}
/// <summary>
/// Set the Cursor start position
/// </summary>
private void SetCursorStartPosition()
{
Point position;
switch (ApplicationSettings.Default.CursorStartPosition)
{
case "Top Left":
position = new Point(0, 0);
break;
case "Top Right":
position = new Point(Width, 0);
break;
case "Bottom Left":
position = new Point(0, Height);
break;
case "Bottom Right":
position = new Point(Width, Height);
break;
default:
// The default position or "unchanged" as it will be sent, is to not do anything
// leave the cursor where it is
return;
}
SetCursorPos((int)position.X, (int)position.Y);
}
/// <summary>
/// Overlay change event.
/// </summary>
/// <param name="overlays"></param>
void ScheduleOverlayChangeEvent(List<ScheduleItem> overlays)
{
Dispatcher.BeginInvoke(new Action<List<ScheduleItem>>(ManageOverlays), overlays);
}
/// <summary>
/// Manage Overlays
/// </summary>
/// <param name="overlays"></param>
public void ManageOverlays(List<ScheduleItem> overlays)
{
try
{
// Parse all overlays and compare what we have now to the overlays we have already created (see OverlayRegions)
Debug.WriteLine("Arrived at Manage Overlays with " + overlays.Count + " overlay schedules to show. We're already showing " + _overlays.Count + " overlay Regions", "Overlays");
// Take the ones we currently have up and remove them if they aren't in the new list or if they've been set to refresh
// We use a for loop so that we are able to remove the region from the collection
for (int i = 0; i < _overlays.Count; i++)
{
Debug.WriteLine("Assessing Overlay Region " + i, "Overlays");
Layout layout = _overlays[i];
bool found = false;
bool refresh = false;
foreach (ScheduleItem item in overlays)
{
if (item.scheduleid == layout.ScheduleId)
{
found = true;
refresh = item.Refresh;
break;
}
}
if (!found || refresh)
{
if (refresh)
{
Trace.WriteLine(new LogMessage("MainForm - ManageOverlays", "Refreshing item that has changed."), LogType.Info.ToString());
}
Debug.WriteLine("Removing overlay " + i + " which is no-longer required. Overlay: " + layout.ScheduleId, "Overlays");
// Remove the Layout from the overlays collection
_overlays.Remove(layout);
// As we've removed the thing we're iterating over, reduce i
i--;
// Clear down and dispose of the region.
layout.Stop();
layout.Remove();
this.OverlayScene.Children.Remove(layout);
}
else
{
Debug.WriteLine("Overlay Layout found and not needing refresh " + i, "Overlays");
}
}
// Take the ones that are in the new list and add them
foreach (ScheduleItem item in overlays)
{
// Check its not already added.
bool found = false;
foreach (Layout layout in _overlays)
{
if (layout.ScheduleId == item.scheduleid)
{
found = true;
break;
}
}
if (found)
{
Debug.WriteLine("Layout already found for overlay - we're assuming here that if we've found one, they are all there.", "Overlays");
continue;
}
// Reset refresh
item.Refresh = false;
// Parse the layout for regions, and create them.
try
{
Layout layout = PrepareLayout(item);
// Add to our collection of Overlays
_overlays.Add(layout);
// Add to the Scene
OverlayScene.Children.Add(layout);
// Start
layout.Start();
}
catch (ShowSplashScreenException)
{
// Unable to prepare this layout - log and move on
Trace.WriteLine(new LogMessage("MainForm - ManageOverlays", "Unable to Prepare Layout: " + item.layoutFile), LogType.Audit.ToString());
}
}
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("MainForm - _schedule_OverlayChangeEvent", "Unknown issue managing overlays. Ex = " + e.Message), LogType.Info.ToString());
}
}
/// <summary>
/// Get actions
/// </summary>
/// <returns></returns>
private List<Action.Action> GetActions()
{
List<Action.Action> actions = new List<Action.Action>();
// Pull actions from the main layout and any overlays
if (currentLayout != null)
{
actions.AddRange(currentLayout.GetActions());
}
// Add overlays