forked from microsoft/PowerToys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
settings_window.cpp
612 lines (544 loc) · 18.3 KB
/
settings_window.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
#include "pch.h"
#include <WinSafer.h>
#include <Sddl.h>
#include <sstream>
#include <aclapi.h>
#include "powertoy_module.h"
#include <common/interop/two_way_pipe_message_ipc.h>
#include "tray_icon.h"
#include "general_settings.h"
#include "restart_elevated.h"
#include "UpdateUtils.h"
#include "centralized_kb_hook.h"
#include <common/utils/json.h>
#include <common/SettingsAPI/settings_helpers.cpp>
#include <common/version/version.h>
#include <common/version/helper.h>
#include <common/logger/logger.h>
#include <common/utils/elevation.h>
#include <common/utils/process_path.h>
#include <common/utils/timeutil.h>
#include <common/utils/winapi_error.h>
#include <common/updating/updateState.h>
#include <common/themes/windows_colors.h>
#include "settings_window.h"
#define BUFSIZE 1024
TwoWayPipeMessageIPC* current_settings_ipc = NULL;
std::atomic_bool g_isLaunchInProgress = false;
json::JsonObject get_power_toys_settings()
{
json::JsonObject result;
for (const auto& [name, powertoy] : modules())
{
try
{
result.SetNamedValue(name, powertoy.json_config());
}
catch (...)
{
Logger::error(L"get_power_toys_settings(): got malformed json for {} module", name);
}
}
return result;
}
json::JsonObject get_all_settings()
{
json::JsonObject result;
result.SetNamedValue(L"general", get_general_settings().to_json());
result.SetNamedValue(L"powertoys", get_power_toys_settings());
return result;
}
std::optional<std::wstring> dispatch_json_action_to_module(const json::JsonObject& powertoys_configs)
{
std::optional<std::wstring> result;
for (const auto& powertoy_element : powertoys_configs)
{
const std::wstring name{ powertoy_element.Key().c_str() };
// Currently, there is only one custom action in the general settings screen,
// so it has to be the "restart as (non-)elevated" button.
if (name == L"general")
{
try
{
const auto value = powertoy_element.Value().GetObjectW();
const auto action = value.GetNamedString(L"action_name");
if (action == L"restart_elevation")
{
if (is_process_elevated())
{
schedule_restart_as_non_elevated();
PostQuitMessage(0);
}
else
{
schedule_restart_as_elevated(true);
PostQuitMessage(0);
}
}
else if (action == L"check_for_updates")
{
CheckForUpdatesCallback();
}
else if (action == L"request_update_state_date")
{
json::JsonObject json;
auto update_state = UpdateState::read();
if (update_state.githubUpdateLastCheckedDate)
{
const time_t date = *update_state.githubUpdateLastCheckedDate;
json.SetNamedValue(L"updateStateDate", json::value(std::to_wstring(date)));
}
result.emplace(json.Stringify());
}
}
catch (...)
{
}
}
else if (modules().find(name) != modules().end())
{
const auto element = powertoy_element.Value().Stringify();
modules().at(name)->call_custom_action(element.c_str());
}
}
return result;
}
void send_json_config_to_module(const std::wstring& module_key, const std::wstring& settings)
{
auto moduleIt = modules().find(module_key);
if (moduleIt != modules().end())
{
moduleIt->second->set_config(settings.c_str());
moduleIt->second.update_hotkeys();
moduleIt->second.UpdateHotkeyEx();
}
}
void dispatch_json_config_to_modules(const json::JsonObject& powertoys_configs)
{
for (const auto& powertoy_element : powertoys_configs)
{
const auto element = powertoy_element.Value().Stringify();
send_json_config_to_module(powertoy_element.Key().c_str(), element.c_str());
}
};
void dispatch_received_json(const std::wstring& json_to_parse)
{
json::JsonObject j;
const bool ok = json::JsonObject::TryParse(json_to_parse, j);
if (!ok)
{
Logger::error(L"dispatch_received_json: got malformed json: {}", json_to_parse);
return;
}
for (const auto& base_element : j)
{
if (!current_settings_ipc)
{
continue;
}
const auto name = base_element.Key();
const auto value = base_element.Value();
if (name == L"general")
{
apply_general_settings(value.GetObjectW());
const std::wstring settings_string{ get_all_settings().Stringify().c_str() };
current_settings_ipc->send(settings_string);
}
else if (name == L"powertoys")
{
dispatch_json_config_to_modules(value.GetObjectW());
const std::wstring settings_string{ get_all_settings().Stringify().c_str() };
current_settings_ipc->send(settings_string);
}
else if (name == L"refresh")
{
const std::wstring settings_string{ get_all_settings().Stringify().c_str() };
current_settings_ipc->send(settings_string);
}
else if (name == L"action")
{
auto result = dispatch_json_action_to_module(value.GetObjectW());
if (result.has_value())
{
current_settings_ipc->send(result.value());
}
}
}
return;
}
void dispatch_received_json_callback(PVOID data)
{
std::wstring* msg = (std::wstring*)data;
dispatch_received_json(*msg);
delete msg;
}
void receive_json_send_to_main_thread(const std::wstring& msg)
{
std::wstring* copy = new std::wstring(msg);
dispatch_run_on_main_ui_thread(dispatch_received_json_callback, copy);
}
// Try to run the Settings process with non-elevated privileges.
BOOL run_settings_non_elevated(LPCWSTR executable_path, LPWSTR executable_args, PROCESS_INFORMATION* process_info)
{
HWND hwnd = GetShellWindow();
if (!hwnd)
{
return false;
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
winrt::handle process{ OpenProcess(PROCESS_CREATE_PROCESS, FALSE, pid) };
if (!process)
{
return false;
}
SIZE_T size = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &size);
auto pproc_buffer = std::unique_ptr<char[]>{ new (std::nothrow) char[size] };
auto pptal = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(pproc_buffer.get());
if (!pptal)
{
return false;
}
if (!InitializeProcThreadAttributeList(pptal, 1, 0, &size))
{
return false;
}
if (!UpdateProcThreadAttribute(pptal,
0,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
&process,
sizeof(process),
nullptr,
nullptr))
{
return false;
}
STARTUPINFOEX siex = { 0 };
siex.lpAttributeList = pptal;
siex.StartupInfo.cb = sizeof(siex);
BOOL process_created = CreateProcessW(executable_path,
executable_args,
nullptr,
nullptr,
FALSE,
EXTENDED_STARTUPINFO_PRESENT,
nullptr,
nullptr,
&siex.StartupInfo,
process_info);
g_isLaunchInProgress = false;
return process_created;
}
DWORD g_settings_process_id = 0;
void run_settings_window(bool show_oobe_window, std::optional<std::wstring> settings_window)
{
g_isLaunchInProgress = true;
PROCESS_INFORMATION process_info = { 0 };
HANDLE hToken = nullptr;
// Arguments for calling the settings executable:
// "C:\powertoys_path\PowerToysSettings.exe" powertoys_pipe settings_pipe powertoys_pid settings_theme
// powertoys_pipe: PowerToys pipe server.
// settings_pipe : Settings pipe server.
// powertoys_pid : PowerToys process pid.
// settings_theme: pass "dark" to start the settings window in dark mode
// Arg 1: executable path.
std::wstring executable_path = get_module_folderpath();
executable_path.append(L"\\Settings\\PowerToys.Settings.exe");
// Args 2,3: pipe server. Generate unique names for the pipes, if getting a UUID is possible.
std::wstring powertoys_pipe_name(L"\\\\.\\pipe\\powertoys_runner_");
std::wstring settings_pipe_name(L"\\\\.\\pipe\\powertoys_settings_");
UUID temp_uuid;
wchar_t* uuid_chars = nullptr;
if (UuidCreate(&temp_uuid) == RPC_S_UUID_NO_ADDRESS)
{
auto val = get_last_error_message(GetLastError());
Logger::warn(L"UuidCreate can not create guid. {}", val.has_value() ? val.value() : L"");
}
else if (UuidToString(&temp_uuid, (RPC_WSTR*)&uuid_chars) != RPC_S_OK)
{
auto val = get_last_error_message(GetLastError());
Logger::warn(L"UuidToString can not convert to string. {}", val.has_value() ? val.value() : L"");
}
if (uuid_chars != nullptr)
{
powertoys_pipe_name += std::wstring(uuid_chars);
settings_pipe_name += std::wstring(uuid_chars);
RpcStringFree((RPC_WSTR*)&uuid_chars);
uuid_chars = nullptr;
}
// Arg 4: process pid.
DWORD powertoys_pid = GetCurrentProcessId();
// Arg 5: settings theme.
const std::wstring settings_theme_setting{ get_general_settings().theme };
std::wstring settings_theme = L"system";
if (settings_theme_setting == L"dark" || (settings_theme_setting == L"system" && WindowsColors::is_dark_mode()))
{
settings_theme = L"dark";
}
GeneralSettings save_settings = get_general_settings();
// Arg 6: elevated status
bool isElevated{ get_general_settings().isElevated };
std::wstring settings_elevatedStatus = isElevated ? L"true" : L"false";
// Arg 7: is user an admin
bool isAdmin{ get_general_settings().isAdmin };
std::wstring settings_isUserAnAdmin = isAdmin ? L"true" : L"false";
// Arg 8: should oobe window be shown
std::wstring settings_showOobe = show_oobe_window ? L"true" : L"false";
// create general settings file to initialize the settings file with installation configurations like :
// 1. Run on start up.
PTSettingsHelper::save_general_settings(save_settings.to_json());
std::wstring executable_args = L"\"";
executable_args.append(executable_path);
executable_args.append(L"\" ");
executable_args.append(powertoys_pipe_name);
executable_args.append(L" ");
executable_args.append(settings_pipe_name);
executable_args.append(L" ");
executable_args.append(std::to_wstring(powertoys_pid));
executable_args.append(L" ");
executable_args.append(settings_theme);
executable_args.append(L" ");
executable_args.append(settings_elevatedStatus);
executable_args.append(L" ");
executable_args.append(settings_isUserAnAdmin);
executable_args.append(L" ");
executable_args.append(settings_showOobe);
if (settings_window.has_value())
{
executable_args.append(L" ");
executable_args.append(settings_window.value());
}
BOOL process_created = false;
if (is_process_elevated())
{
// TODO: Revisit this after switching to .NET 5
// Due to a bug in .NET, running the Settings process as non-elevated
// from an elevated process sometimes results in a crash.
// process_created = run_settings_non_elevated(executable_path.c_str(), executable_args.data(), &process_info);
}
if (FALSE == process_created)
{
// The runner is not elevated or we failed to create the process using the
// attribute list from Windows Explorer (this happens when PowerToys is executed
// as Administrator from a non-Administrator user or an error occur trying).
// In the second case the Settings process will run elevated.
STARTUPINFO startup_info = { sizeof(startup_info) };
if (!CreateProcessW(executable_path.c_str(),
executable_args.data(),
nullptr,
nullptr,
FALSE,
0,
nullptr,
nullptr,
&startup_info,
&process_info))
{
goto LExit;
}
else
{
g_isLaunchInProgress = false;
}
}
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
goto LExit;
}
current_settings_ipc = new TwoWayPipeMessageIPC(powertoys_pipe_name, settings_pipe_name, receive_json_send_to_main_thread);
current_settings_ipc->start(hToken);
g_settings_process_id = process_info.dwProcessId;
if (process_info.hProcess)
{
WaitForSingleObject(process_info.hProcess, INFINITE);
if (WaitForSingleObject(process_info.hProcess, INFINITE) != WAIT_OBJECT_0)
{
show_last_error_message(L"Couldn't wait on the Settings Window to close.", GetLastError(), L"PowerToys - runner");
}
}
else
{
auto val = get_last_error_message(GetLastError());
Logger::error(L"Process handle is empty. {}", val.has_value() ? val.value() : L"");
}
LExit:
if (process_info.hProcess)
{
CloseHandle(process_info.hProcess);
}
if (process_info.hThread)
{
CloseHandle(process_info.hThread);
}
if (current_settings_ipc)
{
current_settings_ipc->end();
delete current_settings_ipc;
current_settings_ipc = nullptr;
}
if (hToken)
{
CloseHandle(hToken);
}
g_settings_process_id = 0;
}
#define MAX_TITLE_LENGTH 100
void bring_settings_to_front()
{
auto callback = [](HWND hwnd, LPARAM data) -> BOOL {
DWORD processId;
if (GetWindowThreadProcessId(hwnd, &processId) && processId == g_settings_process_id)
{
std::wstring windowTitle = L"PowerToys Settings";
WCHAR title[MAX_TITLE_LENGTH];
int len = GetWindowTextW(hwnd, title, MAX_TITLE_LENGTH);
if (len <= 0)
{
return TRUE;
}
if (wcsncmp(title, windowTitle.c_str(), len) == 0)
{
auto lStyles = GetWindowLong(hwnd, GWL_STYLE);
if (lStyles & WS_MAXIMIZE)
{
ShowWindow(hwnd, SW_MAXIMIZE);
}
else
{
ShowWindow(hwnd, SW_RESTORE);
}
SetForegroundWindow(hwnd);
return FALSE;
}
}
return TRUE;
};
EnumWindows(callback, 0);
}
void open_settings_window(std::optional<std::wstring> settings_window)
{
if (g_settings_process_id != 0)
{
bring_settings_to_front();
}
else
{
if (!g_isLaunchInProgress)
{
std::thread([settings_window]() {
run_settings_window(false, settings_window);
}).detach();
}
}
}
void close_settings_window()
{
if (g_settings_process_id != 0)
{
HANDLE proc = OpenProcess(PROCESS_TERMINATE, false, g_settings_process_id);
if (proc != INVALID_HANDLE_VALUE)
{
TerminateProcess(proc, 0);
}
}
}
void open_oobe_window()
{
std::thread([]() {
run_settings_window(true, std::nullopt);
}).detach();
}
std::string ESettingsWindowNames_to_string(ESettingsWindowNames value)
{
switch (value)
{
case ESettingsWindowNames::Overview:
return "Overview";
case ESettingsWindowNames::Awake:
return "Awake";
case ESettingsWindowNames::ColorPicker:
return "ColorPicker";
case ESettingsWindowNames::FancyZones:
return "FancyZones";
case ESettingsWindowNames::Run:
return "Run";
case ESettingsWindowNames::ImageResizer:
return "ImageResizer";
case ESettingsWindowNames::KBM:
return "KBM";
case ESettingsWindowNames::MouseUtils:
return "MouseUtils";
case ESettingsWindowNames::PowerRename:
return "PowerRename";
case ESettingsWindowNames::FileExplorer:
return "FileExplorer";
case ESettingsWindowNames::ShortcutGuide:
return "ShortcutGuide";
case ESettingsWindowNames::VideoConference:
return "VideoConference";
default:
{
Logger::error(L"Can't convert ESettingsWindowNames value={} to string", static_cast<int>(value));
assert(false);
}
}
return "";
}
ESettingsWindowNames ESettingsWindowNames_from_string(std::string value)
{
if (value == "Overview")
{
return ESettingsWindowNames::Overview;
}
else if (value == "Awake")
{
return ESettingsWindowNames::Awake;
}
else if (value == "ColorPicker")
{
return ESettingsWindowNames::ColorPicker;
}
else if (value == "FancyZones")
{
return ESettingsWindowNames::FancyZones;
}
else if (value == "Run")
{
return ESettingsWindowNames::Run;
}
else if (value == "ImageResizer")
{
return ESettingsWindowNames::ImageResizer;
}
else if (value == "KBM")
{
return ESettingsWindowNames::KBM;
}
else if (value == "MouseUtils")
{
return ESettingsWindowNames::MouseUtils;
}
else if (value == "PowerRename")
{
return ESettingsWindowNames::PowerRename;
}
else if (value == "FileExplorer")
{
return ESettingsWindowNames::FileExplorer;
}
else if (value == "ShortcutGuide")
{
return ESettingsWindowNames::ShortcutGuide;
}
else if (value == "VideoConference")
{
return ESettingsWindowNames::VideoConference;
}
else
{
Logger::error(L"Can't convert string value={} to ESettingsWindowNames", winrt::to_hstring(value));
assert(false);
}
return ESettingsWindowNames::Overview;
}