-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathSpiSettingsHandler.js
More file actions
1079 lines (962 loc) · 40.1 KB
/
SpiSettingsHandler.js
File metadata and controls
1079 lines (962 loc) · 40.1 KB
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
/*!
Windows SystemParametersInfo Settings Handler
Copyright 2012 Antranig Basman
Copyright 2012 Astea Solutions AD
Copyright 2014 OCAD University
Copyright 2014 Lucendo Development Ltd.
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.
You may obtain a copy of the License at
https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var ref = require("ref-napi"),
ffi = require("ffi-napi"),
fs = require("fs"),
path = require("path"),
mkdirp = require("mkdirp"),
rimraf = require("rimraf"),
semver = require("semver"),
child_process = require("child_process");
var fluid = require("gpii-universal");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.windows.spi");
fluid.registerNamespace("gpii.windows.spiSettingsHandler");
require("../../WindowsUtilities/WindowsUtilities.js");
require("../../processHandling/processHandling.js");
require("../../gpii-localisation/index.js");
var os = require("os");
// Guide to node-ffi types and conversions:
// https://github.com/rbranson/node-ffi/wiki/Node-FFI-Tutorial
// SystemParametersInfoW
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
// UINT, UINT, PVOID, UINT; return type: BOOL
// We declare 2 versions of SystemParametersInfoW:
// - one with a void* signature for the pvParam parameter and
// - one with an integer signature for pvParam.
// For cases in which calls on SPI_SET* actions need a BOOL or UINT pvParam,
// the BOOL or UINT value is passed directly in pvParam, rather than as a
// pointer.
gpii.windows.spi.systemParametersInfoWPtr = ffi.Library("user32", {
"SystemParametersInfoW": [
"int32", [ "uint32", "uint32", "void*", "uint32" ]
]
});
gpii.windows.spi.systemParametersInfoWUint = ffi.Library("user32", {
"SystemParametersInfoW": [
"int32", [ "uint32", "uint32", "uint32", "uint32" ]
]
});
/**
* Makes a call to SystemParametersInfoW with the get action to retrieve the current settings applied on the system.
* @param {Object} payload Settings handler payload.
* @return {Object} The current settings.
*/
gpii.windows.spi.getCurrentSettings = function (payload) {
var getAction = gpii.windows.spi.actions[payload.options.getAction];
var uiParam = gpii.windows.spi.getUiParam(payload);
var pvParam = gpii.windows.spi.createPvParam(payload);
var currentSettings = {
"uiParam": uiParam,
"pvParam": undefined
};
if (getAction === gpii.windows.spi.actions.SPI_GETMOUSEBUTTONSWAP) {
var swapped = gpii.windows.user32.GetSystemMetrics(gpii.windows.API_constants.SM_SWAPBUTTON);
currentSettings.pvParam = swapped;
} else {
var callSuccessful = gpii.windows.spi.systemParametersInfoWPtr.SystemParametersInfoW(getAction, uiParam, pvParam, 0);
if (!callSuccessful) {
var errorCode = gpii.windows.kernel32.GetLastError();
fluid.fail("SpiSettingsHandler.js: spi.getCurrentSettings() failed with error code " + errorCode + ".");
}
currentSettings.pvParam = (payload.options.pvParam.type === "array") ?
gpii.windows.bufferToArray(pvParam, payload.options.pvParam.valueType) :
pvParam.deref();
}
return currentSettings;
};
/**
* Perform the actual call to SystemParametersInfo.
*
* @param {String} pvParamType The type of pvParam, "BOOL", "UINT", or something else.
* @param {Number} action The system parameter to retrieve or set (SPI_xxx).
* @param {Number} uiParam Parameter specific to the action.
* @param {Number|Buffer} pvParam Parameter specific to the action.
* @param {Number} fWinIni Specifies if a WM_SETTINGCHANGE message will be broadcast to all top-level windows.
* @return {Boolean} true if the call was a success.
*/
gpii.windows.spi.systemParametersInfo = function (pvParamType, action, uiParam, pvParam, fWinIni) {
var callSuccessful = 0;
if (pvParamType === "BOOL" || pvParamType === "UINT") {
callSuccessful = gpii.windows.spi.systemParametersInfoWUint.SystemParametersInfoW(action, uiParam, pvParam, fWinIni);
} else {
callSuccessful = gpii.windows.spi.systemParametersInfoWPtr.SystemParametersInfoW(action, uiParam, pvParam, fWinIni);
}
return callSuccessful;
};
/**
* Waits for a previous call to SPI to complete. This is to work-around the high-contrast change
* taking some time to complete, and to prevent other calls in the meantime.
*
* @param {Number} action The action parameter of the SystemParametersInfo call.
* @return {promise} A promise that resolves when the last SPI call is complete.
*/
gpii.windows.spi.waitForSpi = function (action) {
if (action === gpii.windows.spi.actions.SPI_SETHIGHCONTRAST) {
/*
* Experimentation has uncovered an undocumented occurrence when the high-contrast is changed
* via the SPI call, where Windows executes %WINDIR%\system32\sethc.exe to perform the actual
* work of changing the contrast. Investigations have shown that this executable may be
* called with parameters "10", "11", "100", or "101" (numbers < 100 turn HC off).
*
* It has been noticed that the work behind setting SPI_SETHIGHCONTRAST is complete when
* this process terminates, so this script checks for the existence of this process and
* does not return until the has ended.
*/
return gpii.windows.waitForProcessTermination("sethc.exe");
} else {
// The setting has been applied as soon as SPI returns.
return fluid.promise().resolve();
}
};
/**
* Performs the SPI call in a child-process. This is used on certain SPI_SET* calls to SPI that are known to be
* troublesome and have the potential to hang, or when calling with fWinIni=SPIF_SENDCHANGE.
*
* See GPII-2001 for an example, where a system process causes this phenomenon. While it may be possible to fix that
* particular issue, it raises the question: what prevents other processes from doing the same? To work around this,
* the call to SystemParametersInfo (for problematic actions) shall be invoked in a separate process.
*
* A promise is returned, resolving with the return value of the SystemParametersInfo, or rejects if the call does not
* complete in a timely manner.
*
* @param {String} pvParamType The data type of pvParam.
* @param {Number} action The uiAction SPI parameter.
* @param {Number} uiParam The uiParam SPI parameter.
* @param {Number|Buffer} pvParam The pvParam SPI parameter.
* @param {Number} fWinIni Specifies if a WM_SETTINGCHANGE message will be broadcast to all top-level windows.
* @return {promise} Rejects if the SPI call hangs.
*/
gpii.windows.spi.callProblematicSpi = function (pvParamType, action, uiParam, pvParam, fWinIni) {
var cp = require("child_process");
var primitiveType = pvParamType in gpii.windows.types;
var options = {
env: {
GPII_SPI_ACTION: action,
GPII_SPI_UIPARAM: uiParam,
GPII_SPI_PVPARAM_PRIMITIVE: primitiveType ? 1 : 0,
GPII_SPI_PVPARAM: primitiveType ? pvParam : pvParam.toString("hex"),
GPII_SPI_FWININI: fWinIni
},
execArgv: []
};
var child = cp.fork(__dirname + "/SpiChildProcess.js", options);
var promise = fluid.promise();
var timer = setTimeout(function () {
child.kill();
timer = null;
}, 10000);
child.on("exit", function (code) {
if (timer) {
clearTimeout(timer);
}
if (code === null) {
// The child process was killed.
fluid.log("SPI call has failed");
promise.reject({
isError: true,
message: "Timed out waiting for the SPI call to complete (see GPII-2001)"
});
} else {
promise.resolve(code);
}
});
return promise;
};
/**
* Applies the settings stored in the payload, making a call to SystemParametersInfoW with the
* set action.
* @param {Object} payload The payload.
* @return {Promise} Resolves when the setting is applied.
*/
gpii.windows.spi.applySettings = function (payload) {
var action = gpii.windows.spi.actions[payload.options.setAction];
var uiParam = gpii.windows.spi.getUiParam(payload);
var pvParam = gpii.windows.spi.getPvParam(payload);
var fWinIni = 0;
if (fluid.get(payload, "options.fWinIni") !== undefined) {
fWinIni = gpii.windows.resolveFlags(payload.options.fWinIni, gpii.windows.API_constants.SpiFlags);
}
uiParam = pvParam.uiParam; // this will be updated because it looks bad
pvParam = pvParam.pvParam;
var pvParamType = payload.options.pvParam.type;
var promiseTogo = fluid.promise();
// The SPI_SET* calls that could potentially halt the process.
var problematicSpiCalls = [
gpii.windows.spi.actions.SPI_SETNONCLIENTMETRICS
];
// Wait for sethc.exe to end before making the SPI call
gpii.windows.spi.waitForSpi()
.then(function () {
// SPIF_SENDCHANGE broadcasts several messages and has the potential to block, so call it in a child
// process.
var sendChange = (fWinIni & gpii.windows.API_constants.SpiFlags.SPIF_SENDCHANGE) ===
gpii.windows.API_constants.SpiFlags.SPIF_SENDCHANGE;
if (sendChange || (problematicSpiCalls.indexOf(action) >= 0)) {
var p = gpii.windows.spi.callProblematicSpi(pvParamType, action, uiParam, pvParam, fWinIni);
fluid.promise.follow(p, promiseTogo);
} else {
var callSuccessful = gpii.windows.spi.systemParametersInfo(pvParamType, action, uiParam, pvParam, fWinIni);
if (callSuccessful) {
fluid.promise.follow(gpii.windows.spi.waitForSpi(action), promiseTogo);
} else {
// Log information about the failing payload.
fluid.log("Could not work with SPI payload:\n" + JSON.stringify(payload, null, 2));
var errorCode = gpii.windows.kernel32.GetLastError();
fluid.fail("SpiSettingsHandler.js: spi.applySettings() failed with error code " + errorCode + ".");
}
}
});
return promiseTogo;
};
/**
* Populates the results payload that is returned from the <code>SpiSettingsHandler</code>. These
* results contain the old and new values for each setting in the input payload.
*
* @param {Object} payload The input that is passed to the SPI Settings Handler
* @param {Boolean} isNewValue True if the updated values of the settings are populated, false
* otherwise.
* @param {Boolean} isGetting True if called within spiSettingsHandler.get, false otherwise.
* @param {Object} results The results object to be populated with the old and new settings values.
*/
gpii.windows.spi.populateResults = function (payload, isNewValue, isGetting, results) {
var systemSettings = gpii.windows.spi.getCurrentSettings(payload);
for (var currentSetting in payload.settings) {
if (!isNewValue || isGetting) {
results[currentSetting] = {};
}
var path = payload.settings[currentSetting].path;
if (path.get !== undefined) {
path = path.get;
}
var valueToSet = gpii.windows.resolvePath(systemSettings, path);
if (isGetting) {
results[currentSetting] = {
value: valueToSet,
path: payload.settings[currentSetting].path
};
} else {
results[currentSetting][isNewValue ? "newValue" : "oldValue"] = valueToSet;
}
}
};
/**
* Returns the value for the uiParam parameter of the SystemParametersInfo function from the
* payload.
* @param {Object} payload The payload.
* @return {Number} The uiParam value.
*/
gpii.windows.spi.getUiParam = function (payload) {
var uiParam = payload.options.uiParam;
if (!isNaN(Number(uiParam))) {
return Number(uiParam);
}
if (uiParam === "true" || uiParam === "false") {
return Number(uiParam === "true");
}
if (uiParam === "struct_size") {
var result = gpii.windows.structures[payload.options.pvParam.name].size;
if (payload.options.pvParam.name === "NONCLIENTMETRICS" && os.release() < "6") {
result -= 4; // do not include NONCLIENTMETRICS.iPaddedBorderWidth
}
return result;
}
console.log("SpiSettingsHandler.js: spi.getUiParam() got unknown uiParam value: " + uiParam + " of type " + typeof uiParam + ".");
return 0;
};
/**
* Returns an empty pvParam - creates an empty structure or allocates memory for a
* given type. Primarily called as part of <code>getCurrentSettings</code>
*
* @param {Object} payload The payload.
* @return {Buffer} The empty pvParam structure.
*/
gpii.windows.spi.createPvParam = function (payload) {
var pvParam;
switch (payload.options.pvParam.type) {
case "struct":
pvParam = gpii.windows.createEmptyStructure(payload.options.pvParam.name).ref();
break;
case "array":
var length = payload.options.pvParam.length;
var size = ref.types[gpii.windows.types[payload.options.pvParam.valueType]].size;
pvParam = new Buffer(length * size);
break;
case "NULL":
pvParam = ref.NULL;
break;
default:
if (payload.options.pvParam.type in gpii.windows.types) {
pvParam = ref.alloc(gpii.windows.types[payload.options.pvParam.type]);
} else {
fluid.fail("SpiSettingsHandler.js: spi.createPvParam() failed: got unknown pvParam type " + payload.options.pvParam.type);
}
}
return pvParam;
};
/**
* Creates a pvParam populated with the settings requested in the payload.
* Primarily used within <code>applySettings</code>
*
* @param {Object} payload The payload.
* @return {Object} The pvParam settings..
*/
gpii.windows.spi.getPvParam = function (payload) {
var systemSettings = gpii.windows.spi.getCurrentSettings(payload);
var pvParam = systemSettings.pvParam;
for (var currentSetting in payload.settings) {
var path = payload.settings[currentSetting].path;
if (path.set !== undefined) {
path = path.set;
}
gpii.windows.resolvePath(systemSettings, path, payload.settings[currentSetting].value);
}
if (payload.options.pvParam.type === "array") {
if (payload.options.pvParam.valueType === "TCHAR") {
pvParam = systemSettings.pvParam;
} else {
pvParam = gpii.windows.arrayToBuffer(systemSettings.pvParam, payload.options.pvParam.valueType);
}
} else if (payload.options.pvParam.type in gpii.windows.types) {
pvParam = systemSettings.pvParam;
} else if (payload.options.pvParam.type === "struct") {
pvParam = pvParam.ref();
}
systemSettings.pvParam = pvParam;
return systemSettings;
};
/**
* Entry point function of the component. Takes a payload as an input and sets the corresponding
* settings using the SystemParametersInfoW Windows API function. Returns a promise, resolving
* to an object containing the old and new values for each of the settings, when the setting has
* been applied.
*
* @param {Object} payload The payload.
* @return {Promise} Resolves when the settings have been applied.
*/
gpii.windows.spi.setImpl = function (payload) {
gpii.windows.defineStruct(payload);
var togo = fluid.promise();
var results = {};
// Hack for GPII-4087, the high-contrast is being set to "off" even when it's already "off". This causes Windows
// to reload the default theme (or last saved?) - causing any custom wallpaper to be lost.
// This hack just gets the current high-contrast state and does nothing if it's already turned off.
var applyPromise;
if (payload.settings.HighContrastOn) {
var doNothing = false;
if (!payload.settings.HighContrastOn.value && !payload.settings.HighContrastTheme) {
var currentState = gpii.windows.spi.getImpl(fluid.copy(payload));
if (!currentState.HighContrastOn.value) {
doNothing = true;
}
}
if (doNothing) {
applyPromise = fluid.promise().resolve();
} else {
var cachedFilesPath = path.join(process.env.APPDATA, "Microsoft\\Windows\\Themes\\CachedFiles");
try {
rimraf.sync(cachedFilesPath);
} catch (e) {
// ignore
}
var tWallpaperPath = path.join(process.env.APPDATA, "Microsoft\\Windows\\Themes\\TranscodedWallpaper");
try {
fs.unlinkSync(tWallpaperPath);
} catch (e) {
// ignore
}
}
}
gpii.windows.spi.populateResults(payload, false, false, results);
if (!applyPromise) {
applyPromise = gpii.windows.spi.applySettings(payload);
}
applyPromise.then(function () {
gpii.windows.spi.populateResults(payload, true, false, results);
gpii.windows.spi.GPII1873_HighContrastBug("SET", payload, results);
// transform results here oldValue: x --> oldValue: { value: x, path: ... }
fluid.each(results, function (value, setting) {
results[setting].oldValue = {"value": value.oldValue, "path": payload.settings[setting].path};
results[setting].newValue = {"value": value.newValue, "path": payload.settings[setting].path};
});
fluid.log("SPI settings handler SET returning results ", results);
togo.resolve(results);
}, togo.reject);
return togo;
};
gpii.windows.spiSettingsHandler.set = function (payload) {
return gpii.settingsHandlers.invokeSettingsHandler(gpii.windows.spi.setImpl, payload);
};
gpii.windows.spi.getImpl = function (payload) {
gpii.windows.defineStruct(payload);
var results = {};
gpii.windows.spi.populateResults(payload, false, true, results);
gpii.windows.spi.GPII1873_HighContrastBug("GET", payload, results);
return results;
};
gpii.windows.spiSettingsHandler.get = function (payload) {
return gpii.settingsHandlers.invokeSettingsHandler(gpii.windows.spi.getImpl, payload);
};
/**
* To change the cursor size one must perform the following two steps:
* First write the path to the new cursor icons in the registry. This is done by the Registry
* Settings Handler.
*
* After that we must tell the system to load those new icons, calling SystemParametersInfo
* with the SPI_SETCURSORS action.
*
* The purpose of this function is to perform the second step.
*/
gpii.windows.spiSettingsHandler.updateCursors = function () {
// Call SPI with the SPI_SETCURSORS uiAction
gpii.windows.spi.systemParametersInfoWUint.SystemParametersInfoW(0x57, 0, 0, 0);
};
fluid.defaults("gpii.windows.spiSettingsHandler.updateCursors", {
gradeNames: "fluid.function",
argumentMap: {}
});
/**
* Fix for GPII-1873.
*
* This method overrides the output of the system based on the payload information. We
* actually know that Windows have a bug that disallow us to reset to the HighContrastTheme
* default scheme to null or empty string. That is the reason we are circumventing the
* output of this HIGHCONTRAST methods.
*
* More information at https://issues.gpii.net/browse/GPII-1873
*
* @param {String} method "GET" or "SET".
* @param {Object} payload The payload.
* @param {Object} results The results, which will be modified to set high-contrast theme to empty if appropriate.
*/
gpii.windows.spi.GPII1873_HighContrastBug = function (method, payload, results) {
if ((payload.options.pvParam.type === "struct") &&
(payload.options.pvParam.name === "HIGHCONTRAST")) {
if (payload.settings.HighContrastTheme &&
payload.settings.HighContrastTheme.value === "") {
fluid.log("Bug #1873 detected. We are forcing the return value to empty string although the system cannot set to it.");
if (method === "SET") {
results.HighContrastTheme.newValue = "";
} else {
results.HighContrastTheme.value = "";
}
}
}
};
/**
* Saves the current theme, then configures a high-contrast theme, specified from the given .theme file. This setting
* tells SystemParametersInfo which theme to use.
*
* In the registry, the themes are referred to by their display name. This is identified in the .theme file by the
* DisplayName value in the [Theme] section.
*
* There is an additional complexity where the display names of the built-in themes are localised. Fortunately, there
* is an API call that performs this localisation.
*
* This function reads this display name from a .theme file, gets the localised name (if required) and sets it in the
* registry so when SystemParametersInfo is called, the specified theme will be used.
*
* @param {String} newThemeFile The .theme file, which is in INI file format.
* @param {String} currentThemeFile The current .theme file, which is in INI file format.
* @param {String} saveAs The .theme file to which the current theme is saved.
* @param {Boolean} dryRun true to not update the registry.
* @return {Promise<String>} A promise, resolving with the display name of the theme specified in the .theme file.
*/
gpii.windows.spiSettingsHandler.setHighContrastTheme = function (newThemeFile, currentThemeFile, saveAs, dryRun) {
if (saveAs && saveAs.endsWith("Morphic.theme")) {
gpii.windows.spiSettingsHandler.saveTheme(currentThemeFile, saveAs);
}
// The filename may contain environment variables, "%LikeThis%".
if (newThemeFile.indexOf("%") >= 0) {
newThemeFile = newThemeFile.replace(/%([^%]+)%/g, function (m, name) {
return process.env[name] || "";
});
}
var themeData;
try {
themeData = newThemeFile && gpii.iniFile.readFile(newThemeFile);
} catch (e) {
fluid.log(e.message);
themeData = null;
}
var promise;
// Get the localised display name of the theme.
if (themeData && themeData.Theme) {
// 10.0.17134 = Windows 1803
var windows1809 = semver.gt(os.release(), "10.0.17134");
// For windows 10 1809 or above, the name of the built-in theme which the custom theme is based on is used.
if (windows1809) {
// In a custom theme, the HighContrast value is a number from 1-4 which identifies the built-in theme upon
// which this theme is based.
var highContrastId = themeData.VisualStyles && themeData.VisualStyles.HighContrast;
if (highContrastId) {
promise = gpii.windows.spiSettingsHandler.getLocalisedThemeName(highContrastId);
}
}
if (!promise) {
promise = fluid.promise().resolve(gpii.windows.getIndirectString(themeData.Theme.DisplayName));
}
promise.then(function (displayName) {
console.log(displayName);
if (displayName && !dryRun) {
gpii.windows.writeRegistryKey("HKEY_CURRENT_USER", "Control Panel\\Accessibility\\HighContrast",
"High Contrast Scheme", displayName, "REG_SZ");
// Store the current theme file so it can be referred to later.
gpii.windows.writeRegistryKey(
"HKEY_CURRENT_USER", "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\HighContrast",
"LastSet", newThemeFile, "REG_SZ");
}
}, function (reason) {
console.log(reason);
});
} else {
promise = fluid.toPromise(undefined);
}
return promise;
};
/** Cache for getLocalisedThemeName */
gpii.windows.spiSettingsHandler.getLocalisedThemeNameCache = {};
// Attaches to the language component to update the localised theme names when the language changes.
fluid.defaults("gpii.windows.spiSettingsHandler.highContrastThemes", {
gradeNames: ["fluid.modelComponent"],
modelListeners: {
"{gpii.windows.language}.model.installedLanguages": {
funcName: "gpii.windows.spiSettingsHandler.getLocalisedThemeName",
args: [1]
}
}
});
fluid.makeGradeLinkage("gpii.windows.spiSettingsHandler.highContrastThemesLink",
["gpii.windows.language"],
"gpii.windows.spiSettingsHandler.highContrastThemes"
);
/**
* Gets the localised name of the high-contrast themes, for the current language. Windows appears to use the localised
* name of the high-contrast theme. [GPII-3811]
*
* This starts a child process in order to use the system's current language, because it may be different to when this
* process had started with.
*
* @param {Number} highContrastId The HighContrast value of the .theme file, 1-4.
* @return {Promise} Resolves with the localised name of the high-contrast theme.
*/
gpii.windows.spiSettingsHandler.getLocalisedThemeName = function (highContrastId) {
var promise = fluid.promise();
var currentLanguage = gpii.windows.language.getDisplayLanguage();
var themeNames = gpii.windows.spiSettingsHandler.getLocalisedThemeNameCache[currentLanguage];
if (themeNames) {
promise.resolve(themeNames[highContrastId - 1]);
} else {
var options = {
env: {
},
execArgv: []
};
var child = child_process.fork(__dirname + "/GetHighContrastSchemeName.js", options);
var timer = setTimeout(function () {
child.kill();
timer = null;
}, 10000);
child.on("message", function (hcNames) {
gpii.windows.spiSettingsHandler.getLocalisedThemeNameCache[currentLanguage] = hcNames;
promise.resolve(hcNames[highContrastId - 1]);
});
child.on("exit", function () {
if (timer) {
clearTimeout(timer);
}
if (!promise.disposition) {
fluid.log("Error: Getting high-contrast localized name failed.");
promise.reject({
isError: true,
message: "Timed out waiting for high-contrast localized name."
});
}
});
}
return promise;
};
/**
* Saves the active changes to the current theme.
*
* This is needed to be performed before enabling high-contrast because when high-contrast is de-activated it loads
* the settings (such as the wallpaper) from the .theme file, rather than the last settings. [GPII-2618]
*
* Theme files are described in https://docs.microsoft.com/en-us/windows/desktop/controls/themesfileformat-overview
*
* @param {String} currentThemeFile The .theme file that's currently being used.
* @param {String} saveAs The temporary .theme file to which the current theme is saved.
*/
gpii.windows.spiSettingsHandler.saveTheme = function (currentThemeFile, saveAs) {
var themeData = currentThemeFile && gpii.iniFile.readFile(currentThemeFile);
fluid.log("Saving theme from " + currentThemeFile);
var isValid = themeData && !!(themeData.MasterThemeSelector && themeData.MasterThemeSelector.MTSM);
if (!isValid) {
fluid.log("Theme file invalid.");
// If the theme file isn't valid, load the default one.
var defaultTheme = path.join(process.env.SystemRoot, "resources/Themes/aero.theme");
if (currentThemeFile !== defaultTheme) {
gpii.windows.spiSettingsHandler.saveTheme(defaultTheme, saveAs);
}
} else if (!themeData.VisualStyles || !themeData.VisualStyles.HighContrast) {
// Only save the current theme if it is not high-contrast. Otherwise, when changing the high-contrast theme
// in the QSS, the current high-contrast theme is saved over the last non-high-contrast theme. This causes the
// theme to be incorrectly restored when turning off high-contrast.
// Wallpaper
var desktop = themeData["Control Panel\\Desktop"];
if (!desktop) {
desktop = {};
themeData["Control Panel\\Desktop"] = desktop;
}
desktop.Wallpaper =
gpii.windows.readRegistryKey("HKEY_CURRENT_USER", "Control Panel\\Desktop", "WallPaper", "REG_SZ").value;
desktop.TileWallpaper =
gpii.windows.readRegistryKey("HKEY_CURRENT_USER", "Control Panel\\Desktop", "TileWallpaper", "REG_SZ").value;
desktop.WallpaperStyle =
gpii.windows.readRegistryKey("HKEY_CURRENT_USER", "Control Panel\\Desktop", "WallpaperStyle", "REG_SZ").value;
var backgroundType = gpii.windows.readRegistryKey("HKEY_CURRENT_USER",
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Wallpapers", "BackgroundType", "REG_DWORD").value;
if (backgroundType !== 2) {
// If it's not a slideshow, then remove the entire section.
delete themeData.Slideshow;
}
// Colours
var colors = gpii.windows.enumRegistryValues("HKEY_CURRENT_USER", "Control Panel\\Colors");
if (!themeData["Control Panel\\Colors"]) {
themeData["Control Panel\\Colors"] = {};
}
fluid.each(colors, function (key) {
themeData["Control Panel\\Colors"][key.name] = key.data;
});
// Update the settings from the current theme, saving it into the new file.
var iniData = gpii.iniFile.writeFromFile(currentThemeFile, themeData);
var directory = path.dirname(saveAs);
mkdirp.sync(directory);
fs.writeFileSync(saveAs, iniData);
// Let Windows know to use this theme file when restoring high-contrast.
gpii.windows.writeRegistryKey(
"HKEY_CURRENT_USER", "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\HighContrast",
"Pre-High Contrast Scheme", saveAs, "REG_SZ");
}
};
/**
* The list of colour names for the .theme file, whose index is the value of the corresponding API constant, which are
* listed in https://docs.microsoft.com/windows/desktop/api/winuser/nf-winuser-getsyscolor
*/
gpii.windows.spiSettingsHandler.themeColours = fluid.freezeRecursive([
"Scrollbar",
"Background",
"ActiveTitle",
"InactiveTitle",
"Menu",
"Window",
"WindowFrame",
"MenuText",
"WindowText",
"TitleText",
"ActiveBorder",
"InactiveBorder",
"AppWorkspace",
"Hilight",
"HilightText",
"ButtonFace",
"ButtonShadow",
"GrayText",
"ButtonText",
"InactiveTitleText",
"ButtonHilight",
"ButtonDkShadow",
"ButtonLight",
"InfoText",
"InfoWindow",
"ButtonAlternateFace",
"HotTrackingColor",
"GradientActiveTitle",
"GradientInactiveTitle",
"MenuHilight",
"MenuBar"
]);
/**
*
*/
gpii.windows.spiSettingsHandler.applyCustomTheme = function () {
};
fluid.defaults("gpii.windows.spiSettingsHandler.setHighContrastTheme", {
gradeNames: "fluid.function",
argumentMap: {
newTheme: 0,
currentTheme: 1,
saveAs: 2
}
});
fluid.defaults("gpii.windows.spiSettingsHandler.applyCustomTheme", {
gradeNames: "fluid.function",
argumentMap: {
themeFile: 0,
allThemes: 1
}
});
/**
* All known uiAction values of SystemParametersInfo.
* Taken from WinUser.h
*/
gpii.windows.spi.actions = {
"SPI_GETBEEP": 0x0001,
"SPI_SETBEEP": 0x0002,
"SPI_GETMOUSE": 0x0003,
"SPI_SETMOUSE": 0x0004,
"SPI_GETBORDER": 0x0005,
"SPI_SETBORDER": 0x0006,
"SPI_GETKEYBOARDSPEED": 0x000A,
"SPI_SETKEYBOARDSPEED": 0x000B,
"SPI_LANGDRIVER": 0x000C,
"SPI_ICONHORIZONTALSPACING": 0x000D,
"SPI_GETSCREENSAVETIMEOUT": 0x000E,
"SPI_SETSCREENSAVETIMEOUT": 0x000F,
"SPI_GETSCREENSAVEACTIVE": 0x0010,
"SPI_SETSCREENSAVEACTIVE": 0x0011,
"SPI_GETGRIDGRANULARITY": 0x0012,
"SPI_SETGRIDGRANULARITY": 0x0013,
"SPI_SETDESKWALLPAPER": 0x0014,
"SPI_SETDESKPATTERN": 0x0015,
"SPI_GETKEYBOARDDELAY": 0x0016,
"SPI_SETKEYBOARDDELAY": 0x0017,
"SPI_ICONVERTICALSPACING": 0x0018,
"SPI_GETICONTITLEWRAP": 0x0019,
"SPI_SETICONTITLEWRAP": 0x001A,
"SPI_GETMENUDROPALIGNMENT": 0x001B,
"SPI_SETMENUDROPALIGNMENT": 0x001C,
"SPI_SETDOUBLECLKWIDTH": 0x001D,
"SPI_SETDOUBLECLKHEIGHT": 0x001E,
"SPI_GETICONTITLELOGFONT": 0x001F,
"SPI_SETDOUBLECLICKTIME": 0x0020,
"SPI_SETMOUSEBUTTONSWAP": 0x0021,
"SPI_SETICONTITLELOGFONT": 0x0022,
"SPI_GETFASTTASKSWITCH": 0x0023,
"SPI_SETFASTTASKSWITCH": 0x0024,
"SPI_SETDRAGFULLWINDOWS": 0x0025,
"SPI_GETDRAGFULLWINDOWS": 0x0026,
"SPI_GETNONCLIENTMETRICS": 0x0029,
"SPI_SETNONCLIENTMETRICS": 0x002A,
"SPI_GETMINIMIZEDMETRICS": 0x002B,
"SPI_SETMINIMIZEDMETRICS": 0x002C,
"SPI_GETICONMETRICS": 0x002D,
"SPI_SETICONMETRICS": 0x002E,
"SPI_SETWORKAREA": 0x002F,
"SPI_GETWORKAREA": 0x0030,
"SPI_SETPENWINDOWS": 0x0031,
"SPI_GETHIGHCONTRAST": 0x0042,
"SPI_SETHIGHCONTRAST": 0x0043,
"SPI_GETKEYBOARDPREF": 0x0044,
"SPI_SETKEYBOARDPREF": 0x0045,
"SPI_GETSCREENREADER": 0x0046,
"SPI_SETSCREENREADER": 0x0047,
"SPI_GETANIMATION": 0x0048,
"SPI_SETANIMATION": 0x0049,
"SPI_GETFONTSMOOTHING": 0x004A,
"SPI_SETFONTSMOOTHING": 0x004B,
"SPI_SETDRAGWIDTH": 0x004C,
"SPI_SETDRAGHEIGHT": 0x004D,
"SPI_SETHANDHELD": 0x004E,
"SPI_GETLOWPOWERTIMEOUT": 0x004F,
"SPI_GETPOWEROFFTIMEOUT": 0x0050,
"SPI_SETLOWPOWERTIMEOUT": 0x0051,
"SPI_SETPOWEROFFTIMEOUT": 0x0052,
"SPI_GETLOWPOWERACTIVE": 0x0053,
"SPI_GETPOWEROFFACTIVE": 0x0054,
"SPI_SETLOWPOWERACTIVE": 0x0055,
"SPI_SETPOWEROFFACTIVE": 0x0056,
"SPI_SETCURSORS": 0x0057,
"SPI_SETICONS": 0x0058,
"SPI_GETDEFAULTINPUTLANG": 0x0059,
"SPI_SETDEFAULTINPUTLANG": 0x005A,
"SPI_SETLANGTOGGLE": 0x005B,
"SPI_GETWINDOWSEXTENSION": 0x005C,
"SPI_SETMOUSETRAILS": 0x005D,
"SPI_GETMOUSETRAILS": 0x005E,
"SPI_SETSCREENSAVERRUNNING": 0x0061,
"SPI_SCREENSAVERRUNNING": 0x0061, // SPI_SETSCREENSAVERRUNNING
"SPI_GETFILTERKEYS": 0x0032,
"SPI_SETFILTERKEYS": 0x0033,
"SPI_GETTOGGLEKEYS": 0x0034,
"SPI_SETTOGGLEKEYS": 0x0035,
"SPI_GETMOUSEKEYS": 0x0036,
"SPI_SETMOUSEKEYS": 0x0037,
"SPI_GETSHOWSOUNDS": 0x0038,
"SPI_SETSHOWSOUNDS": 0x0039,
"SPI_GETSTICKYKEYS": 0x003A,
"SPI_SETSTICKYKEYS": 0x003B,
"SPI_GETACCESSTIMEOUT": 0x003C,
"SPI_SETACCESSTIMEOUT": 0x003D,
"SPI_GETSERIALKEYS": 0x003E,
"SPI_SETSERIALKEYS": 0x003F,
"SPI_GETSOUNDSENTRY": 0x0040,
"SPI_SETSOUNDSENTRY": 0x0041,
"SPI_GETSNAPTODEFBUTTON": 0x005F,
"SPI_SETSNAPTODEFBUTTON": 0x0060,
"SPI_GETMOUSEHOVERWIDTH": 0x0062,
"SPI_SETMOUSEHOVERWIDTH": 0x0063,
"SPI_GETMOUSEHOVERHEIGHT": 0x0064,
"SPI_SETMOUSEHOVERHEIGHT": 0x0065,
"SPI_GETMOUSEHOVERTIME": 0x0066,
"SPI_SETMOUSEHOVERTIME": 0x0067,
"SPI_GETWHEELSCROLLLINES": 0x0068,
"SPI_SETWHEELSCROLLLINES": 0x0069,
"SPI_GETMENUSHOWDELAY": 0x006A,
"SPI_SETMENUSHOWDELAY": 0x006B,
"SPI_GETWHEELSCROLLCHARS": 0x006C,
"SPI_SETWHEELSCROLLCHARS": 0x006D,
"SPI_GETSHOWIMEUI": 0x006E,
"SPI_SETSHOWIMEUI": 0x006F,
"SPI_GETMOUSESPEED": 0x0070,
"SPI_SETMOUSESPEED": 0x0071,
"SPI_GETSCREENSAVERRUNNING": 0x0072,
"SPI_GETDESKWALLPAPER": 0x0073,
"SPI_GETAUDIODESCRIPTION": 0x0074,
"SPI_SETAUDIODESCRIPTION": 0x0075,
"SPI_GETSCREENSAVESECURE": 0x0076,
"SPI_SETSCREENSAVESECURE": 0x0077,
"SPI_GETHUNGAPPTIMEOUT": 0x0078,
"SPI_SETHUNGAPPTIMEOUT": 0x0079,
"SPI_GETWAITTOKILLTIMEOUT": 0x007A,
"SPI_SETWAITTOKILLTIMEOUT": 0x007B,
"SPI_GETWAITTOKILLSERVICETIMEOUT": 0x007C,
"SPI_SETWAITTOKILLSERVICETIMEOUT": 0x007D,
"SPI_GETMOUSEDOCKTHRESHOLD": 0x007E,
"SPI_SETMOUSEDOCKTHRESHOLD": 0x007F,
"SPI_GETPENDOCKTHRESHOLD": 0x0080,
"SPI_SETPENDOCKTHRESHOLD": 0x0081,
"SPI_GETWINARRANGING": 0x0082,
"SPI_SETWINARRANGING": 0x0083,
"SPI_GETMOUSEDRAGOUTTHRESHOLD": 0x0084,
"SPI_SETMOUSEDRAGOUTTHRESHOLD": 0x0085,
"SPI_GETPENDRAGOUTTHRESHOLD": 0x0086,
"SPI_SETPENDRAGOUTTHRESHOLD": 0x0087,
"SPI_GETMOUSESIDEMOVETHRESHOLD": 0x0088,
"SPI_SETMOUSESIDEMOVETHRESHOLD": 0x0089,
"SPI_GETPENSIDEMOVETHRESHOLD": 0x008A,
"SPI_SETPENSIDEMOVETHRESHOLD": 0x008B,
"SPI_GETDRAGFROMMAXIMIZE": 0x008C,
"SPI_SETDRAGFROMMAXIMIZE": 0x008D,
"SPI_GETSNAPSIZING": 0x008E,
"SPI_SETSNAPSIZING": 0x008F,
"SPI_GETDOCKMOVING": 0x0090,
"SPI_SETDOCKMOVING": 0x0091,
"SPI_GETTOUCHPREDICTIONPARAMETERS": 0x009C,
"SPI_SETTOUCHPREDICTIONPARAMETERS": 0x009D,
"SPI_GETLOGICALDPIOVERRIDE": 0x009E,
"SPI_SETLOGICALDPIOVERRIDE": 0x009F,
"SPI_GETMENURECT": 0x00A2,
"SPI_SETMENURECT": 0x00A3,
"SPI_GETHIGHDPI": 0x00A5, // not defined in the SDK
"SPI_SETHIGHDPI": 0x00A6, // not defined in the SDK
"SPI_GETACTIVEWINDOWTRACKING": 0x1000,
"SPI_SETACTIVEWINDOWTRACKING": 0x1001,
"SPI_GETMENUANIMATION": 0x1002,
"SPI_SETMENUANIMATION": 0x1003,
"SPI_GETCOMBOBOXANIMATION": 0x1004,
"SPI_SETCOMBOBOXANIMATION": 0x1005,
"SPI_GETLISTBOXSMOOTHSCROLLING": 0x1006,
"SPI_SETLISTBOXSMOOTHSCROLLING": 0x1007,
"SPI_GETGRADIENTCAPTIONS": 0x1008,
"SPI_SETGRADIENTCAPTIONS": 0x1009,
"SPI_GETKEYBOARDCUES": 0x100A,
"SPI_SETKEYBOARDCUES": 0x100B,
"SPI_GETMENUUNDERLINES": 0x100A, // SPI_GETKEYBOARDCUES
"SPI_SETMENUUNDERLINES": 0x100B, // SPI_SETKEYBOARDCUES
"SPI_GETACTIVEWNDTRKZORDER": 0x100C,
"SPI_SETACTIVEWNDTRKZORDER": 0x100D,
"SPI_GETHOTTRACKING": 0x100E,
"SPI_SETHOTTRACKING": 0x100F,
"SPI_GETMENUFADE": 0x1012,
"SPI_SETMENUFADE": 0x1013,