-
Notifications
You must be signed in to change notification settings - Fork 13
/
Installer.cpp
491 lines (380 loc) · 14.8 KB
/
Installer.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
#include "pch.h"
#include "Installer.h"
#include "ClassicEditWithNppExplorerCommandHandler.h"
#include "PathHelper.h"
#include "AclHelper.h"
#include "RegistryKey.h"
#define GUID_STRING_SIZE 40
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::Management::Deployment;
using namespace NppShell::Helpers;
using namespace NppShell::Installer;
using namespace NppShell::Registry;
extern HMODULE g_module;
const wstring SparsePackageName = L"NotepadPlusPlus";
constexpr int FirstWindows11BuildNumber = 22000;
#ifdef WIN64
const wstring ShellKey = L"Software\\Classes\\*\\shell\\ANotepad++64";
const wstring ShellExtensionKey = L"Software\\Classes\\*\\shellex\\ContextMenuHandlers\\ANotepad++64";
#else
const wstring ShellKey = L"Software\\Classes\\*\\shell\\ANotepad++";
const wstring ShellExtensionKey = L"Software\\Classes\\*\\shellex\\ContextMenuHandlers\\ANotepad++";
#endif
bool IsWindows11Installation()
{
RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
wstring buildNumberString = registryKey.GetStringValue(L"CurrentBuildNumber");
const int buildNumber = stoi(buildNumberString);
return buildNumber >= FirstWindows11BuildNumber;
}
wstring GetCLSIDString()
{
const auto uuid = __uuidof(NppShell::CommandHandlers::ClassicEditWithNppExplorerCommandHandler);
LPOLESTR guidString = 0;
const HRESULT result = StringFromCLSID(uuid, &guidString);
if (FAILED(result))
{
if (guidString)
{
CoTaskMemFree(guidString);
}
throw "Failed to parse GUID from command handler";
}
wstring guid(guidString);
if (guidString)
{
CoTaskMemFree(guidString);
}
return guid;
}
void inline CleanupRegistry(const wstring& guid)
{
// First we remove the shell key if it exists.
if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, ShellKey))
{
RegistryKey registryKey(HKEY_LOCAL_MACHINE, ShellKey, KEY_READ | KEY_WRITE);
registryKey.DeleteKey();
}
// Then we remove the shell extension key if it exists.
if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, ShellExtensionKey))
{
RegistryKey registryKey(HKEY_LOCAL_MACHINE, ShellExtensionKey, KEY_READ | KEY_WRITE);
registryKey.DeleteKey();
}
// Then we remove the Notepad++_file key if it exists.
if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"Notepad++_file\\shellex"))
{
RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"Notepad++_file\\shellex", KEY_READ | KEY_WRITE);
registryKey.DeleteKey();
}
// Finally we remove the CLSID key if it exists.
if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid))
{
RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid, KEY_READ | KEY_WRITE);
registryKey.DeleteKey();
}
}
void inline CleanupHack()
{
// First we test if the key even exists.
if (!RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Classes\\*\\shell\\pintohome"))
{
return;
}
// If it does, we open it and check if the value exists.
wstring valueName = L"MUIVerb";
RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Classes\\*\\shell\\pintohome", KEY_READ | KEY_WRITE);
if (!registryKey.ValueExists(valueName))
{
return;
}
// Then we get the value and see if it contains the text "Notepad++"
wstring currentValue = registryKey.GetStringValue(valueName);
bool found = currentValue.find(L"Notepad++") != wstring::npos;
// If we found the text, we delete the entire key.
if (found)
{
registryKey.DeleteKey();
}
}
HRESULT MoveFileToTempAndScheduleDeletion(const wstring& filePath, bool moveToTempDirectory)
{
wstring tempPath(MAX_PATH, L'\0');
wstring tempFileName(MAX_PATH, L'\0');
BOOL moveResult;
if (moveToTempDirectory)
{
// First we get the path to the temporary directory.
GetTempPath(MAX_PATH, &tempPath[0]);
// Then we get a temporary filename in the temporary directory.
GetTempFileName(tempPath.c_str(), L"tempFileName", 0, &tempFileName[0]);
// Move the file into the temp directory - it can be moved even when it is loaded into memory and locked.
moveResult = MoveFileEx(filePath.c_str(), tempFileName.c_str(), MOVEFILE_REPLACE_EXISTING);
if (!moveResult)
{
return S_FALSE;
}
// Schedule it to be deleted from the temp directory on the next reboot.
moveResult = MoveFileExW(tempFileName.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
}
else
{
// Schedule it to be deleted on the next reboot, without moving it.
moveResult = MoveFileExW(filePath.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
}
if (!moveResult)
{
return S_FALSE;
}
return S_OK;
}
void ResetAclPermissionsOnContextMenuFolder()
{
// First we get the path where Notepad++ context menu is installed.
const wstring contextMenuPath = GetContextMenuPath();
// Create a new AclHelper
AclHelper aclHelper;
// Reset the ACL of the folder where Notepad++ context menu is installed.
aclHelper.ResetAcl(contextMenuPath);
}
Package GetSparsePackage(bool allUsers)
{
PackageManager packageManager;
IIterable<Package> packages;
try
{
if (allUsers)
{
packages = packageManager.FindPackages();
}
else
{
packages = packageManager.FindPackagesForUser(L"");
}
}
catch (winrt::hresult_error)
{
return NULL;
}
for (const Package& package : packages)
{
if (package.Id().Name() != SparsePackageName)
{
continue;
}
return package;
}
return NULL;
}
HRESULT NppShell::Installer::RegisterSparsePackageAllUsers()
{
if (::GetSystemMetrics(SM_CLEANBOOT) > 0)
{
return S_FALSE; // Otherwise we will get an unhandled exception later due to HRESULT 0x8007043c (ERROR_NOT_SAFEBOOT_SERVICE).
}
PackageManager packageManager;
StagePackageOptions options;
const wstring externalLocation = GetContextMenuPath();
const wstring sparsePkgPath = externalLocation + L"\\NppShell.msix";
Uri externalUri(externalLocation);
Uri packageUri(sparsePkgPath);
options.ExternalLocationUri(externalUri);
auto deploymentOperation = packageManager.StagePackageByUriAsync(packageUri, options);
auto deployResult = deploymentOperation.get();
if (!SUCCEEDED(deployResult.ExtendedErrorCode()))
{
return deployResult.ExtendedErrorCode();
}
Package package = GetSparsePackage(true);
if (package == NULL)
{
return S_FALSE;
}
winrt::hstring familyName = package.Id().FamilyName();
deploymentOperation = packageManager.ProvisionPackageForAllUsersAsync(familyName);
deployResult = deploymentOperation.get();
if (!SUCCEEDED(deployResult.ExtendedErrorCode()))
{
return deployResult.ExtendedErrorCode();
}
return S_OK;
}
HRESULT NppShell::Installer::RegisterSparsePackageCurrentUser()
{
if (::GetSystemMetrics(SM_CLEANBOOT) > 0)
{
return S_FALSE; // Otherwise we will get an unhandled exception later due to HRESULT 0x8007043c (ERROR_NOT_SAFEBOOT_SERVICE).
}
PackageManager packageManager;
AddPackageOptions options;
const wstring externalLocation = GetContextMenuPath();
const wstring sparsePkgPath = externalLocation + L"\\NppShell.msix";
Uri externalUri(externalLocation);
Uri packageUri(sparsePkgPath);
options.ExternalLocationUri(externalUri);
auto deploymentOperation = packageManager.AddPackageByUriAsync(packageUri, options);
auto deployResult = deploymentOperation.get();
if (!SUCCEEDED(deployResult.ExtendedErrorCode()))
{
return deployResult.ExtendedErrorCode();
}
return S_OK;
}
HRESULT NppShell::Installer::UnregisterSparsePackage()
{
if (::GetSystemMetrics(SM_CLEANBOOT) > 0)
{
return S_FALSE; // Only to speed up things a bit here. (code in the following GetSparsePackage() is safe against the ERROR_NOT_SAFEBOOT_SERVICE)
}
PackageManager packageManager;
IIterable<Package> packages;
Package package = GetSparsePackage(true);
if (package == NULL)
{
return S_FALSE;
}
winrt::hstring fullName = package.Id().FullName();
auto deploymentOperation = packageManager.RemovePackageAsync(fullName, RemovalOptions::RemoveForAllUsers);
auto deployResult = deploymentOperation.get();
if (!SUCCEEDED(deployResult.ExtendedErrorCode()))
{
return deployResult.ExtendedErrorCode();
}
// After unregistering the sparse package, we reset the folder permissions of the folder where we are installed.
ResetAclPermissionsOnContextMenuFolder();
return S_OK;
}
HRESULT NppShell::Installer::RegisterOldContextMenu()
{
const wstring contextMenuFullName = GetContextMenuFullName();
const wstring guid = GetCLSIDString();
// First we set the shell extension values.
RegistryKey regKeyExtension(HKEY_LOCAL_MACHINE, ShellKey, KEY_READ | KEY_WRITE, true);
regKeyExtension.SetStringValue(L"", L"Notepad++ Context menu");
regKeyExtension.SetStringValue(L"ExplorerCommandHandler", guid);
regKeyExtension.SetStringValue(L"NeverDefault", L"");
// Then we create the CLSID for the handler with it's values.
RegistryKey regKeyClsid(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid, KEY_READ | KEY_WRITE, true);
regKeyClsid.SetStringValue(L"", L"notepad++");
RegistryKey regKeyInProc = regKeyClsid.GetSubKey(L"InProcServer32", true);
regKeyInProc.SetStringValue(L"", contextMenuFullName);
regKeyInProc.SetStringValue(L"ThreadingModel", L"Apartment");
return S_OK;
}
HRESULT NppShell::Installer::UnregisterOldContextMenu()
{
const wstring guid = GetCLSIDString();
// Clean up registry entries.
CleanupRegistry(guid);
return S_OK;
}
void ReRegisterSparsePackage()
{
if (::GetSystemMetrics(SM_CLEANBOOT) > 0)
{
return; // Sparse package reg/unreg cannot be done in the Windows OS SafeMode.
}
winrt::init_apartment();
// Since we are on Windows 11, we unregister the sparse package as well.
UnregisterSparsePackage();
// And then we register it again.
RegisterSparsePackageAllUsers();
RegisterSparsePackageCurrentUser();
}
HRESULT NppShell::Installer::Install()
{
const bool isWindows11 = IsWindows11Installation();
HRESULT result;
// Clean up the 8.5 Windows 11 hack if present.
CleanupHack();
if (isWindows11)
{
// We need to unregister the old menu on Windows 11 to prevent double entries in the old menu.
UnregisterOldContextMenu();
// To register the sparse package, we need to do it on another thread due to WinRT requirements.
thread reRegisterThread(ReRegisterSparsePackage);
reRegisterThread.join();
}
result = RegisterOldContextMenu();
// Ensure we schedule old files for removal on next reboot.
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_01.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_02.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_03.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_04.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_05.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_06.dll", false);
// This include the old NppModernShell and NppShell files from the main program directory.
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell.msix", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppModernShell.dll", false);
MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppModernShell.msix", false);
// Finally we notify the shell that we have made changes, so it refreshes the context menus.
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
return result;
}
HRESULT NppShell::Installer::Uninstall()
{
const bool isWindows11 = IsWindows11Installation();
HRESULT result;
// We remove the old context menu in all cases, since both Windows 11 and older versions can have it setup if upgrading.
result = UnregisterOldContextMenu();
if (result != S_OK)
{
return result;
}
if (isWindows11)
{
// Since we are on Windows 11, we unregister the sparse package as well.
result = UnregisterSparsePackage();
if (result != S_OK)
{
return result;
}
}
// Finally we notify the shell that we have made changes, so it refreshes the context menus.
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
return S_OK;
}
void EnsureRegistrationOnCurrentUserWorker()
{
// Initialize the WinRT apartment.
winrt::init_apartment();
// Get the package to check if it is already installed for the current user.
Package existingPackage = GetSparsePackage(false);
if (existingPackage == NULL)
{
// The package is not installed for the current user - but we know that Notepad++ is.
// If it wasn't, this code wouldn't be running, so it is safe to just register the package.
RegisterSparsePackageCurrentUser();
// Finally we notify the shell that we have made changes, so it reloads the right click menu items.
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
}
void NppShell::Installer::EnsureRegistrationOnCurrentUser()
{
// First we find the name of the process the DLL is being loaded into.
wstring moduleName = GetExecutingModuleName();
if (moduleName == L"explorer.exe")
{
const bool isWindows11 = IsWindows11Installation();
if (isWindows11)
{
// We are being loaded into explorer.exe, so we can continue.
// Explorer.exe only loads the DLL on the first time a user right-clicks a file
// after that it stays in memory for the rest of their session.
// Since we are here, we spawn a thread and call the EnsureRegistrationOnCurrentUserWorker function.
thread ensureRegistrationThread = thread(EnsureRegistrationOnCurrentUserWorker);
ensureRegistrationThread.detach();
}
}
}
STDAPI CleanupDll()
{
// First we get the full path to this DLL.
wstring currentFilePath(MAX_PATH, L'\0');
GetModuleFileName(g_module, ¤tFilePath[0], MAX_PATH);
// Then we get it moved out of the way and scheduled for deletion.
return MoveFileToTempAndScheduleDeletion(currentFilePath, true);
}