forked from BOINC/boinc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscreensaver_win.cpp
1913 lines (1534 loc) · 61.3 KB
/
screensaver_win.cpp
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
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
//
// Contributor(s):
// DirectX 8.1 Screen Saver Framework from Microsoft.
// Microsoft Knowledge Base Article - 79212
//
#include "boinc_win.h"
#include <windowsx.h>
#include <mmsystem.h>
#include <regstr.h>
#include <strsafe.h>
#include <mmsystem.h>
#define COMPILE_MULTIMON_STUBS
#include "boinc_ss.h"
#include "diagnostics.h"
#include "common_defs.h"
#include "util.h"
#include "gui_rpc_client.h"
#include "screensaver.h"
#include "screensaver_win.h"
#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif
static HMODULE gshUser32 = NULL;
static HMODULE gshPasswordCPL = NULL;
static VERIFYPWDPROC gspfnMyVerifyPwdProc = NULL;
static MYGETLASTINPUTINFO gspfnMyGetLastInputInfo = NULL;
static MYISHUNGAPPWINDOW gspfnMyIsHungAppWindow = NULL;
static MYBROADCASTSYSTEMMESSAGE gspfnMyBroadcastSystemMessage = NULL;
static CScreensaver* gspScreensaver = NULL;
const UINT WM_SETTIMER = RegisterWindowMessage(TEXT("BOINCSetTimer"));
const UINT WM_INTERRUPTSAVER = RegisterWindowMessage(TEXT("BOINCInterruptScreensaver"));
const UINT WM_BOINCSFW = RegisterWindowMessage(TEXT("BOINCSetForegroundWindow"));
INT WINAPI WinMain(
HINSTANCE hInstance, HINSTANCE UNUSED(hPrevInstance), LPSTR UNUSED(lpCmdLine), int UNUSED(nCmdShow)
) {
HRESULT hr;
CScreensaver BOINCSS;
int retval;
WSADATA wsdata;
BOOL bIs95 = FALSE;
BOOL bIs9x = FALSE;
DWORD dwVal;
DWORD dwSize = sizeof(dwVal);
HKEY hKey;
#ifdef _DEBUG
// Initialize Diagnostics
retval = diagnostics_init (
BOINC_DIAG_DUMPCALLSTACKENABLED |
BOINC_DIAG_HEAPCHECKENABLED |
BOINC_DIAG_MEMORYLEAKCHECKENABLED |
BOINC_DIAG_ARCHIVESTDOUT |
BOINC_DIAG_REDIRECTSTDOUTOVERWRITE |
BOINC_DIAG_REDIRECTSTDERROVERWRITE |
BOINC_DIAG_TRACETOSTDOUT,
"stdoutscr",
"stderrscr"
);
if (retval) {
BOINCTRACE("WinMain - BOINC Screensaver Diagnostic Error '%d'\n", retval);
MessageBox(NULL, NULL, "BOINC Screensaver Diagnostic Error", MB_OK);
}
#endif
// Figure out if we're on Win9x
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
bIs9x = osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS;
bIs95 = (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) &&
((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 0));
// Load dynamically linked modules
gshUser32 = LoadLibrary(_T("USER32.DLL"));
if (bIs9x) {
gshPasswordCPL = LoadLibrary(_T("PASSWORD.CPL"));
}
// Map function pointers
if (gshUser32) {
gspfnMyGetLastInputInfo = (MYGETLASTINPUTINFO) GetProcAddress(gshUser32, _T("GetLastInputInfo"));
gspfnMyIsHungAppWindow = (MYISHUNGAPPWINDOW) GetProcAddress(gshUser32, _T("IsHungAppWindow"));
if (bIs95) {
gspfnMyBroadcastSystemMessage = (MYBROADCASTSYSTEMMESSAGE) GetProcAddress(gshUser32, _T("BroadcastSystemMessage"));
} else {
gspfnMyBroadcastSystemMessage = (MYBROADCASTSYSTEMMESSAGE) GetProcAddress(gshUser32, _T("BroadcastSystemMessageA"));
}
}
if (gshPasswordCPL) {
if (RegOpenKey(HKEY_CURRENT_USER , REGSTR_PATH_SCREENSAVE , &hKey) == ERROR_SUCCESS) {
if ((RegQueryValueEx(hKey, REGSTR_VALUE_USESCRPASSWORD, NULL, NULL, (BYTE *)&dwVal, &dwSize) == ERROR_SUCCESS) && dwVal) {
gspfnMyVerifyPwdProc = (VERIFYPWDPROC)GetProcAddress(gshPasswordCPL, _T("VerifyScreenSavePwd"));
RegCloseKey(hKey);
}
}
}
// Initialize the CRT random number generator.
srand((unsigned int)time(0));
// Initialize the Windows sockets interface.
retval = WSAStartup(MAKEWORD(1, 1), &wsdata);
if (retval) {
BOINCTRACE("WinMain - Winsock Initialization Failure '%d'\n", retval);
return retval;
}
if (FAILED(hr = BOINCSS.Create(hInstance))) {
BOINCSS.DisplayErrorMsg(hr);
WSACleanup();
return 0;
}
retval = BOINCSS.Run();
// Cleanup any existing screensaver objects and handles
BOINCSS.Cleanup();
// Cleanup the Windows sockets interface.
WSACleanup();
// Clean up function pointers.
gspfnMyGetLastInputInfo = NULL;
gspfnMyIsHungAppWindow = NULL;
gspfnMyBroadcastSystemMessage = NULL;
gspfnMyVerifyPwdProc = NULL;
// Free modules
FreeLibrary(gshUser32);
if (gshPasswordCPL) {
FreeLibrary(gshPasswordCPL);
gshPasswordCPL = NULL;
}
// Instruct the OS to terminate the screensaver by any
// means nessassary.
TerminateProcess(GetCurrentProcess(), retval);
return retval;
}
CScreensaver::CScreensaver() {
gspScreensaver = this;
m_bCheckingSaverPassword = FALSE;
m_bIs9x = FALSE;
m_dwSaverMouseMoveCount = 0;
m_hWnd = NULL;
m_hWndParent = NULL;
m_bAllScreensSame = FALSE;
m_bWindowed = FALSE;
m_bWaitForInputIdle = FALSE;
m_bErrorMode = FALSE;
m_hrError = S_OK;
m_szError[0] = _T('\0');
m_strBOINCInstallDirectory.clear();
m_strBOINCDataDirectory.clear();
LoadString(NULL, IDS_DESCRIPTION, m_strWindowTitle, 200);
m_bPaintingInitialized = FALSE;
m_dwBlankScreen = 0;
m_dwBlankTime = 0;
rpc = NULL;
m_bConnected = false;
m_hDataManagementThread = NULL;
m_hGraphicsApplication = NULL;
m_bResetCoreState = TRUE;
m_QuitDataManagementProc = FALSE;
memset(&m_running_result, 0, sizeof(m_running_result));
ZeroMemory(m_Monitors, sizeof(m_Monitors));
m_dwNumMonitors = 0;
m_dwLastInputTimeAtStartup = 0;
m_tThreadCreateTime = 0;
}
// Have the client program call this function before calling Run().
//
HRESULT CScreensaver::Create(HINSTANCE hInstance) {
HRESULT hr;
BOOL bReturnValue;
m_hInstance = hInstance;
// Parse the command line and do the appropriate thing
m_SaverMode = ParseCommandLine(GetCommandLine());
// Figure out if we're on Win9x
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
m_bIs9x = (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
// Store last input value if it exists
if (gspfnMyGetLastInputInfo) {
LASTINPUTINFO lii;
lii.cbSize = sizeof(LASTINPUTINFO);
gspfnMyGetLastInputInfo(&lii);
m_dwLastInputTimeAtStartup = lii.dwTime;
}
// Enumerate Monitors
EnumMonitors();
// Retrieve the locations of the install directory and data directory
bReturnValue = UtilGetRegDirectoryStr(_T("DATADIR"), m_strBOINCDataDirectory);
BOINCTRACE("CScreensaver::Create - BOINC Data Directory '%s'\n", m_strBOINCDataDirectory.c_str());
bReturnValue = UtilGetRegDirectoryStr(_T("INSTALLDIR"), m_strBOINCInstallDirectory);
BOINCTRACE("CScreensaver::Create - BOINC Install Directory '%s'\n", m_strBOINCInstallDirectory.c_str());
// Retrieve the blank screen flag so we can determine if we are
// suppose to actually blank the screen at some point.
bReturnValue = UtilGetRegKey(REG_BLANK_NAME, m_dwBlankScreen);
BOINCTRACE("CScreensaver::Create - Get Reg Key REG_BLANK_NAME return value '%d'\n", bReturnValue);
if (!bReturnValue) m_dwBlankScreen = 0;
// Retrieve the blank screen timeout
// make sure you check return value of registry queries
// in case the item in question doesn't happen to exist.
bReturnValue = UtilGetRegKey(REG_BLANK_TIME, m_dwBlankTime);
BOINCTRACE("CScreensaver::Create - Get Reg Key REG_BLANK_TIME return value '%d'\n", bReturnValue);
if (!bReturnValue) m_dwBlankTime = 5;
// Save the value back to the registry in case this is the first
// execution and so we need the default value later.
bReturnValue = UtilSetRegKey(REG_BLANK_NAME, m_dwBlankScreen);
BOINCTRACE("CScreensaver::Create - Set Reg Key REG_BLANK_NAME return value '%d'\n", bReturnValue);
bReturnValue = UtilSetRegKey(REG_BLANK_TIME, m_dwBlankTime);
BOINCTRACE("CScreensaver::Create - Set Reg Key REG_BLANK_TIME return value '%d'\n", bReturnValue);
// Calculate the estimated blank time by adding the current time
// and and the user specified time which is in minutes
m_dwBlankTime = (DWORD)time(0) + (m_dwBlankTime * 60);
// Create the infrastructure mutexes so we can properly aquire them to report
// errors
if (!CreateInfrastructureMutexes()) {
return E_FAIL;
}
if (rpc == NULL) rpc = new RPC_CLIENT;
// Create the screen saver window(s)
if (m_SaverMode == sm_preview ||
m_SaverMode == sm_full
) {
if (FAILED(hr = CreateSaverWindow())) {
SetError(TRUE, hr);
}
}
if (m_SaverMode == sm_preview) {
// In preview mode, "pause" (enter a limited message loop) briefly
// before proceeding, so the display control panel knows to update itself.
m_bWaitForInputIdle = TRUE;
// Post a message to mark the end of the initial group of window messages
PostMessage(m_hWnd, WM_SETTIMER, 0, 0);
MSG msg;
while(m_bWaitForInputIdle) {
// If GetMessage returns FALSE, it's quitting time.
if (!GetMessage(&msg, m_hWnd, 0, 0)) {
// Post the quit message to handle it later
PostQuitMessage(0);
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return S_OK;
}
// Starts main execution of the screen saver.
//
HRESULT CScreensaver::Run() {
HOST_INFO hostinfo;
HRESULT hr;
// Parse the command line and do the appropriate thing
switch (m_SaverMode) {
case sm_config:
if (m_bErrorMode) {
DisplayErrorMsg(m_hrError);
} else {
DoConfig();
}
break;
case sm_test:
rpc->init(NULL);
rpc->get_host_info(hostinfo);
rpc->close();
break;
case sm_preview:
// In Windows, preview mode is for the mini-view of the screensaver.
// For BOINC we just display the icon, so there is no need to
// startup the data management thread which in turn will
// launch a graphics application.
if (FAILED(hr = DoSaver())) {
DisplayErrorMsg(hr);
}
break;
case sm_full:
// Create the various required threads
if (!CreateInputActivityThread()) return E_FAIL;
if (!CreateGraphicsWindowPromotionThread()) {
DestroyDataManagementThread();
return E_FAIL;
}
if (!CreateDataManagementThread()) {
DestroyDataManagementThread();
DestroyGraphicsWindowPromotionThread();
return E_FAIL;
}
if (FAILED(hr = DoSaver())) {
DisplayErrorMsg(hr);
}
// Destroy the various required threads
//
DestroyDataManagementThread();
DestroyGraphicsWindowPromotionThread();
DestroyInputActivityThread();
break;
case sm_passwordchange:
ChangePassword();
break;
}
return S_OK;
}
// Cleanup anything that needs cleaning.
//
HRESULT CScreensaver::Cleanup() {
if (m_hGraphicsApplication) {
TerminateProcess(m_hGraphicsApplication, 0);
m_hGraphicsApplication = NULL;
}
if (rpc) {
delete rpc;
rpc = NULL;
}
return S_OK;
}
// Displays error messages in a message box
//
HRESULT CScreensaver::DisplayErrorMsg(HRESULT hr) {
TCHAR strMsg[512];
GetTextForError(hr, strMsg, 512);
MessageBox(m_hWnd, strMsg, m_strWindowTitle, MB_ICONERROR | MB_OK);
return hr;
}
// Interpret command-line parameters passed to this app.
//
SaverMode CScreensaver::ParseCommandLine(TCHAR* pstrCommandLine) {
m_hWndParent = NULL;
BOINCTRACE("ParseCommandLine: '%s'\n", pstrCommandLine);
// Skip the first part of the command line, which is the full path
// to the exe. If it contains spaces, it will be contained in quotes.
if (*pstrCommandLine == _T('\"')) {
pstrCommandLine++;
while (*pstrCommandLine != _T('\0') && *pstrCommandLine != _T('\"')) {
pstrCommandLine++;
}
if (*pstrCommandLine == _T('\"')) {
pstrCommandLine++;
}
} else {
while (*pstrCommandLine != _T('\0') && *pstrCommandLine != _T(' ')) {
pstrCommandLine++;
}
if (*pstrCommandLine == _T(' ')) {
pstrCommandLine++;
}
}
// Skip along to the first option delimiter "/" or "-"
while (*pstrCommandLine != _T('\0') && *pstrCommandLine != _T('/') && *pstrCommandLine != _T('-')) {
pstrCommandLine++;
}
// If there wasn't one, then must be config mode
if (*pstrCommandLine == _T('\0')) {
return sm_config;
}
// Otherwise see what the option was
switch (*(++pstrCommandLine)) {
case 'c':
case 'C':
pstrCommandLine++;
while (*pstrCommandLine && !isdigit(*pstrCommandLine)) {
pstrCommandLine++;
}
if (isdigit(*pstrCommandLine)) {
#ifdef _WIN64
m_hWndParent = (HWND)_atoi64(pstrCommandLine);
#else
m_hWndParent = (HWND)_ttol(pstrCommandLine);
#endif
} else {
m_hWndParent = NULL;
}
return sm_config;
case 't':
case 'T':
return sm_test;
case 'p':
case 'P':
// Preview-mode, so option is followed by the parent HWND in decimal
pstrCommandLine++;
while (*pstrCommandLine && !isdigit(*pstrCommandLine)) {
pstrCommandLine++;
}
if (isdigit(*pstrCommandLine)) {
#ifdef _WIN64
m_hWndParent = (HWND)_atoi64(pstrCommandLine);
#else
m_hWndParent = (HWND)_ttol(pstrCommandLine);
#endif
}
return sm_preview;
case 'a':
case 'A':
// Password change mode, so option is followed by parent HWND in decimal
pstrCommandLine++;
while (*pstrCommandLine && !isdigit(*pstrCommandLine)) {
pstrCommandLine++;
}
if (isdigit(*pstrCommandLine)) {
#ifdef _WIN64
m_hWndParent = (HWND)_atoi64(pstrCommandLine);
#else
m_hWndParent = (HWND)_ttol(pstrCommandLine);
#endif
}
return sm_passwordchange;
default:
// All other options => run the screensaver (typically this is "/s")
return sm_full;
}
}
// Determine HMONITOR, desktop rect, and other info for each monitor.
// Note that EnumDisplayDevices enumerates monitors in the order
// indicated on the Settings page of the Display control panel, which
// is the order we want to list monitors in, as opposed to the order
// used by D3D's GetAdapterInfo.
//
VOID CScreensaver::EnumMonitors(VOID) {
DWORD iDevice = 0;
DISPLAY_DEVICE_FULL dispdev;
DISPLAY_DEVICE_FULL dispdev2;
DEVMODE devmode;
dispdev.cb = sizeof(dispdev);
dispdev2.cb = sizeof(dispdev2);
devmode.dmSize = sizeof(devmode);
devmode.dmDriverExtra = 0;
INTERNALMONITORINFO* pMonitorInfoNew;
while(EnumDisplayDevices(NULL, iDevice, (DISPLAY_DEVICE*)&dispdev, 0)) {
// Ignore NetMeeting's mirrored displays
if ((dispdev.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) == 0) {
// To get monitor info for a display device, call EnumDisplayDevices
// a second time, passing dispdev.DeviceName (from the first call) as
// the first parameter.
EnumDisplayDevices(dispdev.DeviceName, 0, (DISPLAY_DEVICE*)&dispdev2, 0);
pMonitorInfoNew = &m_Monitors[m_dwNumMonitors];
ZeroMemory(pMonitorInfoNew, sizeof(INTERNALMONITORINFO));
StringCchCopy(pMonitorInfoNew->strDeviceName, 128, dispdev.DeviceString);
StringCchCopy(pMonitorInfoNew->strMonitorName, 128, dispdev2.DeviceString);
if (dispdev.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
EnumDisplaySettings(dispdev.DeviceName, ENUM_CURRENT_SETTINGS, &devmode);
if (dispdev.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
// For some reason devmode.dmPosition is not always (0, 0)
// for the primary display, so force it.
pMonitorInfoNew->rcScreen.left = 0;
pMonitorInfoNew->rcScreen.top = 0;
} else {
pMonitorInfoNew->rcScreen.left = devmode.dmPosition.x;
pMonitorInfoNew->rcScreen.top = devmode.dmPosition.y;
}
pMonitorInfoNew->rcScreen.right = pMonitorInfoNew->rcScreen.left + devmode.dmPelsWidth;
pMonitorInfoNew->rcScreen.bottom = pMonitorInfoNew->rcScreen.top + devmode.dmPelsHeight;
pMonitorInfoNew->hMonitor = MonitorFromRect(&pMonitorInfoNew->rcScreen, MONITOR_DEFAULTTONULL);
}
m_dwNumMonitors++;
if (m_dwNumMonitors == MAX_DISPLAYS) {
break;
}
}
iDevice++;
}
}
BOOL CScreensaver::UtilGetRegKey(LPCTSTR name, DWORD& keyval) {
LONG error;
DWORD type = REG_DWORD;
DWORD size = sizeof(DWORD);
DWORD value;
HKEY boinc_key;
if (m_bIs9x) {
error = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Screensaver"),
0,
KEY_ALL_ACCESS,
&boinc_key
);
if (error != ERROR_SUCCESS) return FALSE;
} else {
error = RegOpenKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Screensaver"),
0,
KEY_ALL_ACCESS,
&boinc_key
);
if (error != ERROR_SUCCESS) return FALSE;
}
error = RegQueryValueEx(boinc_key, name, NULL, &type, (BYTE *)&value, &size);
keyval = value;
RegCloseKey(boinc_key);
if (error != ERROR_SUCCESS) return FALSE;
return TRUE;
}
BOOL CScreensaver::UtilSetRegKey(LPCTSTR name, DWORD value) {
LONG error;
HKEY boinc_key;
if (m_bIs9x) {
error = RegCreateKeyEx(
HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Screensaver"),
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_READ | KEY_WRITE,
NULL,
&boinc_key,
NULL
);
if (error != ERROR_SUCCESS) return FALSE;
} else {
error = RegCreateKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Screensaver"),
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_READ | KEY_WRITE,
NULL,
&boinc_key,
NULL
);
if (error != ERROR_SUCCESS) return FALSE;
}
error = RegSetValueEx(boinc_key, name, 0, REG_DWORD, (CONST BYTE *)&value, 4);
RegCloseKey(boinc_key);
return TRUE;
}
BOOL CScreensaver::UtilGetRegDirectoryStr(LPCTSTR szTargetName, std::string& strDirectory) {
LONG lReturnValue;
HKEY hkSetupHive;
LPTSTR lpszRegistryValue = NULL;
DWORD dwSize = 0;
// change the current directory to the boinc data directory if it exists
lReturnValue = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"),
0,
KEY_READ,
&hkSetupHive
);
if (lReturnValue == ERROR_SUCCESS) {
// How large does our buffer need to be?
lReturnValue = RegQueryValueEx(
hkSetupHive,
szTargetName,
NULL,
NULL,
NULL,
&dwSize
);
if (lReturnValue != ERROR_FILE_NOT_FOUND) {
// Allocate the buffer space.
lpszRegistryValue = (LPTSTR) malloc(dwSize);
(*lpszRegistryValue) = NULL;
// Now get the data
lReturnValue = RegQueryValueEx(
hkSetupHive,
szTargetName,
NULL,
NULL,
(LPBYTE)lpszRegistryValue,
&dwSize
);
// Store the directory for later use.
strDirectory = lpszRegistryValue;
} else {
return FALSE;
}
} else {
return FALSE;
}
// Cleanup
if (hkSetupHive) RegCloseKey(hkSetupHive);
return TRUE;
}
// Desc: Create the infrastructure for thread safe acccess to the infrastructure
// layer of the screen saver.
//
BOOL CScreensaver::CreateInfrastructureMutexes() {
m_hErrorManagementMutex = CreateMutex(NULL, FALSE, NULL);
if (NULL == m_hErrorManagementMutex) {
BOINCTRACE(_T("CScreensaver::CreateInfrastructureMutexes: Failed to create m_hErrorManagementMutex '%d'\n"), GetLastError());
return FALSE;
}
return TRUE;
}
// Provide a thread-safe implementation for retrieving the current
// error condition.
//
BOOL CScreensaver::GetError(
BOOL& bErrorMode, HRESULT& hrError, TCHAR* pszError, size_t iErrorSize
) {
DWORD dwWaitResult;
BOOL bRetVal = FALSE;
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
m_hErrorManagementMutex, // handle to mutex
5000L); // five-second time-out interval
switch (dwWaitResult) {
// WAIT_OBJECT_0 - The thread got mutex ownership.
case WAIT_OBJECT_0:
bErrorMode = m_bErrorMode;
hrError = m_hrError;
if (NULL != pszError) {
StringCbCopyN(pszError, iErrorSize, m_szError, sizeof(m_szError) * sizeof(TCHAR));
}
bRetVal = TRUE;
break;
// WAIT_TIMEOUT - Cannot get mutex ownership due to time-out.
// WAIT_ABANDONED - Got ownership of the abandoned mutex object.
case WAIT_TIMEOUT:
case WAIT_ABANDONED:
break;
}
ReleaseMutex(m_hErrorManagementMutex);
return bRetVal;
}
// Provide a thread-safe implementation for setting the current
// error condition. This API should only be called in the data management
// thread, any other thread may cause a race condition.
//
BOOL CScreensaver::SetError(BOOL bErrorMode, HRESULT hrError) {
DWORD dwWaitResult;
BOOL bRetVal = FALSE;
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
m_hErrorManagementMutex, // handle to mutex
5000L // five-second time-out interval
);
switch (dwWaitResult) {
// WAIT_OBJECT_0 - The thread got mutex ownership.
case WAIT_OBJECT_0:
m_bErrorMode = bErrorMode;
m_hrError = hrError;
// Update the error text, including a possible RPC call
// to the daemon.
UpdateErrorBoxText();
bRetVal = TRUE;
break;
// WAIT_TIMEOUT - Cannot get mutex ownership due to time-out.
// WAIT_ABANDONED - Got ownership of the abandoned mutex object.
case WAIT_TIMEOUT:
case WAIT_ABANDONED:
break;
}
ReleaseMutex(m_hErrorManagementMutex);
return bRetVal;
}
// Update the error message
//
VOID CScreensaver::UpdateErrorBoxText() {
// Load error string
GetTextForError(m_hrError, m_szError, sizeof(m_szError) / sizeof(TCHAR));
BOINCTRACE(_T("CScreensaver::UpdateErrorBoxText - Updated Text '%s'\n"), m_szError);
}
// Translate an HRESULT error code into a string that can be displayed
// to explain the error. A class derived from CD3DScreensaver can
// provide its own version of this function that provides app-specific
// error translation instead of or in addition to calling this function.
// This function returns TRUE if a specific error was translated, or
// FALSE if no specific translation for the HRESULT was found (though
// it still puts a generic string into pszError).
//
BOOL CScreensaver::GetTextForError(
HRESULT hr, TCHAR* pszError, DWORD dwNumChars
) {
const DWORD dwErrorMap[][2] = {
// HRESULT, stringID
E_FAIL, IDS_ERR_GENERIC,
E_OUTOFMEMORY, IDS_ERR_OUTOFMEMORY,
SCRAPPERR_NOPREVIEW, IDS_ERR_NOPREVIEW,
SCRAPPERR_BOINCSCREENSAVERLOADING, IDS_ERR_BOINCSCREENSAVERLOADING,
SCRAPPERR_BOINCSHUTDOWNEVENT, IDS_ERR_BOINCSHUTDOWNEVENT,
SCRAPPERR_BOINCAPPFOUNDGRAPHICSLOADING, IDS_ERR_BOINCAPPFOUNDGRAPHICSLOADING,
SCRAPPERR_BOINCNOTDETECTED, IDS_ERR_BOINCNOTDETECTED,
SCRAPPERR_BOINCSUSPENDED, IDS_ERR_BOINCSUSPENDED,
SCRAPPERR_BOINCNOAPPSEXECUTING, IDS_ERR_BOINCNOAPPSEXECUTING,
SCRAPPERR_BOINCNOPROJECTSDETECTED, IDS_ERR_BOINCNOAPPSEXECUTINGNOPROJECTSDETECTED,
SCRAPPERR_BOINCNOGRAPHICSAPPSEXECUTING, IDS_ERR_BOINCNOGRAPHICSAPPSEXECUTING,
SCRAPPERR_DAEMONALLOWSNOGRAPHICS, IDS_ERR_DAEMONALLOWSNOGRAPHICS
};
const DWORD dwErrorMapSize = sizeof(dwErrorMap) / sizeof(DWORD[2]);
DWORD iError;
DWORD resid = 0;
for(iError = 0; iError < dwErrorMapSize; iError++) {
if (hr == (HRESULT)dwErrorMap[iError][0]) {
resid = dwErrorMap[iError][1];
}
}
if (resid == 0) {
resid = IDS_ERR_GENERIC;
}
LoadString(NULL, resid, pszError, dwNumChars);
if (resid == IDS_ERR_GENERIC) {
return FALSE;
} else {
return TRUE;
}
}
// Create the thread that is used to monitor input activity.
//
BOOL CScreensaver::CreateInputActivityThread() {
DWORD dwThreadID = 0;
BOINCTRACE(_T("CScreensaver::CreateInputActivityThread Start\n"));
m_hInputActivityThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
InputActivityProcStub, // thread function
NULL, // argument to thread function
0, // use default creation flags
&dwThreadID ); // returns the thread identifier
if (m_hInputActivityThread == NULL) {
BOINCTRACE(_T("CScreensaver::CreateInputActivityThread: Failed to create input activity thread '%d'\n"), GetLastError());
return FALSE;
}
m_tThreadCreateTime = time(0);
return TRUE;
}
// Terminate the thread that is used to monitor input activity.
//
BOOL CScreensaver::DestroyInputActivityThread() {
if (!TerminateThread(m_hInputActivityThread, 0)) {
BOINCTRACE(_T("CScreensaver::DestroyInputActivityThread: Failed to terminate input activity thread '%d'\n"), GetLastError());
return FALSE;
}
return TRUE;
}
// This function forwards to InputActivityProc, which has access to the
// "this" pointer.
//
DWORD WINAPI CScreensaver::InputActivityProcStub(LPVOID UNUSED(lpParam)) {
return gspScreensaver->InputActivityProc();
}
// Some graphics applications take a really long time to display something on their
// window, during this time the window will appear to eat keyboard and mouse event
// messages and not respond to other system events. These windows are considered
// ghost windows, normally they have an outline and can be moved around and resized.
// In the graphic applications case where the borders are hidden from view, the
// window just takes on the background of the previous window which happens to be
// the black screensaver window owned by this process.
//
// Verify that their hasn't been any keyboard or mouse activity. If there has,
// we should hide the window from this process and exit out of the screensaver to
// return control back to the user as quickly as possible.
//
DWORD WINAPI CScreensaver::InputActivityProc() {
LASTINPUTINFO lii;
lii.cbSize = sizeof(LASTINPUTINFO);
while(true) {
if (gspfnMyGetLastInputInfo) {
gspfnMyGetLastInputInfo(&lii);
if (m_dwLastInputTimeAtStartup != lii.dwTime) {
BOINCTRACE(_T("CScreensaver::InputActivityProc - Activity Detected.\n"));
SetError(TRUE, SCRAPPERR_BOINCSHUTDOWNEVENT);
FireInterruptSaverEvent();
}
}
boinc_sleep(0.25);
}
}
// Create the thread that is used to promote the graphics window.
//
BOOL CScreensaver::CreateGraphicsWindowPromotionThread() {
DWORD dwThreadID = 0;
BOINCTRACE(_T("CScreensaver::CreateGraphicsWindowPromotionThread Start\n"));
m_hGraphicsWindowPromotionThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
GraphicsWindowPromotionProcStub, // thread function
NULL, // argument to thread function
0, // use default creation flags
&dwThreadID ); // returns the thread identifier
if (m_hGraphicsWindowPromotionThread == NULL) {
BOINCTRACE(_T("CScreensaver::CreateGraphicsWindowPromotionThread: Failed to create graphics window promotion thread '%d'\n"), GetLastError());
return FALSE;
}
return TRUE;
}
// Terminate the thread that is used to promote the graphics window.
//
BOOL CScreensaver::DestroyGraphicsWindowPromotionThread() {
if (!TerminateThread(m_hGraphicsWindowPromotionThread, 0)) {
BOINCTRACE(_T("CScreensaver::DestroyGraphicsWindowPromotionThread: Failed to terminate graphics window promotion thread '%d'\n"), GetLastError());
return FALSE;
}
return TRUE;
}
// This function forwards to GraphicsWindowPromotionProc, which has access to the
// "this" pointer.
//
DWORD WINAPI CScreensaver::GraphicsWindowPromotionProcStub(LPVOID UNUSED(lpParam)) {
return gspScreensaver->GraphicsWindowPromotionProc();
}
// When running in screensaver mode the only two valid conditions for z-order
// is that either the screensaver or graphics application is the foreground
// application. If this is not true, then blow out of the screensaver.
//