-
Notifications
You must be signed in to change notification settings - Fork 147
/
MediaPortal.cs
6323 lines (5639 loc) · 231 KB
/
MediaPortal.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
#region Copyright (C) 2005-2021 Team MediaPortal
// Copyright (C) 2005-2021 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// MediaPortal 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Linq;
using CSCore.CoreAudioAPI;
using DirectShowLib;
using DShowNET.Helper;
using FilterCategory = DirectShowLib.FilterCategory;
#region usings
using System;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Xml;
using MediaPortal;
using MediaPortal.Common.Utils;
using MediaPortal.Configuration;
using MediaPortal.Database;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using MediaPortal.InputDevices;
using MediaPortal.IR;
using MediaPortal.Player;
using MediaPortal.Profile;
using MediaPortal.Properties;
using MediaPortal.RedEyeIR;
using MediaPortal.Ripper;
using MediaPortal.SerialIR;
using MediaPortal.Util;
using MediaPortal.Services;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Microsoft.Win32;
using Action = MediaPortal.GUI.Library.Action;
using Timer = System.Timers.Timer;
using System.Collections.Generic;
using System.Net;
#endregion
// ReSharper disable EmptyNamespace
namespace MediaPortal {}
// ReSharper restore EmptyNamespace
/// <summary>
///
/// </summary>
public class MediaPortalApp : D3D, IRender
{
#region vars
private static bool _useRestartOptions;
private static bool _isWinScreenSaverInUse;
private static bool _mpCrashed;
private static bool _skinOverrideNoTheme;
private static bool _waitForTvServer;
private static bool _isRendering;
#if !DEBUG
private static bool _avoidVersionChecking;
#endif
private readonly bool _useScreenSaver = true;
private readonly bool _useIdlePluginScreen;
private bool _idlePluginActive = false;
private bool _changeScreen;
private bool _changeScreenDisplayChange;
private readonly bool _useIdleblankScreen;
private int _idlePluginWindowId;
private readonly bool _showLastActiveModule;
private readonly bool _stopOnLostAudioRenderer;
private readonly int _delayOnResume;
private bool _playingState;
private bool _showStats;
private bool _showStatsPrevious;
private bool _restoreTopMost;
private bool _startWithBasicHome;
private bool _useOnlyOneHome;
private bool _suspended;
private bool _ignoreContextMenuAction;
private bool _supportsFiltering;
private bool _supportsAlphaBlend;
private bool _mouseClickFired;
private bool _useLongDateFormat;
private static int _startupDelay;
private readonly int _timeScreenSaver;
private readonly int _suspendGracePeriodSec;
private int _xpos;
private int _frameCount;
private int _errorCounter;
private int _anisotropy;
private static string _alternateConfig;
private static string _safePluginsList;
private string _dateFormat;
private static string _outdatedSkinName;
private static DateTime _lastOnresume;
private DateTime _updateTimer;
private DateTime _lastContextMenuAction;
private Point _lastCursorPosition;
private SerialUIR _serialuirdevice;
private USBUIRT _usbuirtdevice;
private WinLirc _winlircdevice;
private RedEye _redeyedevice;
private MouseEventArgs _lastMouseClickEvent;
private readonly Rectangle[] _region;
private static RestartOptions _restartOptions;
private IntPtr _deviceNotificationHandle;
private IntPtr _displayStatusHandle;
private IntPtr _userPresenceHandle;
private IntPtr _awayModeHandle;
private bool _resumedAutomatic;
private bool _resumedSuspended;
private bool _delayedResume;
private readonly Object _delayedResumeLock = new Object();
private readonly bool _ignoreFullscreenResolutionChanges;
private int _locationX;
private int _locationY;
private bool _firstRestoreScreen = true;
private int _backupSizeWidth;
private int _backupSizeHeight;
private bool _usePrimaryScreen;
private string _screenDisplayName;
private bool _threadedStartup;
/// <summary>
/// Whether HID keyboard handler should be used instead of legacy keyboard handler.
/// </summary>
private bool _hidKeyboard = false;
// ReSharper disable InconsistentNaming
private const int WM_SYSCOMMAND = 0x0112; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
private const int SC_MINIMIZE = 0xF020; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
private const int SC_MONITORPOWER = 0xF170; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
private const int SC_SCREENSAVE = 0xF140; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
private const int WM_ENDSESSION = 0x0016; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa376889(v=vs.85).aspx
private const int WM_DEVICECHANGE = 0x0219; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480(v=vs.85).aspx
private const int DBT_DEVICEARRIVAL = 0x8000; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363211(v=vs.85).aspx
private const int DBT_DEVICEREMOVECOMPLETE = 0x8004; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363211(v=vs.85).aspx
private const int WM_QUERYENDSESSION = 0x0011; // http://msdn.microsoft.com/en-us/library/windows/desktop/aa376890(v=vs.85).aspx
private const int WM_ACTIVATE = 0x0006; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646274(v=vs.85).aspx
private const int WA_INACTIVE = 0; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646274(v=vs.85).aspx
private const int WA_ACTIVE = 1; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646274(v=vs.85).aspx
private const int WA_CLICKACTIVE = 2; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646274(v=vs.85).aspx
private const int WM_SIZING = 0x0214; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_LEFT = 1; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_RIGHT = 2; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_TOP = 3; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_TOPLEFT = 4; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_TOPRIGHT = 5; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_BOTTOM = 6; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_BOTTOMLEFT = 7; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WMSZ_BOTTOMRIGHT = 8; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632647(v=vs.85).aspx
private const int WM_SIZE = 0x0005; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int SIZE_RESTORED = 0; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int SIZE_MINIMIZED = 1; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int SIZE_MAXIMIZED = 2; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int SIZE_MAXSHOW = 3; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int SIZE_MAXHIDE = 4; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646(v=vs.85).aspx
private const int WM_GETMINMAXINFO = 0x0024; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632626(v=vs.85).aspx
private const int WM_MOVING = 0x0216; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632632(v=vs.85).aspx
private const int WM_ENTERSIZEMOVE = 0x0231; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632622(v=vs.85).aspx
private const int WM_EXITSIZEMOVE = 0x0232; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms632623(v=vs.85).aspx
private const int WM_DISPLAYCHANGE = 0x007E; // http://msdn.microsoft.com/en-us/library/windows/desktop/dd145210(v=vs.85).aspx
private const int WM_POWERBROADCAST = 0x0218; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa373247(v=vs.85).aspx
private const int WM_WINDOWPOSCHANGED = 0x0047; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa373247(v=vs.85).aspx
private const int WM_WINDOWPOSCHANGING = 0x0046; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa373247(v=vs.85).aspx
private const int SPI_GETSCREENSAVEACTIVE = 0x0010; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
private const int SPI_SETSCREENSAVEACTIVE = 0x0011; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
private const int SPIF_SENDCHANGE = 0x0002; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
private const int D3DERR_DEVICEHUNG = -2005530508; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx
private const int D3DERR_DEVICEREMOVED = -2005530512; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx
private const int D3DERR_INVALIDCALL = -2005530516; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx
private const int D3DERR_NOTAVAILABLE = -2005530518; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx
private const int E_FAIL = -2147467259; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx
private const int DEVICE_NOTIFY_WINDOW_HANDLE = 0;
private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4;
private const int DBT_DEVTYP_DEVICEINTERFACE = 5;
private static readonly Guid KSCATEGORY_RENDER = new Guid("{65E8773E-8F56-11D0-A3B9-00A0C9223196}");
private static readonly Guid KSCATEGORY_INTEL_AUDIO = new Guid("{86841137-ed8e-4d97-9975-f2ed56b4430e}");
private static readonly Guid RDP_REMOTE_AUDIO = new Guid("{E6327CAD-DCEC-4949-AE8A-991E976A79D2}");
private static readonly Guid KSCATEGORY_AUDIO = new Guid("{6994ad04-93ef-11d0-a3cc-00a0c9223196}");
private static readonly Guid KSCATEGORY_VIDEO = new Guid("{e6dfdc31-31d0-46ac-86af-da1eb05fc599}");
private static readonly Guid KSCATEGORY_SCREEN = new Guid("{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}");
private static readonly Guid KSCATEGORY_DISPLAY_ADAPTER = new Guid("{5b45201d-f2f2-4f3b-85bb-30ff1f953599}");
// http://msdn.microsoft.com/en-us/library/windows/desktop/hh448380(v=vs.85).aspx
private static Guid GUID_MONITOR_POWER_ON = new Guid("02731015-4510-4526-99e6-e5a17ebd1aea");
private static Guid GUID_SESSION_DISPLAY_STATUS = new Guid("2b84c20e-ad23-4ddf-93db-05ffbd7efca5");
private static Guid GUID_SESSION_USER_PRESENCE = new Guid("{3c0f4548-c03f-4c4d-b9f2-237ede686376}");
private static Guid GUID_SYSTEM_AWAYMODE = new Guid("98a7f580-01f7-48aa-9c0f-44352c29e5c0");
// ReSharper restore InconsistentNaming
private const string MPMutex = "{E0151CBA-7F81-41df-9849-F5298A779EB3}";
#pragma warning disable 169
private const string ConfigMutex = "{0BFD648F-A59F-482A-961B-337D70968611}";
#pragma warning restore 169
private ShellNotifications Notifications = new ShellNotifications();
// Framegrabber instance
private FrameGrabber grabber = FrameGrabber.GetInstance();
// Core Audio controller
MMDeviceEnumerator _mMdeviceEnumerator = new MMDeviceEnumerator();
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
// ReSharper disable InconsistentNaming
public class DISPLAY_DEVICE
// ReSharper restore InconsistentNaming
{
public int cb = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DeviceName = new String(' ', 32);
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceString = new String(' ', 128);
public int StateFlags = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceID = new String(' ', 128);
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceKey = new String(' ', 128);
}
[DllImport("user32.dll")]
public static extern bool EnumDisplayDevices(string lpDevice, int iDevNum, [In, Out] DISPLAY_DEVICE lpDisplayDevice, int dwFlags);
#endregion
#region enumns
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx
[FlagsAttribute]
// ReSharper disable InconsistentNaming
public enum EXECUTION_STATE : uint
{
ES_SYSTEM_REQUIRED = 0x00000001,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_USER_PRESENT = 0x00000004, // Legacy flag, should not be used.
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
}
// ReSharper restore InconsistentNaming
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480(v=vs.85).aspx
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Local
private enum DBT_EVENT
{
DBT_CONFIGCHANGECANCELED = 0x0019,
DBT_CONFIGCHANGED = 0x0018,
DBT_CUSTOMEVENT = 0x8006,
DBT_DEVICEARRIVAL = 0x8000,
DBT_DEVICEQUERYREMOVE = 0x8001,
DBT_DEVICEQUERYREMOVEFAILED = 0x8002,
DBT_DEVICEREMOVECOMPLETE = 0x8004,
DBT_DEVICEREMOVEPENDING = 0x8003,
DBT_DEVICETYPESPECIFIC = 0x8005,
DBT_DEVNODES_CHANGED = 0x0007,
DBT_QUERYCHANGECONFIG = 0x0017,
DBT_USERDEFINED = 0xFFFF
}
// ReSharper restore UnusedMember.Local
// ReSharper restore InconsistentNaming
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373247(v=vs.85).aspx
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Local
private enum PBT_EVENT
{
PBT_APMPOWERSTATUSCHANGE = 0x000A,
PBT_APMRESUMEAUTOMATIC = 0x0012,
PBT_APMRESUMESUSPEND = 0x0007,
PBT_APMSUSPEND = 0x0004,
PBT_POWERSETTINGCHANGE = 0x8013,
// XP only
PBT_APMBATTERYLOW = 0x0009,
PBT_APMOEMEVENT = 0x000B,
PBT_APMQUERYSUSPEND = 0x0000,
PBT_APMQUERYSUSPENDFAILED = 0x0002,
PBT_APMRESUMECRITICAL = 0x0006
}
// ReSharper restore UnusedMember.Local
// ReSharper restore InconsistentNaming
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646274(v=vs.85).aspx
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Local
private enum WA_EVENT
{
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2,
WA_INACTIVE = 0
}
// ReSharper restore InconsistentNaming
// ReSharper restore UnusedMember.Local
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Local
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa363246(v=vs.85).aspx
private enum DBT_DEV_TYPE
{
DBT_DEVTYP_DEVICEINTERFACE = 0x00000005,
DBT_DEVTYP_HANDLE = 0x00000006,
DBT_DEVTYP_OEM = 0x00000000,
DBT_DEVTYP_PORT = 0x00000003,
DBT_DEVTYP_VOLUME = 0x00000002
}
// ReSharper restore InconsistentNaming
// ReSharper restore UnusedMember.Local
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Local
private enum SYSCOMMAND
{
SC_CLOSE = 0xF060,
SC_CONTEXTHELP = 0xF180,
SC_DEFAULT = 0xF160,
SC_HOTKEY = 0xF150,
SC_HSCROLL = 0xF080,
SCF_ISSECURE = 0x0001,
SC_KEYMENU = 0xF100,
SC_MAXIMIZE = 0xF030,
SC_MINIMIZE = 0xF020,
SC_MONITORPOWER = 0xF170,
SC_MOUSEMENU = 0xF090,
SC_MOVE = 0xF010,
SC_NEXTWINDOW = 0xF040,
SC_PREVWINDOW = 0xF050,
SC_RESTORE = 0xF120,
SC_SCREENSAVE = 0xF140,
SC_SIZE = 0xF000,
SC_TASKLIST = 0xF130,
SC_VSCROLL = 0xF070
}
// ReSharper restore InconsistentNaming
// ReSharper restore UnusedMember.Local
private enum DisplayState
{
ON = -1,
OFF = 2,
STANDBY = 1
}
#endregion
#region structs
// ReSharper disable InconsistentNaming
// ReSharper disable NotAccessedField.Local
#pragma warning disable 169, 649
private struct POINTAPI
{
public int x;
public int y;
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632605(v=vs.85).aspx
private struct MINMAXINFO
{
public POINTAPI ptReserved;
public POINTAPI ptMaxSize;
public POINTAPI ptMaxPosition;
public POINTAPI ptMinTrackSize;
public POINTAPI ptMaxTrackSize;
}
#pragma warning restore 169, 649
// ReSharper restore NotAccessedField.Local
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363244(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
public string dbcc_name;
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363246(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential)]
public struct DEV_BROADCAST_HDR
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363245(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential)]
public struct DEV_BROADCAST_HANDLE
{
public int dbch_size;
public int dbch_devicetype;
public int dbch_reserved;
public IntPtr dbch_handle;
public IntPtr dbch_hdevnotify;
public Guid dbch_eventguid;
public long dbch_nameoffset;
public byte dbch_data;
public byte dbch_data1;
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa372723(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct POWERBROADCAST_SETTING
{
public Guid PowerSetting;
public uint DataLength;
public byte Data;
}
// ReSharper restore InconsistentNaming
#endregion
#region imports
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
[DllImport("user32")]
private static extern bool SystemParametersInfo(int uAction, int uParam, ref bool lpvParam, int fuWinIni);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
[DllImport("user32")]
private static extern bool SystemParametersInfo(int uAction, int uParam, int lpvParam, int fuWinIni);
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx
[DllImport("kernel32")]
private static extern bool SetProcessWorkingSetSize(IntPtr handle, int minSize, int maxSize);
// http://msdn.microsoft.com/en-us/library/ms648415(v=vs.85).aspx
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern void DisableProcessWindowsGhosting();
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb773640(v=vs.85).aspx
[DllImport("shlwapi.dll")]
private static extern bool PathIsNetworkPath(string path);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363431(v=vs.85).aspx
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr notificationFilter, uint flags);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363475(v=vs.85).aspx
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint UnregisterDeviceNotification(IntPtr hHandle);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373196(v=vs.85).aspx
[DllImport(@"User32", SetLastError = true, EntryPoint = "RegisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient, ref Guid powerSettingGuid, Int32 flags);
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373237(v=vs.85).aspx
[DllImport(@"User32", EntryPoint = "UnregisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)]
private static extern bool UnregisterPowerSettingNotification(IntPtr handle);
[DllImport("user32.dll", SetLastError = true)]
private static extern int SetProcessDPIAware();
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
#endregion
#region main()
[STAThread]
public static void Main(string[] args)
{
//Log.Info("Starting deployer application");
//Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
// .NET 4.0: Use TLS v1.2. Many download sources no longer support the older and now insecure TLS v1.0/1.1 and SSL v3.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)0xc00;
using (Settings xmlreader = new MPSettings())
{
bool noAutoStartOnRDP = xmlreader.GetValueAsBool("general", "noautostartonrdp", false);
if (System.Windows.Forms.SystemInformation.TerminalServerSession && noAutoStartOnRDP)
{
Environment.Exit(0);
return; // exit
}
}
Thread.CurrentThread.Name = "MPMain";
if (Environment.OSVersion.Version.Major >= 6)
{
int succeeded = SetProcessDPIAware();
Log.Info("Main: MediaPortal SetProcessDPIAware {0}", succeeded);
}
#if !DEBUG
// TODO: work on the handlers to take over more Watchdog capabilities, current use for Area51 builds as needed only
//AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
//Application.ThreadException += OnThreadException;
#endif
SkinOverride = string.Empty;
WindowedOverride = false;
FullscreenOverride = false;
ScreenNumberOverride = -1;
if (args.Length > 0)
{
foreach (string arg in args)
{
if (arg == "/fullscreen")
{
FullscreenOverride = true;
}
if (arg == "/windowed")
{
WindowedOverride = true;
}
if (arg.StartsWith("/fullscreen="))
{
string argValue = arg.Remove(0, 12); // remove /?= from the argument
FullscreenOverride |= argValue != "no";
WindowedOverride |= argValue.Equals("no");
}
if (arg == "/crashtest")
{
_mpCrashed = true;
}
if (arg.StartsWith("/screen="))
{
string screenarg = arg.Remove(0, 8); // remove /?= from the argument
if (!int.TryParse(screenarg, out ScreenNumberOverride))
{
ScreenNumberOverride = -1;
}
}
if (arg.StartsWith("/skin="))
{
string skinOverrideArg = arg.Remove(0, 6); // remove /?= from the argument
SkinOverride = skinOverrideArg;
}
if (arg.StartsWith("/config="))
{
_alternateConfig = arg.Remove(0, 8); // remove /?= from the argument
if (!Path.IsPathRooted(_alternateConfig))
{
_alternateConfig = Config.GetFile(Config.Dir.Config, _alternateConfig);
}
}
if (arg.StartsWith("/safelist="))
{
_safePluginsList = arg.Remove(0, 10); // remove /?= from the argument
}
if (arg == "/NoTheme")
{
_skinOverrideNoTheme = true;
}
if (arg == "/Debug")
{
Log.SetLogLevel(Level.Debug);
}
#if !DEBUG
_avoidVersionChecking = arg.ToLowerInvariant() == "/avoidversioncheck";
#endif
}
}
// check if MediaPotal is already running
using (var processLock = new ProcessLock(MPMutex))
{
if (processLock.AlreadyExists)
{
Log.Warn("Main: MediaPortal is already running");
Win32API.ActivatePreviousInstance();
}
}
// Check for a Configuration Instance running and don't allow Mediaportal to start
using (ProcessLock processLock = new ProcessLock(ConfigMutex))
{
if (processLock.AlreadyExists)
{
DialogResult dialogResult = MessageBox.Show(
"MediaPortal configuration has to be closed for starting MediaPortal",
"MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Question);
Log.Warn("Main: Configuration is running - start of MediaPortal aborted");
return;
}
}
if (string.IsNullOrEmpty(_alternateConfig))
{
Log.BackupLogFiles();
}
else
{
if (File.Exists(_alternateConfig))
{
try
{
MPSettings.AlternateConfig = true;
MPSettings.ConfigPathName = _alternateConfig;
MPSettings.AlternateConfig = false;
try
{
using (Settings xmlreader = new MPSettings())
{
var logLevel = (Level)xmlreader.GetValueAsInt("general", "loglevel", 3);
Log.SetLogLevel(logLevel);
}
}
catch (Exception ex)
{
Log.Error("Failed to change Log level from alternate configuration file.");
Log.Error(ex);
}
Log.BackupLogFiles();
Log.Info("Using alternate configuration file: {0}", MPSettings.ConfigPathName);
}
catch (Exception ex)
{
Log.BackupLogFiles();
Log.Error("Failed to change to alternate configuration file:");
Log.Error(ex);
}
}
else
{
Log.BackupLogFiles();
Log.Info("Alternative configuration file was specified but the file was not found: '{0}'", _alternateConfig);
Log.Info("Using default configuration file instead.");
}
}
if (!Config.DirsFileUpdateDetected)
{
// check if Mediaportal has been configured
var fi = new FileInfo(MPSettings.ConfigPathName);
if (!File.Exists(MPSettings.ConfigPathName) || (fi.Length < 10000))
{
// no, then start configuration.exe in wizard form
Log.Info("MediaPortal.xml not found. Launching configuration tool and exiting...");
try
{
Process.Start(Config.GetFile(Config.Dir.Base, "configuration.exe"), @"/wizard");
}
// ReSharper disable EmptyGeneralCatchClause
catch {} // no exception logging needed, since MP is now closed
// ReSharper restore EmptyGeneralCatchClause
return;
}
// TODO: check if config is valid. If you create a config file > 10000 bytes full of spaces MP will crash as Utils.dll does nearly no error checking
using (Settings xmlreader = new MPSettings())
{
string threadPriority = xmlreader.GetValueAsString("general", "ThreadPriority", "Normal");
switch (threadPriority)
{
case "AboveNormal":
Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
break;
case "High":
Thread.CurrentThread.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
break;
case "BelowNormal":
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
break;
}
_startupDelay = xmlreader.GetValueAsBool("general", "delay startup", false) ? xmlreader.GetValueAsInt("general", "delay", 0): 0;
_waitForTvServer = xmlreader.GetValueAsBool("general", "wait for tvserver", false);
}
#if !DEBUG
bool watchdogEnabled;
bool restartOnError;
int restartDelay;
using (Settings xmlreader = new MPSettings())
{
watchdogEnabled = xmlreader.GetValueAsBool("general", "watchdogEnabled", true);
restartOnError = xmlreader.GetValueAsBool("general", "restartOnError", false);
restartDelay = xmlreader.GetValueAsInt("general", "restart delay", 10);
}
AddExceptionHandler();
if (watchdogEnabled)
{
using (var sw = new StreamWriter(Config.GetFile(Config.Dir.Config, "mediaportal.running"), false))
{
sw.WriteLine("running");
sw.Close();
}
Log.Info("Main: Starting MPWatchDog");
string cmdargs = "-watchdog";
if (restartOnError)
{
cmdargs += " -restartMP " + restartDelay.ToString(CultureInfo.InvariantCulture);
}
var mpWatchDog = new Process
{
StartInfo =
{
ErrorDialog = true,
UseShellExecute = true,
WorkingDirectory = Application.StartupPath,
FileName = "WatchDog.exe",
Arguments = cmdargs
}
};
mpWatchDog.Start();
}
#endif
// Log MediaPortal version build and operating system level
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
try
{
Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion());
}
catch {
Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on Windows 10 Pro for Workstations (???)");
}
//Log.Info(OSInfo.OSInfo.GetLastInstalledWindowsUpdateTimestampAsString());
Log.Info("Windows Media Player: [{0}]", OSInfo.OSInfo.GetWMPVersion());
#if DEBUG
Log.Info("Debug Build: " + Application.ProductVersion);
#else
Log.Info("Build: " + Application.ProductVersion);
#endif
// setting minimum worker threads
int minWorker, minIOC;
ThreadPool.GetMinThreads(out minWorker, out minIOC);
ThreadPool.SetMinThreads(minWorker * 2, minIOC * 1);
ThreadPool.GetMinThreads(out minWorker, out minIOC);
Log.Info("Main: Minimum number of worker threads to {0}/{1}", minWorker, minIOC);
// Check for unsupported operating systems
OSPrerequisites.OSPrerequisites.OsCheck(false);
Log.Debug("Disabling process window ghosting");
DisableProcessWindowsGhosting();
// Start MediaPortal
Log.Info("Main: Using Directories:");
foreach (Config.Dir option in Enum.GetValues(typeof (Config.Dir)))
{
Log.Info("{0} - {1}", option, Config.GetFolder(option));
}
var mpFi = new FileInfo(Assembly.GetExecutingAssembly().Location);
Log.Info("Main: Assembly creation time: {0} (UTC)", mpFi.LastWriteTimeUtc.ToUniversalTime());
#pragma warning disable 168
using (var processLock = new ProcessLock(MPMutex))
#pragma warning restore 168
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Set current directory
string applicationPath = Application.ExecutablePath;
applicationPath = Path.GetFullPath(applicationPath);
applicationPath = Path.GetDirectoryName(applicationPath);
if (!String.IsNullOrEmpty(applicationPath))
{
Directory.SetCurrentDirectory(applicationPath);
Log.Info("Main: Set current directory to: {0}", applicationPath);
}
else
{
Log.Error("Main: Cannot set current directory to {0}", applicationPath);
}
// log about available displays
foreach (var screen in Screen.AllScreens)
{
Log.Debug("Display: {0} - IsPrimary: {1} - BitsPerPixel: {2} - Bounds: {3}x{4} @ {5},{6} - WorkingArea: {7}x{8} @ {9},{10}",
GetCleanDisplayName(screen), screen.Primary, screen.BitsPerPixel,
screen.Bounds.Width, screen.Bounds.Height, screen.Bounds.X, screen.Bounds.Y,
screen.WorkingArea.Width, screen.WorkingArea.Height, screen.WorkingArea.X, screen.WorkingArea.Y);
}
// Localization strings for new splash screen and for MediaPortal itself
LoadLanguageString();
// Initialize the skin and theme prior to beginning the splash screen thread. This provides for the splash screen to be used in a theme.
string skin;
try
{
using (Settings xmlreader = new MPSettings())
{
skin = string.IsNullOrEmpty(SkinOverride) ? xmlreader.GetValueAsString("skin", "name", "Titan") : SkinOverride;
}
}
catch (Exception ex)
{
Log.Error("MediaPortal: Main {0}", ex.Message);
skin = "Titan";
}
Config.SkinName = skin;
GUIGraphicsContext.Skin = skin;
SkinSettings.NoTheme = _skinOverrideNoTheme;
SkinSettings.Load();
// Send a message that the skin has changed.
var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SKIN_CHANGED, 0, 0, 0, 0, 0, null);
GUIGraphicsContext.SendMessage(msg);
Log.Info("Main: Skin is {0} using theme {1}", skin, GUIThemeManager.CurrentTheme);
// Start Splash Screen
string version = ConfigurationManager.AppSettings["version"];
SplashScreen = new SplashScreen {Version = version};
#if !DEBUG
SplashScreen.Run();
#endif
if (_waitForTvServer)
{
Log.Debug("Main: Wait for TV service requested");
ServiceController ctrl;
try
{
ctrl = new ServiceController("TVService");
}
catch (Exception ex)
{
ctrl = null;
Log.Debug("Main: Create ServiceController for TV service failed - proceeding... {0}", ex.Message);
}
if (ctrl != null)
{
//Sanity check for existance of TV service
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
status = ctrl.Status;
}
catch (Exception ex)
{
Log.Debug("Main: Failed to retrieve TV service status {0}", ex.Message);
ctrl.Close();
ctrl = null;
}
}
if (ctrl != null)
{
Log.Debug("Main: TV service found. Checking status...");
UpdateSplashScreenMessage(GUILocalizeStrings.Get(60)); // Waiting for startup of TV service...
if (ctrl.Status == ServiceControllerStatus.StartPending || ctrl.Status == ServiceControllerStatus.Stopped)
{
if (ctrl.Status == ServiceControllerStatus.StartPending)
{
Log.Info("Main: TV service start is pending. Waiting...");
}
if (ctrl.Status == ServiceControllerStatus.Stopped)
{
Log.Info("Main: TV service is stopped, so we try start it...");
try
{
ctrl.Start();
}
catch (Exception ex)
{
Log.Info("TvService seems to be already starting up. {0}", ex.Message);
}
}
try
{
ctrl.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 45));
}
catch (Exception ex)
{
Log.Error("MediaPortal: WaitForStatus {0}", ex.Message);
}
if (ctrl.Status == ServiceControllerStatus.Running)
{
Log.Info("Main: The TV service has started successfully.");
}
else
{
Log.Info("Main: Startup of the TV service failed - current status: {0}", ctrl.Status.ToString());
}
}
Log.Info("Main: TV service is in status {0} - proceeding...", ctrl.Status.ToString());
ctrl.Close();
}
}
if (_startupDelay > 0)
{
Log.Info("Main: Waiting {0} second(s) before startup", _startupDelay);
for (int i = _startupDelay; i > 0; i--)
{
UpdateSplashScreenMessage(String.Format(GUILocalizeStrings.Get(61), i.ToString(CultureInfo.InvariantCulture)));
Thread.Sleep(1000);
}
}
Log.Debug("Main: Checking prerequisites");
try
{
// check if DirectX 9.0c if installed
Log.Debug("Main: Verifying DirectX 9");
if (!DirectXCheck.IsInstalled())
{
DisableSplashScreen();
string strLine = "Please install a newer DirectX 9.0c redist!\r\n";
strLine = strLine + "MediaPortal cannot run without DirectX 9.0c redist (August 2008)\r\n";
strLine = strLine + "http://install.team-mediaportal.com/DirectX";
// ReSharper disable LocalizableElement
MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
// ReSharper restore LocalizableElement
return;
}
#if !DEBUG
// Check TvPlugin version
string mpExe = Assembly.GetExecutingAssembly().Location;
string tvPlugin = Config.GetFolder(Config.Dir.Plugins) + "\\Windows\\TvPlugin.dll";
if (File.Exists(tvPlugin) && !_avoidVersionChecking)
{
string tvPluginVersion = FileVersionInfo.GetVersionInfo(tvPlugin).ProductVersion;
string mpVersion = FileVersionInfo.GetVersionInfo(mpExe).ProductVersion;
if (mpVersion != tvPluginVersion)
{
string strLine = "TvPlugin and MediaPortal don't have the same version.\r\n";
strLine += "Please update the older component to the same version as the newer one.\r\n";
strLine += "MediaPortal Version: " + mpVersion + "\r\n";
strLine += "TvPlugin Version: " + tvPluginVersion;
DisableSplashScreen();
// ReSharper disable LocalizableElement
MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
// ReSharper restore LocalizableElement
Log.Info(strLine);