├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ └── CI_build.yml ├── .gitignore ├── AclHelper.cpp ├── AclHelper.h ├── BaseNppExplorerCommandHandler.cpp ├── BaseNppExplorerCommandHandler.h ├── ClassicEditWithNppExplorerCommandHandler.cpp ├── ClassicEditWithNppExplorerCommandHandler.h ├── ExplorerCommandBase.cpp ├── ExplorerCommandBase.h ├── Installer.cpp ├── Installer.h ├── LICENSE ├── LoggingHelper.cpp ├── LoggingHelper.h ├── ModernEditWithNppExplorerCommandHandler.cpp ├── ModernEditWithNppExplorerCommandHandler.h ├── NppShell.rc ├── NppShell.sln ├── NppShell.vcxproj ├── NppShell.vcxproj.filters ├── Packaging ├── AppxManifest.xml ├── Square150x150Logo.png ├── Square44x44Logo.png └── StoreLogo.png ├── PathHelper.cpp ├── PathHelper.h ├── README.md ├── RegistryKey.cpp ├── RegistryKey.h ├── SharedCounter.cpp ├── SharedCounter.h ├── SharedState.cpp ├── SharedState.h ├── SimpleFactory.h ├── ThreadUILanguageChanger.cpp ├── ThreadUILanguageChanger.h ├── dllmain.cpp ├── framework.h ├── packages.config ├── pch.cpp ├── pch.h ├── resource.h └── source.def /.gitattributes: -------------------------------------------------------------------------------- 1 | *.h text 2 | *.rc text diff working-tree-encoding=UTF-16LE-BOM eol=crlf -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | 9 | # Maintain dependencies for GitHub Actions 10 | - package-ecosystem: "github-actions" 11 | directory: "/" 12 | schedule: 13 | interval: "monthly" 14 | 15 | - package-ecosystem: "nuget" # See documentation for possible values 16 | directory: "/" # Location of package manifests 17 | schedule: 18 | interval: "monthly" 19 | -------------------------------------------------------------------------------- /.github/workflows/CI_build.yml: -------------------------------------------------------------------------------- 1 | name: CI_build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: windows-latest 9 | strategy: 10 | matrix: 11 | build_platform: [x64, Win32, ARM64] 12 | 13 | steps: 14 | - name: Checkout repo 15 | uses: actions/checkout@v4 16 | 17 | - name: Add msbuild to PATH 18 | uses: microsoft/setup-msbuild@v2 19 | 20 | - name: Setup NuGet.exe 21 | uses: nuget/setup-nuget@v2 22 | 23 | - name: Restore 24 | working-directory: . 25 | run: nuget restore NppShell.sln 26 | 27 | - name: MSBuild of dll and msix 28 | working-directory: . 29 | run: | 30 | msbuild NppShell.sln /m /p:configuration="Debug" /p:platform="${{ matrix.build_platform }}" 31 | msbuild NppShell.sln /m /p:configuration="Release" /p:platform="${{ matrix.build_platform }}" 32 | 33 | - name: Archive artifacts for win32 34 | if: matrix.build_platform == 'Win32' 35 | uses: actions/upload-artifact@v4 36 | with: 37 | name: artifacts_win32 38 | path: | 39 | Release\NppShell.x86.dll 40 | 41 | - name: Archive artifacts for x64 42 | if: matrix.build_platform == 'x64' 43 | uses: actions/upload-artifact@v4 44 | with: 45 | name: artifacts_x64 46 | path: | 47 | ${{ matrix.build_platform }}\Release\NppShell.x64.dll 48 | ${{ matrix.build_platform }}\Release\NppShell.msix 49 | 50 | - name: Archive artifacts for ARM64 51 | if: matrix.build_platform == 'ARM64' 52 | uses: actions/upload-artifact@v4 53 | with: 54 | name: artifacts_arm64 55 | path: | 56 | ${{ matrix.build_platform }}\Release\NppShell.arm64.dll 57 | ${{ matrix.build_platform }}\Release\NppShell.msix 58 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | packages 2 | Packaging/NppShell.msix 3 | .vs 4 | *.user 5 | Debug 6 | Release 7 | *.user 8 | *.aps 9 | -------------------------------------------------------------------------------- /AclHelper.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "AclHelper.h" 3 | 4 | AclHelper::AclHelper() 5 | { 6 | emptyAcl = (PACL)malloc(sizeof(ACL)); 7 | 8 | if (emptyAcl) 9 | { 10 | InitializeAcl(emptyAcl, sizeof(ACL), ACL_REVISION); 11 | } 12 | } 13 | 14 | AclHelper::~AclHelper() 15 | { 16 | if (emptyAcl) 17 | { 18 | free(emptyAcl); 19 | } 20 | } 21 | 22 | DWORD AclHelper::ResetAcl(const wstring& path) 23 | { 24 | if (emptyAcl) 25 | { 26 | return SetNamedSecurityInfoW(const_cast(path.c_str()), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, emptyAcl, NULL); 27 | } 28 | else 29 | { 30 | return ERROR_OUTOFMEMORY; 31 | } 32 | } -------------------------------------------------------------------------------- /AclHelper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class AclHelper 4 | { 5 | public: 6 | AclHelper(); 7 | ~AclHelper(); 8 | 9 | DWORD ResetAcl(const wstring& path); 10 | 11 | private: 12 | PACL emptyAcl; 13 | }; -------------------------------------------------------------------------------- /BaseNppExplorerCommandHandler.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "resource.h" 3 | #include "BaseNppExplorerCommandHandler.h" 4 | 5 | #include "PathHelper.h" 6 | #include "ThreadUILanguageChanger.h" 7 | 8 | using namespace NppShell::CommandHandlers; 9 | using namespace NppShell::Helpers; 10 | 11 | extern HMODULE g_module; 12 | 13 | BaseNppExplorerCommandHandler::BaseNppExplorerCommandHandler() 14 | { 15 | counter = make_unique(); 16 | state = make_unique(); 17 | } 18 | 19 | const wstring BaseNppExplorerCommandHandler::GetNppExecutableFullPath() 20 | { 21 | const wstring path = GetApplicationPath(); 22 | const wstring fileName = L"\\notepad++.exe"; 23 | 24 | return path + fileName; 25 | } 26 | 27 | bool ReadLanguageOverrideFile(wstring& content) 28 | { 29 | const wstring fileFullName = GetContextMenuPath() + L"\\overrideMenuEntryLanguage.txt"; 30 | 31 | // Open the file for reading. 32 | HANDLE file = CreateFileW(fileFullName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 33 | if (file == INVALID_HANDLE_VALUE) 34 | { 35 | // The file does not exist, so no override. 36 | return false; 37 | } 38 | 39 | // Allocate a buffer for the file content. 40 | // Since we only need 6 chars ("xx-XX" followed by a null byte, maybe double if unicode encoded), so we use 32 bytes, to be on the safe side. 41 | const DWORD bufferSize = 32; 42 | vector buffer(bufferSize); 43 | 44 | // Read the first 32 chars into the buffer. 45 | DWORD bytesRead; 46 | if (!ReadFile(file, buffer.data(), bufferSize - 1, &bytesRead, NULL)) 47 | { 48 | CloseHandle(file); 49 | 50 | return false; 51 | } 52 | 53 | // Close the file handle 54 | CloseHandle(file); 55 | 56 | // Null-terminate the buffer 57 | buffer[bytesRead] = '\0'; 58 | 59 | // Convert the buffer to a wstring 60 | content = wstring(buffer.begin(), buffer.begin() + bytesRead); 61 | 62 | if (content == L"") 63 | { 64 | // The file exists, but is empty, so we default to "en-US"; 65 | content = L"en-US"; 66 | } 67 | 68 | return true; 69 | } 70 | 71 | const wstring BaseNppExplorerCommandHandler::Title() 72 | { 73 | // A buffer size of 1024 should be enough to hold the for all languages. 74 | constexpr int bufferSize = 1024; 75 | 76 | // Buffer to store the string resource into. 77 | WCHAR buffer[bufferSize]; 78 | 79 | // Read the override file, and if success, we change the language we use. 80 | wstring overrideLanguage; 81 | if (ReadLanguageOverrideFile(overrideLanguage)) 82 | { 83 | // Change the language 84 | ThreadUILanguageChanger languageChanger(overrideLanguage); 85 | 86 | // Load the string from the resource matching the override language. 87 | LoadStringW(g_module, IDS_EDIT_WITH_NOTEPADPLUSPLUS, buffer, bufferSize); 88 | } 89 | else 90 | { 91 | // Load the string from the resource matching the current language. 92 | LoadStringW(g_module, IDS_EDIT_WITH_NOTEPADPLUSPLUS, buffer, bufferSize); 93 | } 94 | 95 | // Finally we convert the buffer into a wstring that we can return. 96 | return wstring(buffer); 97 | } 98 | 99 | const wstring BaseNppExplorerCommandHandler::Icon() 100 | { 101 | const wstring fileName = GetNppExecutableFullPath(); 102 | 103 | return fileName; 104 | } 105 | 106 | const wstring BaseNppExplorerCommandHandler::GetCommandLine(const wstring& itemName) 107 | { 108 | const wstring fileName = GetNppExecutableFullPath(); 109 | const wstring parameters = L"\"" + itemName + L"\""; 110 | 111 | return L"\"" + fileName + L"\" " + parameters; 112 | } 113 | 114 | IFACEMETHODIMP BaseNppExplorerCommandHandler::Invoke(IShellItemArray* psiItemArray, IBindCtx* pbc) noexcept try 115 | { 116 | UNREFERENCED_PARAMETER(pbc); 117 | 118 | if (!psiItemArray) 119 | { 120 | return S_OK; 121 | } 122 | 123 | DWORD count; 124 | RETURN_IF_FAILED(psiItemArray->GetCount(&count)); 125 | 126 | IShellItem* psi = nullptr; 127 | LPWSTR file2OpenPath; 128 | 129 | wstring appPath = L"\""; 130 | appPath += GetNppExecutableFullPath().c_str(); 131 | appPath += L"\""; 132 | 133 | wstring filePathsArg = appPath; 134 | filePathsArg += L" "; 135 | 136 | for (DWORD i = 0; i < count; ++i) 137 | { 138 | psiItemArray->GetItemAt(i, &psi); 139 | RETURN_IF_FAILED(psi->GetDisplayName(SIGDN_FILESYSPATH, &file2OpenPath)); 140 | // Release the IShellItem pointer, since we are done with it as well. 141 | psi->Release(); 142 | 143 | filePathsArg += L"\""; 144 | filePathsArg += file2OpenPath; 145 | filePathsArg += L"\" "; 146 | 147 | // Cleanup itemName, since we are done with it. 148 | if (file2OpenPath) 149 | { 150 | CoTaskMemFree(file2OpenPath); 151 | } 152 | } 153 | 154 | STARTUPINFO si; 155 | PROCESS_INFORMATION pi; 156 | 157 | ZeroMemory(&si, sizeof(si)); 158 | si.cb = sizeof(si); 159 | ZeroMemory(&pi, sizeof(pi)); 160 | 161 | if (!CreateProcessW(GetNppExecutableFullPath().c_str(), (LPWSTR)filePathsArg.c_str(), nullptr, nullptr, false, CREATE_NEW_PROCESS_GROUP, nullptr, nullptr, &si, &pi)) 162 | { 163 | return S_OK; 164 | } 165 | 166 | CloseHandle(pi.hProcess); 167 | CloseHandle(pi.hThread); 168 | 169 | return S_OK; 170 | } 171 | CATCH_RETURN(); 172 | 173 | const EXPCMDSTATE BaseNppExplorerCommandHandler::State(IShellItemArray* psiItemArray) 174 | { 175 | UNREFERENCED_PARAMETER(psiItemArray); 176 | 177 | throw L"State must be overridden in all implementations"; 178 | } -------------------------------------------------------------------------------- /BaseNppExplorerCommandHandler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "ExplorerCommandBase.h" 3 | #include "SharedCounter.h" 4 | #include "SharedState.h" 5 | 6 | using namespace NppShell::Helpers; 7 | 8 | namespace NppShell::CommandHandlers 9 | { 10 | class BaseNppExplorerCommandHandler : public ExplorerCommandBase 11 | { 12 | public: 13 | BaseNppExplorerCommandHandler(); 14 | 15 | const wstring Title() override; 16 | const wstring Icon() override; 17 | 18 | IFACEMETHODIMP Invoke(IShellItemArray* psiItemArray, IBindCtx* pbc) noexcept override; 19 | 20 | virtual const EXPCMDSTATE State(IShellItemArray* psiItemArray) override; 21 | 22 | private: 23 | const wstring GetNppExecutableFullPath(); 24 | const wstring GetCommandLine(const wstring& itemName); 25 | 26 | protected: 27 | unique_ptr counter; 28 | unique_ptr state; 29 | }; 30 | } -------------------------------------------------------------------------------- /ClassicEditWithNppExplorerCommandHandler.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "ClassicEditWithNppExplorerCommandHandler.h" 3 | 4 | #include "LoggingHelper.h" 5 | #include "SharedState.h" 6 | 7 | using namespace NppShell::CommandHandlers; 8 | using namespace NppShell::Helpers; 9 | 10 | extern LoggingHelper g_loggingHelper; 11 | 12 | ClassicEditWithNppExplorerCommandHandler::ClassicEditWithNppExplorerCommandHandler() 13 | { 14 | g_loggingHelper.LogMessage(L"ClassicEditWithNppExplorerCommandHandler::ctor", L"Creating object"); 15 | } 16 | 17 | ClassicEditWithNppExplorerCommandHandler::~ClassicEditWithNppExplorerCommandHandler() 18 | { 19 | g_loggingHelper.LogMessage(L"ClassicEditWithNppExplorerCommandHandler::~tor", L"Destroying object"); 20 | } 21 | 22 | const EXPCMDSTATE ClassicEditWithNppExplorerCommandHandler::State(IShellItemArray* psiItemArray) 23 | { 24 | UNREFERENCED_PARAMETER(psiItemArray); 25 | 26 | // First we get the current state, before we clear it. 27 | CounterState currentState = state->GetState(L"ClassicEditWithNppExplorerCommandHandler"); 28 | state->SetState(L"ClassicEditWithNppExplorerCommandHandler", NotSet); 29 | 30 | g_loggingHelper.LogMessage(L"ClassicEditWithNppExplorerCommandHandler::State", L"Current state: " + std::to_wstring(currentState)); 31 | 32 | // If it is set, it means the State function has been called in the Modern command handler last, which means we should hide this one. 33 | if (currentState == CounterState::Set) 34 | { 35 | return ECS_HIDDEN; 36 | } 37 | 38 | return ECS_ENABLED; 39 | } -------------------------------------------------------------------------------- /ClassicEditWithNppExplorerCommandHandler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "BaseNppExplorerCommandHandler.h" 3 | 4 | using namespace NppShell::Helpers; 5 | 6 | namespace NppShell::CommandHandlers 7 | { 8 | #ifdef WIN64 9 | class __declspec(uuid("B298D29A-A6ED-11DE-BA8C-A68E55D89593")) ClassicEditWithNppExplorerCommandHandler : public BaseNppExplorerCommandHandler 10 | #else 11 | class __declspec(uuid("00F3C2EC-A6EE-11DE-A03A-EF8F55D89593")) ClassicEditWithNppExplorerCommandHandler : public BaseNppExplorerCommandHandler 12 | #endif 13 | { 14 | public: 15 | ClassicEditWithNppExplorerCommandHandler(); 16 | ~ClassicEditWithNppExplorerCommandHandler(); 17 | 18 | const EXPCMDSTATE State(IShellItemArray* psiItemArray); 19 | }; 20 | } -------------------------------------------------------------------------------- /ExplorerCommandBase.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "ExplorerCommandBase.h" 3 | 4 | using namespace NppShell::CommandHandlers; 5 | 6 | const EXPCMDFLAGS ExplorerCommandBase::Flags() 7 | { 8 | return ECF_DEFAULT; 9 | } 10 | 11 | IFACEMETHODIMP ExplorerCommandBase::GetTitle(IShellItemArray* psiItemArray, LPWSTR* ppszName) 12 | { 13 | UNREFERENCED_PARAMETER(psiItemArray); 14 | 15 | wstring title = Title(); 16 | SHStrDup(title.data(), ppszName); 17 | 18 | return S_OK; 19 | } 20 | 21 | IFACEMETHODIMP ExplorerCommandBase::GetIcon(IShellItemArray* psiItemArray, LPWSTR* ppszIcon) 22 | { 23 | UNREFERENCED_PARAMETER(psiItemArray); 24 | 25 | wstring icon = Icon(); 26 | SHStrDup(icon.data(), ppszIcon); 27 | 28 | return S_OK; 29 | } 30 | 31 | IFACEMETHODIMP ExplorerCommandBase::GetToolTip(IShellItemArray* psiItemArray, LPWSTR* ppszInfotip) 32 | { 33 | UNREFERENCED_PARAMETER(psiItemArray); 34 | UNREFERENCED_PARAMETER(ppszInfotip); 35 | 36 | return E_NOTIMPL; 37 | } 38 | 39 | IFACEMETHODIMP ExplorerCommandBase::GetState(IShellItemArray* psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE* pCmdState) 40 | { 41 | UNREFERENCED_PARAMETER(fOkToBeSlow); 42 | 43 | *pCmdState = State(psiItemArray); 44 | return S_OK; 45 | } 46 | 47 | IFACEMETHODIMP ExplorerCommandBase::GetFlags(EXPCMDFLAGS* flags) 48 | { 49 | *flags = Flags(); 50 | return S_OK; 51 | } 52 | 53 | IFACEMETHODIMP ExplorerCommandBase::GetCanonicalName(GUID* pguidCommandName) 54 | { 55 | *pguidCommandName = GUID_NULL; 56 | return S_OK; 57 | } 58 | 59 | IFACEMETHODIMP ExplorerCommandBase::EnumSubCommands(IEnumExplorerCommand** ppEnum) 60 | { 61 | *ppEnum = nullptr; 62 | return E_NOTIMPL; 63 | } -------------------------------------------------------------------------------- /ExplorerCommandBase.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | namespace NppShell::CommandHandlers 5 | { 6 | class ExplorerCommandBase : public winrt::implements 7 | { 8 | public: 9 | virtual const wstring Title() = 0; 10 | virtual const wstring Icon() = 0; 11 | virtual const EXPCMDFLAGS Flags(); 12 | virtual const EXPCMDSTATE State(IShellItemArray* psiItemArray) = 0; 13 | 14 | IFACEMETHODIMP GetTitle(IShellItemArray* psiItemArray, LPWSTR* ppszName); 15 | IFACEMETHODIMP GetIcon(IShellItemArray* psiItemArray, LPWSTR* ppszIcon); 16 | IFACEMETHODIMP GetToolTip(IShellItemArray* psiItemArray, LPWSTR* ppszInfotip); 17 | IFACEMETHODIMP GetState(IShellItemArray* psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE* pCmdState); 18 | IFACEMETHODIMP GetFlags(EXPCMDFLAGS* flags); 19 | IFACEMETHODIMP GetCanonicalName(GUID* pguidCommandName); 20 | IFACEMETHODIMP EnumSubCommands(IEnumExplorerCommand** ppEnum); 21 | 22 | virtual IFACEMETHODIMP Invoke(IShellItemArray* psiItemArray, IBindCtx* pbc) noexcept = 0; 23 | }; 24 | } -------------------------------------------------------------------------------- /Installer.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "Installer.h" 3 | 4 | #include "ClassicEditWithNppExplorerCommandHandler.h" 5 | #include "PathHelper.h" 6 | #include "AclHelper.h" 7 | #include "RegistryKey.h" 8 | 9 | #define GUID_STRING_SIZE 40 10 | 11 | using namespace winrt::Windows::ApplicationModel; 12 | using namespace winrt::Windows::Foundation; 13 | using namespace winrt::Windows::Foundation::Collections; 14 | using namespace winrt::Windows::Management::Deployment; 15 | 16 | using namespace NppShell::Helpers; 17 | using namespace NppShell::Installer; 18 | using namespace NppShell::Registry; 19 | 20 | 21 | extern HMODULE g_module; 22 | 23 | const wstring SparsePackageName = L"NotepadPlusPlus"; 24 | constexpr int FirstWindows11BuildNumber = 22000; 25 | 26 | #ifdef WIN64 27 | const wstring ShellKey = L"Software\\Classes\\*\\shell\\ANotepad++64"; 28 | const wstring ShellExtensionKey = L"Software\\Classes\\*\\shellex\\ContextMenuHandlers\\ANotepad++64"; 29 | #else 30 | const wstring ShellKey = L"Software\\Classes\\*\\shell\\ANotepad++"; 31 | const wstring ShellExtensionKey = L"Software\\Classes\\*\\shellex\\ContextMenuHandlers\\ANotepad++"; 32 | #endif 33 | 34 | bool IsWindows11Installation() 35 | { 36 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); 37 | wstring buildNumberString = registryKey.GetStringValue(L"CurrentBuildNumber"); 38 | 39 | const int buildNumber = stoi(buildNumberString); 40 | 41 | return buildNumber >= FirstWindows11BuildNumber; 42 | } 43 | 44 | wstring GetCLSIDString() 45 | { 46 | const auto uuid = __uuidof(NppShell::CommandHandlers::ClassicEditWithNppExplorerCommandHandler); 47 | 48 | LPOLESTR guidString = 0; 49 | const HRESULT result = StringFromCLSID(uuid, &guidString); 50 | 51 | if (FAILED(result)) 52 | { 53 | if (guidString) 54 | { 55 | CoTaskMemFree(guidString); 56 | } 57 | 58 | throw "Failed to parse GUID from command handler"; 59 | } 60 | 61 | wstring guid(guidString); 62 | 63 | if (guidString) 64 | { 65 | CoTaskMemFree(guidString); 66 | } 67 | 68 | return guid; 69 | } 70 | 71 | void inline CleanupRegistry(const wstring& guid) 72 | { 73 | // First we remove the shell key if it exists. 74 | if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, ShellKey)) 75 | { 76 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, ShellKey, KEY_READ | KEY_WRITE); 77 | registryKey.DeleteKey(); 78 | } 79 | 80 | // Then we remove the shell extension key if it exists. 81 | if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, ShellExtensionKey)) 82 | { 83 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, ShellExtensionKey, KEY_READ | KEY_WRITE); 84 | registryKey.DeleteKey(); 85 | } 86 | 87 | // Then we remove the Notepad++_file key if it exists. 88 | if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"Notepad++_file\\shellex")) 89 | { 90 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"Notepad++_file\\shellex", KEY_READ | KEY_WRITE); 91 | registryKey.DeleteKey(); 92 | } 93 | 94 | // Finally we remove the CLSID key if it exists. 95 | if (RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid)) 96 | { 97 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid, KEY_READ | KEY_WRITE); 98 | registryKey.DeleteKey(); 99 | } 100 | } 101 | 102 | void inline CleanupHack() 103 | { 104 | // First we test if the key even exists. 105 | if (!RegistryKey::KeyExists(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Classes\\*\\shell\\pintohome")) 106 | { 107 | return; 108 | } 109 | 110 | // If it does, we open it and check if the value exists. 111 | wstring valueName = L"MUIVerb"; 112 | RegistryKey registryKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Classes\\*\\shell\\pintohome", KEY_READ | KEY_WRITE); 113 | 114 | if (!registryKey.ValueExists(valueName)) 115 | { 116 | return; 117 | } 118 | 119 | // Then we get the value and see if it contains the text "Notepad++" 120 | wstring currentValue = registryKey.GetStringValue(valueName); 121 | bool found = currentValue.find(L"Notepad++") != wstring::npos; 122 | 123 | // If we found the text, we delete the entire key. 124 | if (found) 125 | { 126 | registryKey.DeleteKey(); 127 | } 128 | } 129 | 130 | HRESULT MoveFileToTempAndScheduleDeletion(const wstring& filePath, bool moveToTempDirectory) 131 | { 132 | // Recommended way to check if a file exist: 133 | // https://devblogs.microsoft.com/oldnewthing/20071023-00/?p=24713 134 | DWORD fileAttributes = GetFileAttributesW(filePath.c_str()); 135 | 136 | if (fileAttributes == INVALID_FILE_ATTRIBUTES) 137 | { 138 | // If GetFileAttributes return INVALID_FILE_ATTRIBUTES, that means the file doesn't exist. 139 | // In that case, we shouldn't try and schedule a deletion of it. 140 | return S_OK; 141 | } 142 | 143 | wstring tempPath(MAX_PATH, L'\0'); 144 | wstring tempFileName(MAX_PATH, L'\0'); 145 | 146 | BOOL moveResult; 147 | 148 | if (moveToTempDirectory) 149 | { 150 | // First we get the path to the temporary directory. 151 | GetTempPath(MAX_PATH, &tempPath[0]); 152 | 153 | // Then we get a temporary filename in the temporary directory. 154 | GetTempFileName(tempPath.c_str(), L"tempFileName", 0, &tempFileName[0]); 155 | 156 | // Move the file into the temp directory - it can be moved even when it is loaded into memory and locked. 157 | moveResult = MoveFileEx(filePath.c_str(), tempFileName.c_str(), MOVEFILE_REPLACE_EXISTING); 158 | 159 | if (!moveResult) 160 | { 161 | return S_FALSE; 162 | } 163 | 164 | // Schedule it to be deleted from the temp directory on the next reboot. 165 | moveResult = MoveFileExW(tempFileName.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT); 166 | } 167 | else 168 | { 169 | // Schedule it to be deleted on the next reboot, without moving it. 170 | moveResult = MoveFileExW(filePath.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT); 171 | } 172 | 173 | if (!moveResult) 174 | { 175 | return S_FALSE; 176 | } 177 | 178 | return S_OK; 179 | } 180 | 181 | void ResetAclPermissionsOnApplicationFolder() 182 | { 183 | // First we get the path where Notepad++ is installed. 184 | const wstring applicationPath = GetApplicationPath(); 185 | 186 | // Create a new AclHelper 187 | AclHelper aclHelper; 188 | 189 | // Reset the ACL of the folder where Notepad++ is installed. 190 | aclHelper.ResetAcl(applicationPath); 191 | } 192 | 193 | Package GetSparsePackage() 194 | { 195 | PackageManager packageManager; 196 | IIterable packages; 197 | 198 | try 199 | { 200 | packages = packageManager.FindPackagesForUser(L""); 201 | } 202 | catch (winrt::hresult_error) 203 | { 204 | return NULL; 205 | } 206 | 207 | for (const Package& package : packages) 208 | { 209 | if (package.Id().Name() != SparsePackageName) 210 | { 211 | continue; 212 | } 213 | 214 | return package; 215 | } 216 | 217 | return NULL; 218 | } 219 | 220 | HRESULT NppShell::Installer::RegisterSparsePackage() 221 | { 222 | if (::GetSystemMetrics(SM_CLEANBOOT) > 0) 223 | { 224 | return S_FALSE; // Otherwise we will get an unhandled exception later due to HRESULT 0x8007043c (ERROR_NOT_SAFEBOOT_SERVICE). 225 | } 226 | 227 | PackageManager packageManager; 228 | AddPackageOptions options; 229 | 230 | const wstring externalLocation = GetContextMenuPath(); 231 | const wstring sparsePkgPath = externalLocation + L"\\NppShell.msix"; 232 | 233 | Uri externalUri(externalLocation); 234 | Uri packageUri(sparsePkgPath); 235 | 236 | options.ExternalLocationUri(externalUri); 237 | 238 | auto deploymentOperation = packageManager.AddPackageByUriAsync(packageUri, options); 239 | auto deployResult = deploymentOperation.get(); 240 | 241 | if (!SUCCEEDED(deployResult.ExtendedErrorCode())) 242 | { 243 | return deployResult.ExtendedErrorCode(); 244 | } 245 | 246 | return S_OK; 247 | } 248 | 249 | HRESULT NppShell::Installer::UnregisterSparsePackage() 250 | { 251 | if (::GetSystemMetrics(SM_CLEANBOOT) > 0) 252 | { 253 | return S_FALSE; // Only to speed up things a bit here. (code in the following GetSparsePackage() is safe against the ERROR_NOT_SAFEBOOT_SERVICE) 254 | } 255 | 256 | PackageManager packageManager; 257 | IIterable packages; 258 | 259 | Package package = GetSparsePackage(); 260 | 261 | if (package == NULL) 262 | { 263 | return S_FALSE; 264 | } 265 | 266 | winrt::hstring fullName = package.Id().FullName(); 267 | auto deploymentOperation = packageManager.RemovePackageAsync(fullName, RemovalOptions::None); 268 | auto deployResult = deploymentOperation.get(); 269 | 270 | if (!SUCCEEDED(deployResult.ExtendedErrorCode())) 271 | { 272 | return deployResult.ExtendedErrorCode(); 273 | } 274 | 275 | // After unregistering the sparse package, we reset the folder permissions of the folder where we are installed. 276 | ResetAclPermissionsOnApplicationFolder(); 277 | 278 | return S_OK; 279 | } 280 | 281 | HRESULT NppShell::Installer::RegisterOldContextMenu() 282 | { 283 | const wstring contextMenuFullName = GetContextMenuFullName(); 284 | const wstring guid = GetCLSIDString(); 285 | 286 | // First we set the shell extension values. 287 | RegistryKey regKeyExtension(HKEY_LOCAL_MACHINE, ShellKey, KEY_READ | KEY_WRITE, true); 288 | regKeyExtension.SetStringValue(L"", L"Notepad++ Context menu"); 289 | regKeyExtension.SetStringValue(L"ExplorerCommandHandler", guid); 290 | regKeyExtension.SetStringValue(L"NeverDefault", L""); 291 | 292 | // Then we create the CLSID for the handler with it's values. 293 | RegistryKey regKeyClsid(HKEY_LOCAL_MACHINE, L"Software\\Classes\\CLSID\\" + guid, KEY_READ | KEY_WRITE, true); 294 | regKeyClsid.SetStringValue(L"", L"notepad++"); 295 | 296 | RegistryKey regKeyInProc = regKeyClsid.GetSubKey(L"InProcServer32", true); 297 | regKeyInProc.SetStringValue(L"", contextMenuFullName); 298 | regKeyInProc.SetStringValue(L"ThreadingModel", L"Apartment"); 299 | 300 | return S_OK; 301 | } 302 | 303 | HRESULT NppShell::Installer::UnregisterOldContextMenu() 304 | { 305 | const wstring guid = GetCLSIDString(); 306 | 307 | // Clean up registry entries. 308 | CleanupRegistry(guid); 309 | 310 | return S_OK; 311 | } 312 | 313 | void ReRegisterSparsePackage() 314 | { 315 | if (::GetSystemMetrics(SM_CLEANBOOT) > 0) 316 | { 317 | return; // Sparse package reg/unreg cannot be done in the Windows OS SafeMode. 318 | } 319 | 320 | winrt::init_apartment(); 321 | 322 | // Since we are on Windows 11, we unregister the sparse package as well. 323 | UnregisterSparsePackage(); 324 | 325 | // And then we register it again. 326 | RegisterSparsePackage(); 327 | } 328 | 329 | HRESULT NppShell::Installer::Install() 330 | { 331 | const bool isWindows11 = IsWindows11Installation(); 332 | 333 | HRESULT result; 334 | 335 | // Clean up the 8.5 Windows 11 hack if present. 336 | CleanupHack(); 337 | 338 | if (isWindows11) 339 | { 340 | // We need to unregister the old menu on Windows 11 to prevent double entries in the old menu. 341 | UnregisterOldContextMenu(); 342 | 343 | // To register the sparse package, we need to do it on another thread due to WinRT requirements. 344 | thread reRegisterThread(ReRegisterSparsePackage); 345 | reRegisterThread.join(); 346 | } 347 | 348 | result = RegisterOldContextMenu(); 349 | 350 | // Ensure we schedule old files for removal on next reboot. 351 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_01.dll", false); 352 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_02.dll", false); 353 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_03.dll", false); 354 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_04.dll", false); 355 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_05.dll", false); 356 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell_06.dll", false); 357 | 358 | // This include the old NppModernShell and NppShell files from the main program directory. 359 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell.dll", false); 360 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppShell.msix", false); 361 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppModernShell.dll", false); 362 | MoveFileToTempAndScheduleDeletion(GetApplicationPath() + L"\\NppModernShell.msix", false); 363 | 364 | // Finally we notify the shell that we have made changes, so it refreshes the context menus. 365 | SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0); 366 | 367 | return result; 368 | } 369 | 370 | HRESULT NppShell::Installer::Uninstall() 371 | { 372 | const bool isWindows11 = IsWindows11Installation(); 373 | 374 | HRESULT result; 375 | 376 | // We remove the old context menu in all cases, since both Windows 11 and older versions can have it setup if upgrading. 377 | result = UnregisterOldContextMenu(); 378 | 379 | if (result != S_OK) 380 | { 381 | return result; 382 | } 383 | 384 | if (isWindows11) 385 | { 386 | // Since we are on Windows 11, we unregister the sparse package as well. 387 | result = UnregisterSparsePackage(); 388 | 389 | if (result != S_OK) 390 | { 391 | return result; 392 | } 393 | } 394 | 395 | // Finally we notify the shell that we have made changes, so it refreshes the context menus. 396 | SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0); 397 | 398 | return S_OK; 399 | } 400 | 401 | void EnsureRegistrationOnCurrentUserWorker() 402 | { 403 | // Initialize the WinRT apartment. 404 | winrt::init_apartment(); 405 | 406 | // Get the package to check if it is already installed for the current user. 407 | Package existingPackage = GetSparsePackage(); 408 | 409 | if (existingPackage == NULL) 410 | { 411 | // The package is not installed for the current user - but we know that Notepad++ is. 412 | // If it wasn't, this code wouldn't be running, so it is safe to just register the package. 413 | RegisterSparsePackage(); 414 | 415 | // Finally we notify the shell that we have made changes, so it reloads the right click menu items. 416 | SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0); 417 | } 418 | } 419 | 420 | void NppShell::Installer::EnsureRegistrationOnCurrentUser() 421 | { 422 | // First we find the name of the process the DLL is being loaded into. 423 | wstring moduleName = GetExecutingModuleName(); 424 | 425 | if (moduleName == L"explorer.exe") 426 | { 427 | const bool isWindows11 = IsWindows11Installation(); 428 | 429 | if (isWindows11) 430 | { 431 | // We are being loaded into explorer.exe, so we can continue. 432 | // Explorer.exe only loads the DLL on the first time a user right-clicks a file 433 | // after that it stays in memory for the rest of their session. 434 | // Since we are here, we spawn a thread and call the EnsureRegistrationOnCurrentUserWorker function. 435 | thread ensureRegistrationThread = thread(EnsureRegistrationOnCurrentUserWorker); 436 | ensureRegistrationThread.detach(); 437 | } 438 | } 439 | } 440 | 441 | STDAPI CleanupDll() 442 | { 443 | // First we get the full path to this DLL. 444 | wstring currentFilePath(MAX_PATH, L'\0'); 445 | GetModuleFileName(g_module, ¤tFilePath[0], MAX_PATH); 446 | 447 | // Then we get it moved out of the way and scheduled for deletion. 448 | return MoveFileToTempAndScheduleDeletion(currentFilePath, true); 449 | } 450 | -------------------------------------------------------------------------------- /Installer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | namespace NppShell::Installer 5 | { 6 | HRESULT RegisterOldContextMenu(); 7 | HRESULT UnregisterOldContextMenu(); 8 | 9 | HRESULT RegisterSparsePackage(); 10 | HRESULT UnregisterSparsePackage(); 11 | 12 | HRESULT Install(); 13 | HRESULT Uninstall(); 14 | 15 | void EnsureRegistrationOnCurrentUser(); 16 | } 17 | 18 | STDAPI CleanupDll(); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /LoggingHelper.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "LoggingHelper.h" 3 | 4 | #include 5 | 6 | using namespace NppShell::Helpers; 7 | 8 | LoggingHelper::LoggingHelper() 9 | { 10 | appDataLoggingEnabled = IsAppDataLoggingEnabled(); 11 | 12 | if (!appDataLoggingEnabled) 13 | { 14 | return; 15 | } 16 | 17 | const wstring logFileFolder = CreateAppDataFolder(); 18 | logFilePath = logFileFolder + L"\\NppShell.log"; 19 | } 20 | 21 | void LoggingHelper::LogMessage(const wstring& source, const wstring& message) 22 | { 23 | if (!appDataLoggingEnabled) 24 | { 25 | return; 26 | } 27 | 28 | wofstream file(logFilePath, ios_base::app); 29 | if (file.is_open()) 30 | { 31 | file << GetTimestamp(); 32 | file << L" - "; 33 | file << source; 34 | file << L": "; 35 | file << message; 36 | file << endl; 37 | file.close(); 38 | } 39 | } 40 | 41 | wstring LoggingHelper::GetRoamingAppDataFolderPath() 42 | { 43 | // Initialize COM 44 | CoInitialize(NULL); 45 | 46 | // Create an instance of the KnownFolderManager interface 47 | IKnownFolderManager* pManager; 48 | HRESULT hr = CoCreateInstance(CLSID_KnownFolderManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pManager)); 49 | 50 | if (FAILED(hr)) 51 | { 52 | // Handle error 53 | return L""; 54 | } 55 | 56 | // Get the Roaming App Data folder 57 | IKnownFolder* pFolder; 58 | hr = pManager->GetFolder(FOLDERID_RoamingAppData, &pFolder); 59 | if (FAILED(hr)) 60 | { 61 | // Handle error 62 | pManager->Release(); 63 | return L""; 64 | } 65 | 66 | // Get the path to the Roaming App Data folder 67 | PWSTR pszPath = nullptr; 68 | hr = pFolder->GetPath(KF_FLAG_DEFAULT, &pszPath); 69 | if (FAILED(hr)) 70 | { 71 | // Handle error 72 | pFolder->Release(); 73 | pManager->Release(); 74 | 75 | return L""; 76 | } 77 | 78 | // Convert the path to a wstring 79 | wstring path(pszPath); 80 | 81 | // Free the allocated memory 82 | CoTaskMemFree(pszPath); 83 | 84 | // Release interfaces 85 | pFolder->Release(); 86 | pManager->Release(); 87 | 88 | // Uninitialize COM 89 | CoUninitialize(); 90 | 91 | // Return the path to the Roaming App Data folder 92 | return path; 93 | } 94 | 95 | wstring LoggingHelper::CreateAppDataFolder() 96 | { 97 | wstring folderPath = GetRoamingAppDataFolderPath() + L"\\NppShell"; 98 | 99 | if (!CreateDirectoryW(folderPath.c_str(), NULL) && GetLastError() != ERROR_ALREADY_EXISTS) 100 | { 101 | throw runtime_error("Failed to create folder"); 102 | } 103 | 104 | return folderPath; 105 | } 106 | 107 | wstring LoggingHelper::GetTimestamp() 108 | { 109 | SYSTEMTIME st; 110 | GetLocalTime(&st); 111 | 112 | wchar_t buffer[25]; 113 | swprintf_s(buffer, L"%04d-%02d-%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); 114 | 115 | return wstring(buffer); 116 | } 117 | 118 | bool LoggingHelper::IsAppDataLoggingEnabled() 119 | { 120 | const wstring environmentVariableName = L"NPPSHELL_LOGGING_ENABLED"; 121 | 122 | // Get the size of the buffer required to hold the environment variable value 123 | DWORD size = GetEnvironmentVariableW(environmentVariableName.c_str(), nullptr, 0); 124 | if (size == 0) 125 | { 126 | // The specified environment variable was not found 127 | return false; 128 | } 129 | 130 | // Allocate a buffer to hold the environment variable value 131 | wstring buffer(size, L'\0'); 132 | 133 | // Retrieve the environment variable value 134 | DWORD result = GetEnvironmentVariableW(environmentVariableName.c_str(), buffer.data(), size); 135 | if (result == 0 || result > size) 136 | { 137 | // An error occurred while retrieving the environment variable value 138 | return false; 139 | } 140 | 141 | // Return if the value is set to true 142 | return wstring(buffer.data()) == L"true"; 143 | } -------------------------------------------------------------------------------- /LoggingHelper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace NppShell::Helpers 4 | { 5 | class LoggingHelper 6 | { 7 | public: 8 | LoggingHelper(); 9 | void LogMessage(const wstring& source, const wstring& message); 10 | 11 | private: 12 | wstring GetRoamingAppDataFolderPath(); 13 | wstring CreateAppDataFolder(); 14 | wstring GetTimestamp(); 15 | bool IsAppDataLoggingEnabled(); 16 | 17 | bool appDataLoggingEnabled; 18 | wstring logFilePath; 19 | }; 20 | } -------------------------------------------------------------------------------- /ModernEditWithNppExplorerCommandHandler.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "ModernEditWithNppExplorerCommandHandler.h" 3 | 4 | #include "SharedState.h" 5 | #include "LoggingHelper.h" 6 | 7 | using namespace NppShell::CommandHandlers; 8 | using namespace NppShell::Helpers; 9 | 10 | extern LoggingHelper g_loggingHelper; 11 | 12 | ModernEditWithNppExplorerCommandHandler::ModernEditWithNppExplorerCommandHandler() 13 | { 14 | g_loggingHelper.LogMessage(L"ModernEditWithNppExplorerCommandHandler::ctor", L"Creating object"); 15 | } 16 | 17 | ModernEditWithNppExplorerCommandHandler::~ModernEditWithNppExplorerCommandHandler() 18 | { 19 | g_loggingHelper.LogMessage(L"ModernEditWithNppExplorerCommandHandler::~tor", L"Destroying object"); 20 | } 21 | 22 | const EXPCMDSTATE ModernEditWithNppExplorerCommandHandler::State(IShellItemArray* psiItemArray) 23 | { 24 | UNREFERENCED_PARAMETER(psiItemArray); 25 | 26 | state->SetState(L"ModernEditWithNppExplorerCommandHandler", Set); 27 | 28 | g_loggingHelper.LogMessage(L"ModernEditWithNppExplorerCommandHandler::State", L"Current state: " + std::to_wstring(state->GetState(L"ModernEditWithNppExplorerCommandHandler"))); 29 | 30 | return ECS_ENABLED; 31 | } -------------------------------------------------------------------------------- /ModernEditWithNppExplorerCommandHandler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "BaseNppExplorerCommandHandler.h" 3 | 4 | using namespace NppShell::Helpers; 5 | 6 | namespace NppShell::CommandHandlers 7 | { 8 | class __declspec(uuid("E6950302-61F0-4FEB-97DB-855E30D4A991")) ModernEditWithNppExplorerCommandHandler : public BaseNppExplorerCommandHandler 9 | { 10 | public: 11 | ModernEditWithNppExplorerCommandHandler(); 12 | ~ModernEditWithNppExplorerCommandHandler(); 13 | 14 | const EXPCMDSTATE State(IShellItemArray* psiItemArray); 15 | }; 16 | } -------------------------------------------------------------------------------- /NppShell.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notepad-plus-plus/nppShell/98fa2ce51b23c017d632d5b469749179988d9ef8/NppShell.rc -------------------------------------------------------------------------------- /NppShell.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33414.496 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NppShell", "NppShell.vcxproj", "{E7539F55-2932-47D0-82B8-46ED5AFCA1C0}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packaging", "Packaging", "{B9E2DBFF-8940-482F-9D07-BA9C4EAE7620}" 9 | ProjectSection(SolutionItems) = preProject 10 | Packaging\AppxManifest.xml = Packaging\AppxManifest.xml 11 | Packaging\Square150x150Logo.png = Packaging\Square150x150Logo.png 12 | Packaging\Square44x44Logo.png = Packaging\Square44x44Logo.png 13 | Packaging\StoreLogo.png = Packaging\StoreLogo.png 14 | EndProjectSection 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|ARM64 = Debug|ARM64 19 | Debug|Win32 = Debug|Win32 20 | Debug|x64 = Debug|x64 21 | Release|ARM64 = Release|ARM64 22 | Release|Win32 = Release|Win32 23 | Release|x64 = Release|x64 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|ARM64.ActiveCfg = Debug|ARM64 27 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|ARM64.Build.0 = Debug|ARM64 28 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|Win32.ActiveCfg = Debug|Win32 29 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|Win32.Build.0 = Debug|Win32 30 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|x64.ActiveCfg = Debug|x64 31 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Debug|x64.Build.0 = Debug|x64 32 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|ARM64.ActiveCfg = Release|ARM64 33 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|ARM64.Build.0 = Release|ARM64 34 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|Win32.ActiveCfg = Release|Win32 35 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|Win32.Build.0 = Release|Win32 36 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|x64.ActiveCfg = Release|x64 37 | {E7539F55-2932-47D0-82B8-46ED5AFCA1C0}.Release|x64.Build.0 = Release|x64 38 | EndGlobalSection 39 | GlobalSection(SolutionProperties) = preSolution 40 | HideSolutionNode = FALSE 41 | EndGlobalSection 42 | GlobalSection(ExtensibilityGlobals) = postSolution 43 | SolutionGuid = {EAA0AA08-253D-435A-929E-9214D1E358CB} 44 | EndGlobalSection 45 | EndGlobal 46 | -------------------------------------------------------------------------------- /NppShell.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Debug 7 | ARM64 8 | 9 | 10 | Debug 11 | Win32 12 | 13 | 14 | Debug 15 | x64 16 | 17 | 18 | Release 19 | ARM64 20 | 21 | 22 | Release 23 | Win32 24 | 25 | 26 | Release 27 | x64 28 | 29 | 30 | 31 | 16.0 32 | Win32Proj 33 | {e7539f55-2932-47d0-82b8-46ed5afca1c0} 34 | NppShell 35 | 10.0 36 | 37 | 38 | 39 | DynamicLibrary 40 | true 41 | v143 42 | Unicode 43 | 44 | 45 | DynamicLibrary 46 | true 47 | v143 48 | Unicode 49 | 50 | 51 | DynamicLibrary 52 | true 53 | v143 54 | Unicode 55 | 56 | 57 | DynamicLibrary 58 | false 59 | v143 60 | true 61 | Unicode 62 | 63 | 64 | DynamicLibrary 65 | false 66 | v143 67 | true 68 | Unicode 69 | 70 | 71 | DynamicLibrary 72 | false 73 | v143 74 | true 75 | Unicode 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 | $(ProjectName).x64 103 | 104 | 105 | $(ProjectName).x64 106 | 107 | 108 | $(ProjectName).arm64 109 | 110 | 111 | $(ProjectName).arm64 112 | 113 | 114 | $(ProjectName).x86 115 | 116 | 117 | $(ProjectName).x86 118 | 119 | 120 | 121 | Level4 122 | true 123 | _DEBUG;WIN64;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 124 | true 125 | Use 126 | pch.h 127 | stdcpp20 128 | MultiThreadedDebug 129 | true 130 | true 131 | 132 | 133 | Windows 134 | true 135 | false 136 | source.def 137 | 138 | 139 | makeappx pack /d .\Packaging /p $(OutDir)NppShell.msix /nv /o 140 | 141 | 142 | 143 | 144 | Level4 145 | true 146 | _DEBUG;WIN32;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 147 | true 148 | Use 149 | pch.h 150 | stdcpp20 151 | MultiThreadedDebug 152 | true 153 | true 154 | 155 | 156 | Windows 157 | true 158 | false 159 | source.def 160 | 161 | 162 | 163 | 164 | Level4 165 | true 166 | _DEBUG;WIN64;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 167 | true 168 | Use 169 | pch.h 170 | stdcpp20 171 | MultiThreadedDebug 172 | true 173 | true 174 | 175 | 176 | Windows 177 | true 178 | false 179 | source.def 180 | 181 | 182 | makeappx pack /d .\Packaging /p $(OutDir)NppShell.msix /nv /o 183 | 184 | 185 | 186 | 187 | Level4 188 | true 189 | true 190 | true 191 | NDEBUG;WIN64;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 192 | true 193 | Use 194 | pch.h 195 | stdcpp20 196 | MultiThreaded 197 | true 198 | true 199 | 200 | 201 | Windows 202 | true 203 | true 204 | true 205 | false 206 | source.def 207 | 208 | 209 | makeappx pack /d .\Packaging /p $(OutDir)NppShell.msix /nv /o 210 | 211 | 212 | 213 | 214 | Level4 215 | true 216 | true 217 | true 218 | NDEBUG;WIN32;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 219 | true 220 | Use 221 | pch.h 222 | stdcpp20 223 | MultiThreaded 224 | true 225 | true 226 | 227 | 228 | Windows 229 | true 230 | true 231 | true 232 | false 233 | source.def 234 | 235 | 236 | 237 | 238 | Level4 239 | true 240 | true 241 | true 242 | NDEBUG;WIN64;NPPSHELL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 243 | true 244 | Use 245 | pch.h 246 | stdcpp20 247 | MultiThreaded 248 | true 249 | $(OutDir)$(TargetName).arm64$(TargetExt) 250 | true 251 | 252 | 253 | Windows 254 | true 255 | true 256 | true 257 | false 258 | source.def 259 | 260 | 261 | makeappx pack /d .\Packaging /p $(OutDir)NppShell.msix /nv /o 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 | Create 294 | Create 295 | Create 296 | Create 297 | Create 298 | Create 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 320 | 321 | 322 | 323 | 324 | 325 | -------------------------------------------------------------------------------- /NppShell.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {ff31b0d8-bf03-4a28-945d-cfae6eb365fa} 6 | 7 | 8 | {ca898efe-24d8-4317-99c9-769e8e80c3aa} 9 | 10 | 11 | {a0f353df-9c6f-4612-a2d1-98aa7a6d6893} 12 | 13 | 14 | {9c186a78-bd74-4ac7-b560-e61aeb6d2350} 15 | 16 | 17 | {7a045eaf-b500-484e-998a-394c98da10f1} 18 | 19 | 20 | {fc167318-0574-47ba-aa80-a48008ef4b8c} 21 | 22 | 23 | {2de5b87c-2f6d-4a04-bd61-1e1be9a91fdf} 24 | 25 | 26 | {31c51ab1-0502-40df-b93e-2932b487656e} 27 | 28 | 29 | 30 | 31 | Installer 32 | 33 | 34 | 35 | 36 | Factories 37 | 38 | 39 | Helpers 40 | 41 | 42 | Helpers 43 | 44 | 45 | CommandHandlers\Base 46 | 47 | 48 | CommandHandlers\Base 49 | 50 | 51 | CommandHandlers\Implementation 52 | 53 | 54 | CommandHandlers\Implementation 55 | 56 | 57 | Registry 58 | 59 | 60 | Helpers 61 | 62 | 63 | Helpers 64 | 65 | 66 | Resources 67 | 68 | 69 | Helpers 70 | 71 | 72 | Helpers 73 | 74 | 75 | 76 | 77 | Installer 78 | 79 | 80 | 81 | 82 | Helpers 83 | 84 | 85 | Helpers 86 | 87 | 88 | Helpers 89 | 90 | 91 | CommandHandlers\Base 92 | 93 | 94 | CommandHandlers\Base 95 | 96 | 97 | CommandHandlers\Implementation 98 | 99 | 100 | CommandHandlers\Implementation 101 | 102 | 103 | Registry 104 | 105 | 106 | Helpers 107 | 108 | 109 | Helpers 110 | 111 | 112 | Helpers 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | Resources 122 | 123 | 124 | -------------------------------------------------------------------------------- /Packaging/AppxManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | Notepad++ 17 | Notepad++ 18 | StoreLogo.png 19 | true 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 | -------------------------------------------------------------------------------- /Packaging/Square150x150Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notepad-plus-plus/nppShell/98fa2ce51b23c017d632d5b469749179988d9ef8/Packaging/Square150x150Logo.png -------------------------------------------------------------------------------- /Packaging/Square44x44Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notepad-plus-plus/nppShell/98fa2ce51b23c017d632d5b469749179988d9ef8/Packaging/Square44x44Logo.png -------------------------------------------------------------------------------- /Packaging/StoreLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notepad-plus-plus/nppShell/98fa2ce51b23c017d632d5b469749179988d9ef8/Packaging/StoreLogo.png -------------------------------------------------------------------------------- /PathHelper.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "PathHelper.h" 3 | 4 | using namespace NppShell::Helpers; 5 | using namespace std::filesystem; 6 | 7 | extern HMODULE g_module; 8 | 9 | const path GetModulePath() 10 | { 11 | wchar_t pathBuffer[MAX_PATH] = { 0 }; 12 | GetModuleFileNameW(g_module, pathBuffer, MAX_PATH); 13 | return path(pathBuffer); 14 | } 15 | 16 | const wstring NppShell::Helpers::GetApplicationPath() 17 | { 18 | path modulePath = GetModulePath(); 19 | return modulePath.parent_path().parent_path().wstring(); 20 | } 21 | 22 | const wstring NppShell::Helpers::GetContextMenuPath() 23 | { 24 | path modulePath = GetModulePath(); 25 | return modulePath.parent_path().wstring(); 26 | } 27 | 28 | const wstring NppShell::Helpers::GetContextMenuFullName() 29 | { 30 | path modulePath = GetModulePath(); 31 | return modulePath.wstring(); 32 | } 33 | 34 | const wstring NppShell::Helpers::GetExecutingModuleName() 35 | { 36 | wchar_t pathBuffer[FILENAME_MAX] = { 0 }; 37 | GetModuleFileNameW(NULL, pathBuffer, FILENAME_MAX); 38 | PathStripPathW(pathBuffer); 39 | 40 | wstring moduleName(pathBuffer); 41 | transform(moduleName.begin(), moduleName.end(), moduleName.begin(), towlower); 42 | 43 | return moduleName; 44 | } -------------------------------------------------------------------------------- /PathHelper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | #include 5 | 6 | namespace NppShell::Helpers 7 | { 8 | const wstring GetApplicationPath(); 9 | const wstring GetContextMenuPath(); 10 | const wstring GetContextMenuFullName(); 11 | const wstring GetExecutingModuleName(); 12 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Windows 11 Modern UI Context Menu integration 2 | 3 | The purpose of this project is to allow Notepad++ to integrate into the new Windows 11 right-click context menu. 4 | Doing this requires two new things. 5 | 6 | * A dll library with some COM objects that the shell can communicate with. 7 | * A Sparse Package containing the metadata for the COM server. 8 | 9 | To build this, the following steps needs to be taken: 10 | 11 | 1. Build a Release dll file three times (Win32, x64 and ARM64) resulting in three dll files (NppShell.x86.dll, NppShell.x64.dll and NppShell.arm64.dll) 12 | 2. Generate a Sparse Package (NppShell.msix) 13 | 3. Sign both of these with signtool.exe 14 | 4. Make sure they are included in the installer, so they are deployed next to the notepad++.exe program. 15 | 5. The installer should, upon installation, install the package. 16 | 6. The installer should, upon uninstallation, uninstall the package. 17 | 18 | ## Prerequisites 19 | 20 | To be able to build this project, the following is needed: 21 | 22 | * [Visual Studio 2022](https://visualstudio.microsoft.com/vs) 23 | * [Windows 11 SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk) 24 | 25 | ## Build a Release dll file (NppShell.dll) 26 | Just open the NppShell.sln Visual Studio solution, select Release as the build type, and do a Rebuild of the solution. 27 | 28 | ## Generate a Sparse Package (NppShell.msix) 29 | To generate a Sparse Package, you need to have the makeappx.exe tool in your PATH, the easiest way to do this is to run the `Developer Command Prompt for VS 2022` command prompt, since it sets up the path. 30 | Once inside the NppShell folder, run the following command to generate the Sparse Package: 31 | ``` 32 | makeappx pack /d .\Packaging /p .\NppShell.msix /nv 33 | ``` 34 | This takes the content of the Packaging directory, and packages them up into the msix file. 35 | 36 | ## Sign both of these with signtool.exe 37 | Now we have both the `NppShell.dll` and `NppShell.msix` files, we need to sign them with a valid certificate. 38 | To do this, once again run the `Developer Command Prompt for VS 2022` command prompt and change to the NppShell folder. 39 | The following command expects the following: 40 | * The pfx certificate is called MyCert.pfx 41 | * The password for the pfx certificate is: `Test1234` 42 | 43 | Make the needed changes to match the real certificate. 44 | ``` 45 | SignTool.exe sign /fd SHA256 /tr http://timestamp.digicert.com /td sha256 /a /f .\MyCert.pfx /p Test1234 /d "Notepad++" /du https://notepad-plus-plus.org/ NppShell.msix 46 | SignTool.exe sign /fd SHA256 /tr http://timestamp.digicert.com /td sha256 /a /f .\MyCert.pfx /p Test1234 /d "Notepad++" /du https://notepad-plus-plus.org/ (ARCH)\Release\NppShell.dll 47 | ``` 48 | Now both files has been signed, and can be used. 49 | 50 | ## Make sure they are included in the installer, so they are deployed next to the notepad++.exe program. 51 | The installer needs to deploy the two files into the same directory as notepad++.exe . 52 | They need to be there, since the DLL is looking for notepad++.exe in the same directory as it is located itself. 53 | 54 | ## The installer should, upon installation, install the package. 55 | When the installer is running, after all the files has been copied into the program files directory, the follow command should be be run to run the register function to register the package: 56 | ``` 57 | regsvr32.exe /s .\contextmenu\NppShell.dll 58 | ``` 59 | 60 | Remember to wait for the regsvr32 process to exit before continuing. 61 | 62 | ## The installer should, upon uninstallation, uninstall the package. 63 | When the uninstaller is running, it should run this command to unregister the package: 64 | ``` 65 | regsvr32.exe /s /u .\contextmenu\NppShell.dll 66 | ``` 67 | 68 | Here we need to wait for regsvr32 to finish, since if it isn't finished, the dll file will be locked by explorer. -------------------------------------------------------------------------------- /RegistryKey.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "RegistryKey.h" 3 | #include "LoggingHelper.h" 4 | 5 | using namespace NppShell::Registry; 6 | using namespace NppShell::Helpers; 7 | 8 | extern LoggingHelper g_loggingHelper; 9 | 10 | RegistryKey::RegistryKey(HKEY hKey, const wstring& subKey, REGSAM access, bool createIfMissing) 11 | : m_hKey(nullptr), m_regsam(access), m_originalHKey(hKey), m_originalSubKey(subKey) 12 | { 13 | if (RegOpenKeyExW(hKey, subKey.data(), 0, access, &m_hKey) == ERROR_SUCCESS) 14 | { 15 | g_loggingHelper.LogMessage(L"RegistryKey::ctor", L"Opened sub key: " + subKey); 16 | return; 17 | } 18 | 19 | if (!createIfMissing) 20 | { 21 | return; 22 | } 23 | 24 | DWORD disposition = 0; 25 | 26 | if (RegCreateKeyExW(hKey, subKey.data(), 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &m_hKey, &disposition) != ERROR_SUCCESS) 27 | { 28 | g_loggingHelper.LogMessage(L"RegistryKey::ctor", L"Failed to create sub key: " + subKey); 29 | throw runtime_error("Failed to create registry key."); 30 | } 31 | else 32 | { 33 | g_loggingHelper.LogMessage(L"RegistryKey::ctor", L"Created sub key: " + subKey); 34 | } 35 | } 36 | 37 | RegistryKey::~RegistryKey() 38 | { 39 | if (m_hKey != nullptr) 40 | { 41 | RegCloseKey(m_hKey); 42 | } 43 | } 44 | 45 | bool RegistryKey::KeyExists(HKEY hKey, const wstring& subKey) 46 | { 47 | HKEY result; 48 | LONG status = RegOpenKeyExW(hKey, subKey.data(), 0, KEY_READ, &result); 49 | 50 | if (status == ERROR_SUCCESS) 51 | { 52 | RegCloseKey(result); 53 | 54 | return true; 55 | } 56 | else if (status == ERROR_FILE_NOT_FOUND) 57 | { 58 | return false; 59 | } 60 | else 61 | { 62 | throw runtime_error("Error opening registry key."); 63 | } 64 | } 65 | 66 | bool RegistryKey::ValueExists(const wstring& valueName) const 67 | { 68 | DWORD type; 69 | DWORD size = 0; 70 | 71 | LONG status = RegQueryValueExW(m_hKey, valueName.empty() ? NULL : valueName.data(), nullptr, &type, nullptr, &size); 72 | 73 | if (status == ERROR_SUCCESS) 74 | { 75 | return true; 76 | } 77 | else if (status == ERROR_FILE_NOT_FOUND) 78 | { 79 | return false; 80 | } 81 | else 82 | { 83 | throw runtime_error("Error querying registry value."); 84 | } 85 | } 86 | 87 | RegistryKey RegistryKey::GetSubKey(const wstring& subKey, bool createIfMissing) const 88 | { 89 | if (m_hKey == nullptr) 90 | { 91 | throw runtime_error("Registry key is not open."); 92 | } 93 | 94 | HKEY hNewKey; 95 | if (RegOpenKeyExW(m_hKey, NULL, 0, m_regsam, &hNewKey) != ERROR_SUCCESS) 96 | { 97 | throw runtime_error("Failed to open registry key."); 98 | } 99 | 100 | return RegistryKey(hNewKey, subKey, m_regsam, createIfMissing); 101 | } 102 | 103 | DWORD RegistryKey::GetDwordValue(const wstring& valueName) 104 | { 105 | if (m_hKey == nullptr) 106 | { 107 | throw runtime_error("Registry key is not open."); 108 | } 109 | 110 | DWORD value = 0; 111 | DWORD dataSize = sizeof(DWORD); 112 | 113 | if (RegGetValueW(m_hKey, nullptr, valueName.empty() ? NULL : valueName.data(), RRF_RT_REG_DWORD, nullptr, &value, &dataSize) != ERROR_SUCCESS) 114 | { 115 | g_loggingHelper.LogMessage(L"RegistryKey::GetDwordValue", L"Failed to get DWORD value: " + valueName); 116 | throw runtime_error("Failed to get registry value."); 117 | } 118 | 119 | return value; 120 | } 121 | 122 | wstring RegistryKey::GetStringValue(const wstring& valueName) 123 | { 124 | if (m_hKey == nullptr) 125 | { 126 | throw runtime_error("Registry key is not open."); 127 | } 128 | 129 | DWORD dataSize = 0; 130 | 131 | if (RegGetValueW(m_hKey, nullptr, valueName.empty() ? NULL : valueName.data(), RRF_RT_REG_SZ, nullptr, nullptr, &dataSize) != ERROR_SUCCESS) 132 | { 133 | g_loggingHelper.LogMessage(L"RegistryKey::GetStringValue", L"Failed to get REG_SZ value: " + valueName); 134 | throw runtime_error("Failed to get registry value size."); 135 | } 136 | 137 | wstring value(dataSize / sizeof(wchar_t), L'\0'); 138 | 139 | if (RegGetValueW(m_hKey, nullptr, valueName.empty() ? NULL : valueName.data(), RRF_RT_REG_SZ, nullptr, bit_cast(value.data()), &dataSize) != ERROR_SUCCESS) 140 | { 141 | g_loggingHelper.LogMessage(L"RegistryKey::GetStringValue", L"Failed to get REG_SZ value: " + valueName); 142 | throw runtime_error("Failed to get registry value."); 143 | } 144 | 145 | return value; 146 | } 147 | 148 | void RegistryKey::SetDwordValue(const wstring& valueName, DWORD value) 149 | { 150 | if (m_hKey == nullptr) 151 | { 152 | throw runtime_error("Registry key is not open."); 153 | } 154 | 155 | if (RegSetValueExW(m_hKey, valueName.empty() ? NULL : valueName.data(), 0, REG_DWORD, bit_cast(&value), sizeof(DWORD)) != ERROR_SUCCESS) 156 | { 157 | g_loggingHelper.LogMessage(L"RegistryKey::SetDwordValue", L"Failed to set DWORD value: " + valueName); 158 | throw runtime_error("Failed to set registry value."); 159 | } 160 | 161 | wstring valueNameLog = valueName.empty() ? L"(default)" : valueName.data(); 162 | g_loggingHelper.LogMessage(L"RegistryKey::SetDwordValue", L"Setting DWORD name: " + valueNameLog + L" to: " + to_wstring(value)); 163 | } 164 | 165 | void RegistryKey::SetStringValue(const wstring& valueName, const wstring& value) 166 | { 167 | if (m_hKey == nullptr) 168 | { 169 | throw runtime_error("Registry key is not open."); 170 | } 171 | 172 | if (RegSetValueExW(m_hKey, valueName.empty() ? NULL : valueName.data(), 0, REG_SZ, bit_cast(value.data()), static_cast((value.length() + 1) * sizeof(wchar_t))) != ERROR_SUCCESS) 173 | { 174 | g_loggingHelper.LogMessage(L"RegistryKey::SetStringValue", L"Failed to set REG_SZ value: " + valueName); 175 | throw runtime_error("Failed to set registry value."); 176 | } 177 | 178 | wstring valueNameLog = valueName.empty() ? L"(default)" : valueName.data(); 179 | g_loggingHelper.LogMessage(L"RegistryKey::SetStringValue", L"Setting REG_SZ name: " + valueNameLog + L" to: \"" + value + L"\""); 180 | } 181 | 182 | void RegistryKey::DeleteKey() 183 | { 184 | if (m_hKey == nullptr) 185 | { 186 | throw runtime_error("Registry key is not open."); 187 | } 188 | 189 | if (RegDeleteTreeW(m_originalHKey, m_originalSubKey.data()) != ERROR_SUCCESS) 190 | { 191 | g_loggingHelper.LogMessage(L"RegistryKey::DeleteKey", L"Failed to delete subkey: " + m_originalSubKey); 192 | throw runtime_error("Failed to delete registry key."); 193 | } 194 | 195 | g_loggingHelper.LogMessage(L"RegistryKey::DeleteKey", L"Deleted subkey: " + m_originalSubKey); 196 | 197 | m_hKey = nullptr; 198 | m_originalHKey = nullptr; 199 | } -------------------------------------------------------------------------------- /RegistryKey.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace NppShell::Registry 4 | { 5 | class RegistryKey 6 | { 7 | public: 8 | RegistryKey(HKEY hKey, const wstring& subKey = L"", REGSAM access = KEY_READ, bool createIfMissing = false); 9 | ~RegistryKey(); 10 | 11 | static bool KeyExists(HKEY hKey, const wstring& subKey); 12 | bool ValueExists(const wstring& valueName) const; 13 | 14 | RegistryKey GetSubKey(const wstring& subKey, bool createIfMissing = false) const; 15 | 16 | DWORD GetDwordValue(const wstring& valueName); 17 | wstring GetStringValue(const wstring& valueName); 18 | 19 | void SetDwordValue(const wstring& valueName, DWORD value); 20 | void SetStringValue(const wstring& valueName, const wstring& value); 21 | 22 | void DeleteKey(); 23 | 24 | private: 25 | HKEY m_hKey; 26 | REGSAM m_regsam; 27 | HKEY m_originalHKey; 28 | wstring m_originalSubKey; 29 | }; 30 | } -------------------------------------------------------------------------------- /SharedCounter.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "SharedCounter.h" 3 | #include "LoggingHelper.h" 4 | 5 | using namespace NppShell::Helpers; 6 | 7 | extern LoggingHelper g_loggingHelper; 8 | 9 | SharedCounter::SharedCounter() 10 | { 11 | // Create or open the shared memory mapped file 12 | hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), L"Local\\BaseNppExplorerCommandHandlerSharedMemory"); 13 | if (hFileMapping == NULL) 14 | { 15 | g_loggingHelper.LogMessage(L"SharedCounter::ctor", L"Failed to create or open shared memory mapped file"); 16 | return; 17 | } 18 | 19 | // Create a mutex to synchronize access to the shared memory 20 | hMutex = CreateMutex(NULL, FALSE, L"Local\\BaseNppExplorerCommandHandlerSharedMutex"); 21 | if (hMutex == NULL) 22 | { 23 | g_loggingHelper.LogMessage(L"SharedCounter::ctor", L"Failed to create mutex"); 24 | CloseHandle(hFileMapping); 25 | return; 26 | } 27 | 28 | // Map the shared memory into the current process's address space 29 | pCounter = (int*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(int)); 30 | if (pCounter == NULL) 31 | { 32 | g_loggingHelper.LogMessage(L"SharedCounter::ctor", L"Failed to map shared memory"); 33 | CloseHandle(hMutex); 34 | CloseHandle(hFileMapping); 35 | return; 36 | } 37 | 38 | // Increment the shared counter 39 | WaitForSingleObject(hMutex, INFINITE); 40 | *pCounter += 1; 41 | localValue = *pCounter; 42 | ReleaseMutex(hMutex); 43 | } 44 | 45 | SharedCounter::~SharedCounter() 46 | { 47 | // Decrement the shared counter 48 | WaitForSingleObject(hMutex, INFINITE); 49 | *pCounter -= 1; 50 | ReleaseMutex(hMutex); 51 | 52 | // Unmap the shared memory from the current process's address space 53 | UnmapViewOfFile(pCounter); 54 | 55 | // Close the mutex and the shared memory mapped file 56 | CloseHandle(hMutex); 57 | CloseHandle(hFileMapping); 58 | } 59 | 60 | int SharedCounter::GetValue() const 61 | { 62 | return localValue; 63 | } -------------------------------------------------------------------------------- /SharedCounter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace NppShell::Helpers 4 | { 5 | class SharedCounter 6 | { 7 | public: 8 | SharedCounter(); 9 | ~SharedCounter(); 10 | 11 | int GetValue() const; 12 | 13 | private: 14 | HANDLE hFileMapping; 15 | HANDLE hMutex; 16 | int* pCounter; 17 | int localValue; 18 | }; 19 | } -------------------------------------------------------------------------------- /SharedState.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "SharedState.h" 3 | #include "LoggingHelper.h" 4 | 5 | using namespace NppShell::Helpers; 6 | 7 | extern LoggingHelper g_loggingHelper; 8 | 9 | SharedState::SharedState() 10 | { 11 | // Create or open the shared memory mapped file 12 | hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), L"Local\\BaseNppExplorerCommandHandlerSharedStateMemory"); 13 | if (hFileMapping == NULL) 14 | { 15 | g_loggingHelper.LogMessage(L"SharedState::ctor", L"Failed to create or open shared memory mapped file"); 16 | return; 17 | } 18 | 19 | // Create a mutex to synchronize access to the shared memory 20 | hMutex = CreateMutex(NULL, FALSE, L"Local\\BaseNppExplorerCommandHandlerSharedStateMutex"); 21 | if (hMutex == NULL) 22 | { 23 | g_loggingHelper.LogMessage(L"SharedState::ctor", L"Failed to create mutex"); 24 | CloseHandle(hFileMapping); 25 | return; 26 | } 27 | 28 | // Map the shared memory into the current process's address space 29 | pState = (CounterState*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CounterState)); 30 | if (pState == NULL) 31 | { 32 | MessageBox(NULL, L"Failed to map shared memory", L"SharedState", MB_OK | MB_ICONERROR); 33 | CloseHandle(hMutex); 34 | CloseHandle(hFileMapping); 35 | return; 36 | } 37 | } 38 | 39 | SharedState::~SharedState() 40 | { 41 | // Unmap the shared memory from the current process's address space 42 | UnmapViewOfFile(pState); 43 | 44 | // Close the mutex and the shared memory mapped file 45 | CloseHandle(hMutex); 46 | CloseHandle(hFileMapping); 47 | } 48 | 49 | CounterState SharedState::GetState(const wstring caller) const 50 | { 51 | WaitForSingleObject(hMutex, INFINITE); 52 | CounterState value = *pState; 53 | g_loggingHelper.LogMessage(L"SharedState::GetState", L"Get shared state by caller: " + caller); 54 | ReleaseMutex(hMutex); 55 | 56 | return value; 57 | } 58 | 59 | void SharedState::SetState(const wstring caller, const CounterState state) 60 | { 61 | WaitForSingleObject(hMutex, INFINITE); 62 | *pState = state; 63 | g_loggingHelper.LogMessage(L"SharedState::SetState", L"Set shared state to: " + to_wstring(state) + L" by caller: " + caller); 64 | ReleaseMutex(hMutex); 65 | } -------------------------------------------------------------------------------- /SharedState.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace NppShell::Helpers 4 | { 5 | enum CounterState 6 | { 7 | NotSet, 8 | Set 9 | }; 10 | 11 | class SharedState 12 | { 13 | public: 14 | SharedState(); 15 | ~SharedState(); 16 | 17 | CounterState GetState(const wstring caller) const; 18 | void SetState(const wstring caller, const CounterState state); 19 | 20 | private: 21 | HANDLE hFileMapping = 0; 22 | HANDLE hMutex = 0; 23 | CounterState* pState = 0; 24 | }; 25 | } -------------------------------------------------------------------------------- /SimpleFactory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | namespace NppShell::Factories 5 | { 6 | template 7 | struct SimpleFactory : winrt::implements, IClassFactory> 8 | { 9 | IFACEMETHODIMP CreateInstance(IUnknown* pUnkOuter, REFIID riid, void** ppvObject) override try 10 | { 11 | *ppvObject = nullptr; 12 | 13 | if (!pUnkOuter) 14 | { 15 | return winrt::make().as(riid, ppvObject); 16 | } 17 | else 18 | { 19 | return CLASS_E_NOAGGREGATION; 20 | } 21 | } 22 | catch (...) 23 | { 24 | return winrt::to_hresult(); 25 | } 26 | 27 | IFACEMETHODIMP LockServer(BOOL) noexcept override 28 | { 29 | return S_OK; 30 | } 31 | }; 32 | } -------------------------------------------------------------------------------- /ThreadUILanguageChanger.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "ThreadUILanguageChanger.h" 3 | #include "LoggingHelper.h" 4 | 5 | using namespace NppShell::Helpers; 6 | 7 | extern LoggingHelper g_loggingHelper; 8 | 9 | ThreadUILanguageChanger::ThreadUILanguageChanger(const wstring& languageTag) 10 | { 11 | // Save the original thread UI language setting 12 | m_originalLanguageTag = GetThreadLanguage(); 13 | 14 | // Set the new thread UI language setting 15 | SetThreadLanguage(languageTag); 16 | 17 | g_loggingHelper.LogMessage(L"ThreadUILanguageChanger::ctor", L"Original language: " + m_originalLanguageTag); 18 | g_loggingHelper.LogMessage(L"ThreadUILanguageChanger::ctor", L"New language: " + languageTag); 19 | } 20 | 21 | ThreadUILanguageChanger::~ThreadUILanguageChanger() 22 | { 23 | // Restore the original thread UI language setting 24 | SetThreadLanguage(m_originalLanguageTag); 25 | 26 | g_loggingHelper.LogMessage(L"ThreadUILanguageChanger::~tor", L"Original language: " + m_originalLanguageTag); 27 | } 28 | 29 | wstring ThreadUILanguageChanger::GetThreadLanguage() 30 | { 31 | DWORD numLanguages = 0; 32 | DWORD bufferSize = 0; 33 | GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, &numLanguages, nullptr, &bufferSize); 34 | 35 | wstring language(bufferSize, '\0'); 36 | GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, &numLanguages, language.data(), &bufferSize); 37 | 38 | return language; 39 | } 40 | 41 | void ThreadUILanguageChanger::SetThreadLanguage(const wstring& languageTag) 42 | { 43 | // Set the new thread UI language setting 44 | SetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, languageTag.c_str(), nullptr); 45 | } -------------------------------------------------------------------------------- /ThreadUILanguageChanger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace NppShell::Helpers 4 | { 5 | class ThreadUILanguageChanger 6 | { 7 | public: 8 | ThreadUILanguageChanger(const wstring& languageTag); 9 | ~ThreadUILanguageChanger(); 10 | 11 | private: 12 | wstring GetThreadLanguage(); 13 | void SetThreadLanguage(const wstring& languageTag); 14 | 15 | wstring m_originalLanguageTag; 16 | }; 17 | } -------------------------------------------------------------------------------- /dllmain.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | 3 | #include "Installer.h" 4 | #include "SimpleFactory.h" 5 | #include "ClassicEditWithNppExplorerCommandHandler.h" 6 | #include "ModernEditWithNppExplorerCommandHandler.h" 7 | #include "LoggingHelper.h" 8 | 9 | using namespace NppShell::CommandHandlers; 10 | using namespace NppShell::Factories; 11 | using namespace NppShell::Helpers; 12 | 13 | HMODULE g_module; 14 | LoggingHelper g_loggingHelper; 15 | 16 | BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) 17 | { 18 | UNREFERENCED_PARAMETER(lpReserved); 19 | 20 | switch (ul_reason_for_call) 21 | { 22 | case DLL_PROCESS_ATTACH: 23 | g_module = hModule; 24 | NppShell::Installer::EnsureRegistrationOnCurrentUser(); 25 | break; 26 | case DLL_THREAD_ATTACH: 27 | case DLL_THREAD_DETACH: 28 | case DLL_PROCESS_DETACH: 29 | break; 30 | } 31 | 32 | return TRUE; 33 | } 34 | 35 | STDAPI DllRegisterServer() 36 | { 37 | return NppShell::Installer::Install(); 38 | } 39 | 40 | STDAPI DllUnregisterServer() 41 | { 42 | return NppShell::Installer::Uninstall(); 43 | } 44 | 45 | __control_entrypoint(DllExport) 46 | STDAPI DllCanUnloadNow(void) 47 | { 48 | if (winrt::get_module_lock()) 49 | { 50 | return S_FALSE; 51 | } 52 | else 53 | { 54 | return S_OK; 55 | } 56 | } 57 | 58 | _Use_decl_annotations_ STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) try 59 | { 60 | *ppv = nullptr; 61 | 62 | if (rclsid == __uuidof(ClassicEditWithNppExplorerCommandHandler)) 63 | { 64 | return winrt::make>().as(riid, ppv); 65 | } 66 | else if (rclsid == __uuidof(ModernEditWithNppExplorerCommandHandler)) 67 | { 68 | return winrt::make>().as(riid, ppv); 69 | } 70 | else 71 | { 72 | return CLASS_E_CLASSNOTAVAILABLE; 73 | } 74 | } 75 | catch (...) 76 | { 77 | return winrt::to_hresult(); 78 | } -------------------------------------------------------------------------------- /framework.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning(disable:4324) 3 | 4 | #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers 5 | // Windows Header Files 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | // WinRT Header Files 15 | #include "winrt/base.h" 16 | #include "winrt/Windows.ApplicationModel.h" 17 | #include "winrt/Windows.Foundation.Collections.h" 18 | #include "winrt/Windows.Management.Deployment.h" 19 | 20 | // Windows Implementation Library Header Files 21 | #include "wil\winrt.h" 22 | 23 | // Link libraries 24 | #pragma comment(lib, "shlwapi.lib") 25 | #pragma comment(lib, "runtimeobject.lib") -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to the pre-compiled header 2 | 3 | #include "pch.h" 4 | 5 | // When you are using pre-compiled headers, this source file is necessary for compilation to succeed. 6 | -------------------------------------------------------------------------------- /pch.h: -------------------------------------------------------------------------------- 1 | // pch.h: This is a precompiled header file. 2 | // Files listed below are compiled only once, improving build performance for future builds. 3 | // This also affects IntelliSense performance, including code completion and many code browsing features. 4 | // However, files listed here are ALL re-compiled if any one of them is updated between builds. 5 | // Do not add files here that you will be updating frequently as this negates the performance advantage. 6 | 7 | #ifndef PCH_H 8 | #define PCH_H 9 | 10 | // add headers that you want to pre-compile here 11 | #include "framework.h" 12 | 13 | using namespace std; 14 | 15 | #endif //PCH_H 16 | -------------------------------------------------------------------------------- /resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by NppShell.rc 4 | // 5 | #define IDS_EDIT_WITH_NOTEPADPLUSPLUS 101 6 | 7 | #define VERSION_VALUE "1.5" 8 | #define VERSION_DIGITALVALUE 1,5,0,0 9 | 10 | // Next default values for new objects 11 | // 12 | #ifdef APSTUDIO_INVOKED 13 | #ifndef APSTUDIO_READONLY_SYMBOLS 14 | #define _APS_NEXT_RESOURCE_VALUE 102 15 | #define _APS_NEXT_COMMAND_VALUE 40001 16 | #define _APS_NEXT_CONTROL_VALUE 1001 17 | #define _APS_NEXT_SYMED_VALUE 101 18 | #endif 19 | #endif 20 | -------------------------------------------------------------------------------- /source.def: -------------------------------------------------------------------------------- 1 | LIBRARY 2 | EXPORTS 3 | DllMain PRIVATE 4 | DllCanUnloadNow PRIVATE 5 | DllGetClassObject PRIVATE 6 | DllRegisterServer PRIVATE 7 | DllUnregisterServer PRIVATE 8 | CleanupDll PRIVATE --------------------------------------------------------------------------------