forked from microsoft/PowerToys
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewPlusViewModel.cs
More file actions
436 lines (365 loc) · 16.1 KB
/
NewPlusViewModel.cs
File metadata and controls
436 lines (365 loc) · 16.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
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Principal;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using global::PowerToys.GPOWrapper;
using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.Library.Utilities;
using Microsoft.PowerToys.Settings.UI.Library.ViewModels.Commands;
using Microsoft.PowerToys.Settings.UI.SerializationContext;
using Microsoft.Win32;
using static Microsoft.PowerToys.Settings.UI.Helpers.ShellGetFolder;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public partial class NewPlusViewModel : Observable
{
private GeneralSettings GeneralSettingsConfig { get; set; }
private readonly ISettingsUtils _settingsUtils;
private NewPlusSettings Settings { get; set; }
private const string ModuleName = NewPlusSettings.ModuleName;
private const string BuiltInNewRegistryPath = @"HKEY_CLASSES_ROOT\Directory\Background\shellex\ContextMenuHandlers\New";
private const string NewDisabledValuePrefix = "0_";
private const string BuiltNewCOMGuid = "{D969A300-E7FF-11d0-A93B-00A0C90F2719}";
public NewPlusViewModel(ISettingsUtils settingsUtils, ISettingsRepository<GeneralSettings> settingsRepository, Func<string, int> ipcMSGCallBackFunc)
{
_settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
// To obtain the general settings configurations of PowerToys Settings.
ArgumentNullException.ThrowIfNull(settingsRepository);
GeneralSettingsConfig = settingsRepository.SettingsConfig;
Settings = LoadSettings(settingsUtils);
// Initialize properties
_hideFileExtension = Settings.Properties.HideFileExtension.Value;
_hideStartingDigits = Settings.Properties.HideStartingDigits.Value;
_templateLocation = Settings.Properties.TemplateLocation.Value;
_replaceVariables = Settings.Properties.ReplaceVariables.Value;
InitializeEnabledValue();
InitializeGpoValues();
_disableBuiltInNew = !IsBuiltInNewEnabled();
// set the callback functions value to handle outgoing IPC message.
SendConfigMSG = ipcMSGCallBackFunc;
}
private void InitializeEnabledValue()
{
_enabledGpoRuleConfiguration = GPOWrapper.GetConfiguredNewPlusEnabledValue();
if (_enabledGpoRuleConfiguration == GpoRuleConfigured.Disabled || _enabledGpoRuleConfiguration == GpoRuleConfigured.Enabled)
{
// Get the enabled state from GPO.
_enabledStateIsGPOConfigured = true;
_isNewPlusEnabled = _enabledGpoRuleConfiguration == GpoRuleConfigured.Enabled;
}
else
{
_isNewPlusEnabled = GeneralSettingsConfig.Enabled.NewPlus;
}
}
private void InitializeGpoValues()
{
// Policy for hide file extension setting
_hideFileExtensionGpoRuleConfiguration = GPOWrapper.GetConfiguredNewPlusHideTemplateFilenameExtensionValue();
_hideFileExtensionIsGPOConfigured = _hideFileExtensionGpoRuleConfiguration == GpoRuleConfigured.Disabled || _hideFileExtensionGpoRuleConfiguration == GpoRuleConfigured.Enabled;
// Same for Replace Variables
_replaceVariablesIsGPOConfigured = GPOWrapper.GetConfiguredNewPlusReplaceVariablesValue() == GpoRuleConfigured.Enabled
|| GPOWrapper.GetConfiguredNewPlusReplaceVariablesValue() == GpoRuleConfigured.Disabled;
}
public bool IsEnabled
{
get => _isNewPlusEnabled;
set
{
if (_isNewPlusEnabled != value)
{
_isNewPlusEnabled = value;
GeneralSettingsConfig.Enabled.NewPlus = value;
OnPropertyChanged(nameof(IsEnabled));
OnPropertyChanged(nameof(IsHideFileExtSettingsCardEnabled));
OnPropertyChanged(nameof(IsHideFileExtSettingGPOConfigured));
OnPropertyChanged(nameof(IsReplaceVariablesSettingGPOConfigured));
OnPropertyChanged(nameof(IsReplaceVariablesSettingsCardEnabled));
OnPropertyChanged(nameof(IsDisableBuiltInNewSettingsCardEnabled));
OnPropertyChanged(nameof(IsEnabledAndNotElevated));
OutGoingGeneralSettings outgoingMessage = new OutGoingGeneralSettings(GeneralSettingsConfig);
SendConfigMSG(outgoingMessage.ToString());
NotifySettingsChanged();
if (_isNewPlusEnabled == true)
{
CopyTemplateExamples(_templateLocation);
}
}
}
}
private bool IsElevated()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public bool IsWin10OrLower
{
get => !OSVersionHelper.IsWindows11();
}
public string TemplateLocation
{
get => _templateLocation;
set
{
if (_templateLocation != value)
{
_templateLocation = value;
Settings.Properties.TemplateLocation.Value = value;
OnPropertyChanged(nameof(TemplateLocation));
NotifySettingsChanged();
}
}
}
public bool HideFileExtension
{
get
{
if (_hideFileExtensionIsGPOConfigured)
{
return _hideFileExtensionGpoRuleConfiguration == GpoRuleConfigured.Enabled;
}
return _hideFileExtension;
}
set
{
if (_hideFileExtension != value && !_hideFileExtensionIsGPOConfigured)
{
_hideFileExtension = value;
Settings.Properties.HideFileExtension.Value = value;
OnPropertyChanged(nameof(HideFileExtension));
NotifySettingsChanged();
}
}
}
public bool IsHideFileExtSettingsCardEnabled => _isNewPlusEnabled && !_hideFileExtensionIsGPOConfigured;
public bool IsHideFileExtSettingGPOConfigured => _isNewPlusEnabled && _hideFileExtensionIsGPOConfigured;
public bool IsReplaceVariablesSettingsCardEnabled => _isNewPlusEnabled && !_replaceVariablesIsGPOConfigured;
public bool IsReplaceVariablesSettingGPOConfigured => _isNewPlusEnabled && _replaceVariablesIsGPOConfigured;
public bool IsDisableBuiltInNewSettingsCardEnabled => _isNewPlusEnabled && IsElevated();
public bool HideStartingDigits
{
get => _hideStartingDigits;
set
{
if (_hideStartingDigits != value)
{
_hideStartingDigits = value;
Settings.Properties.HideStartingDigits.Value = value;
OnPropertyChanged(nameof(HideStartingDigits));
NotifySettingsChanged();
}
}
}
public bool ReplaceVariables
{
get
{
// Check to see if setting has been enabled or disabled via GPO, and if so, use that value
if (IsReplaceVariablesSettingGPOConfigured)
{
return GPOWrapper.GetConfiguredNewPlusReplaceVariablesValue() == GpoRuleConfigured.Enabled;
}
return _replaceVariables;
}
set
{
if (_replaceVariables != value)
{
_replaceVariables = value;
Settings.Properties.ReplaceVariables.Value = value;
OnPropertyChanged(nameof(ReplaceVariables));
NotifySettingsChanged();
}
}
}
public bool HideBuiltInNew
{
get
{
return _disableBuiltInNew;
}
set
{
if (_disableBuiltInNew != value)
{
if (_disableBuiltInNew)
{
EnableBuiltInNew();
}
else
{
DisableBuiltInNew();
}
_disableBuiltInNew = value;
OnPropertyChanged(nameof(DisableBuiltInNew));
NotifySettingsChanged();
}
}
}
public bool IsEnabledGpoConfigured
{
get => _enabledStateIsGPOConfigured;
}
public bool IsEnabledAndNotElevated
{
get => _isNewPlusEnabled && !IsElevated();
}
public ButtonClickCommand OpenCurrentNewTemplateFolder => new ButtonClickCommand(OpenNewTemplateFolder);
public ButtonClickCommand PickAnotherNewTemplateFolder => new ButtonClickCommand(PickNewTemplateFolder);
private void NotifySettingsChanged()
{
// Using InvariantCulture as this is an IPC message
SendConfigMSG(
string.Format(
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
ModuleName,
JsonSerializer.Serialize(Settings, SourceGenerationContextContext.Default.NewPlusSettings)));
}
private Func<string, int> SendConfigMSG { get; }
public static NewPlusSettings LoadSettings(ISettingsUtils settingsUtils)
{
NewPlusSettings settings = null;
try
{
settings = settingsUtils.GetSettingsOrDefault<NewPlusSettings>(NewPlusSettings.ModuleName);
if (string.IsNullOrEmpty(settings.Properties.TemplateLocation.Value))
{
// This can happen when running the DEBUG Settings application without first letting the runner create the default settings file.
settings.Properties.TemplateLocation.Value = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "PowerToys", "NewPlus", "Templates");
}
}
catch (Exception e)
{
Logger.LogError($"Exception encountered while reading {NewPlusSettings.ModuleName} settings.", e);
}
return settings;
}
public static void CopyTemplateExamples(string templateLocation)
{
if (!Directory.Exists(templateLocation))
{
Directory.CreateDirectory(templateLocation);
}
if (Directory.GetFiles(templateLocation).Length == 0 && Directory.GetDirectories(templateLocation).Length == 0)
{
// No files in templateLocation directory
// Copy over examples files from <Program Files>\PowerToys\WinUI3Apps\Assets\NewPlus\Templates
var example_templates = Path.Combine(Helper.GetPowerToysInstallationWinUI3AppsAssetsFolder(), "NewPlus", "Templates");
Helper.CopyDirectory(example_templates, templateLocation, true);
}
}
private bool _isNewPlusEnabled;
private string _templateLocation;
private bool _hideFileExtension;
private bool _hideStartingDigits;
private bool _replaceVariables;
private bool _disableBuiltInNew;
private GpoRuleConfigured _enabledGpoRuleConfiguration;
private bool _enabledStateIsGPOConfigured;
private GpoRuleConfigured _hideFileExtensionGpoRuleConfiguration;
private bool _hideFileExtensionIsGPOConfigured;
private bool _replaceVariablesIsGPOConfigured;
public void RefreshEnabledState()
{
InitializeEnabledValue();
OnPropertyChanged(nameof(IsEnabled));
}
private void OpenNewTemplateFolder()
{
try
{
CopyTemplateExamples(_templateLocation);
var process = new ProcessStartInfo()
{
FileName = _templateLocation,
UseShellExecute = true,
};
Process.Start(process);
}
catch (Exception ex)
{
Logger.LogError("Failed to show NewPlus template folder.", ex);
}
}
private async void PickNewTemplateFolder()
{
var newPath = await PickFolderDialog();
if (!string.IsNullOrEmpty(newPath))
{
TemplateLocation = newPath;
}
}
private async Task<string> PickFolderDialog()
{
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.GetSettingsWindow());
return await Task.FromResult(GetFolderDialogWithFlags(hwnd, FolderDialogFlags._BIF_NEWDIALOGSTYLE));
}
private bool IsBuiltInNewEnabled()
{
try
{
string builtInNewHandlerValue = Registry.GetValue(BuiltInNewRegistryPath, string.Empty, null) as string;
return IsValidRegistryCOMFormatGuid(builtInNewHandlerValue);
}
catch (Exception ex)
{
Logger.LogError("Failed to determine built-in New enablement status.", ex);
}
return false;
}
private static bool IsValidRegistryCOMFormatGuid(string input)
{
return Guid.TryParseExact(input, "B", out _);
}
private void DisableBuiltInNew()
{
try
{
string builtInNewHandlerValue = Registry.GetValue(BuiltInNewRegistryPath, string.Empty, null) as string;
if (builtInNewHandlerValue.StartsWith(NewDisabledValuePrefix, StringComparison.OrdinalIgnoreCase))
{
// Already disabled
return;
}
Debug.Assert(builtInNewHandlerValue == BuiltNewCOMGuid, "Unexpected GUID encountered while disabling built-in New");
string newDisabledValue = NewDisabledValuePrefix + builtInNewHandlerValue;
Registry.SetValue(BuiltInNewRegistryPath, string.Empty, newDisabledValue);
}
catch (Exception ex)
{
Logger.LogError("Failed to disable built-in New in the registry.", ex);
MessageBox.Show(ex.Message);
}
}
private void EnableBuiltInNew()
{
try
{
string builtInNewHandlerValue = Registry.GetValue(BuiltInNewRegistryPath, string.Empty, null) as string;
if (builtInNewHandlerValue.StartsWith(NewDisabledValuePrefix, StringComparison.OrdinalIgnoreCase))
{
string newEnabledValue = builtInNewHandlerValue.Substring(NewDisabledValuePrefix.Length);
Debug.Assert(newEnabledValue == BuiltNewCOMGuid, "Unexpected GUID encountered while reenabling built-in New");
Registry.SetValue(BuiltInNewRegistryPath, string.Empty, newEnabledValue);
}
}
catch (Exception ex)
{
Logger.LogError("Failed to enable built-in New in the registry.", ex);
MessageBox.Show(ex.Message);
}
}
}
}