[Kbm] Save the remaps to file[part-1] (#2184)

* Added Inital FileWatcher Implementation

* Added logic to read remap from file

* Added remap logic save to file

* Refactor code

* Moved the strings to constant file

* Added logic to handle Win key

* Updated filewatcher logic to avoid duplicate events

* Added comments

* Fix spacing

* Fix spacing

* Update logic to accomodate upstream merge

* Added global property name for os level shortcuts

* Added subkey for inprocess keys

* Remove non required file

* Added Changes required after merge

* Fix spacing in Helper.cpp
This commit is contained in:
udit3333
2020-04-20 08:22:36 -07:00
committed by GitHub
parent cae77ae291
commit 325db535c0
29 changed files with 647 additions and 152 deletions

View File

@@ -2,74 +2,77 @@
#include "Helpers.h"
#include <sstream>
// Function to split a wstring based on a delimiter and return a vector of split strings
std::vector<std::wstring> splitwstring(const std::wstring& input, wchar_t delimiter)
namespace KeyboardManagerHelper
{
std::wstringstream ss(input);
std::wstring item;
std::vector<std::wstring> splittedStrings;
while (std::getline(ss, item, L' '))
// Function to split a wstring based on a delimiter and return a vector of split strings
std::vector<std::wstring> splitwstring(const std::wstring& input, wchar_t delimiter)
{
splittedStrings.push_back(item);
std::wstringstream ss(input);
std::wstring item;
std::vector<std::wstring> splittedStrings;
while (std::getline(ss, item, delimiter))
{
splittedStrings.push_back(item);
}
return splittedStrings;
}
// Function to return the next sibling element for an element under a stack panel
winrt::Windows::Foundation::IInspectable getSiblingElement(winrt::Windows::Foundation::IInspectable const& element)
{
FrameworkElement frameworkElement = element.as<FrameworkElement>();
StackPanel parentElement = frameworkElement.Parent().as<StackPanel>();
uint32_t index;
parentElement.Children().IndexOf(frameworkElement, index);
return parentElement.Children().GetAt(index + 1);
}
// Function to check if the key is a modifier key
bool IsModifierKey(DWORD key)
{
return (GetKeyType(key) != KeyType::Action);
}
return splittedStrings;
}
// Function to return the next sibling element for an element under a stack panel
IInspectable getSiblingElement(IInspectable const& element)
{
FrameworkElement frameworkElement = element.as<FrameworkElement>();
StackPanel parentElement = frameworkElement.Parent().as<StackPanel>();
uint32_t index;
parentElement.Children().IndexOf(frameworkElement, index);
return parentElement.Children().GetAt(index + 1);
}
// Function to check if the key is a modifier key
bool IsModifierKey(DWORD key)
{
return (GetKeyType(key) != KeyType::Action);
}
// Function to get the type of the key
KeyType GetKeyType(DWORD key)
{
switch (key)
// Function to get the type of the key
KeyType GetKeyType(DWORD key)
{
case VK_LWIN:
case VK_RWIN:
return KeyType::Win;
case VK_CONTROL:
case VK_LCONTROL:
case VK_RCONTROL:
return KeyType::Ctrl;
case VK_MENU:
case VK_LMENU:
case VK_RMENU:
return KeyType::Alt;
case VK_SHIFT:
case VK_LSHIFT:
case VK_RSHIFT:
return KeyType::Shift;
default:
return KeyType::Action;
}
}
// Function to return if the key is an extended key which requires the use of the extended key flag
bool isExtendedKey(DWORD key)
{
switch (key)
{
case VK_RCONTROL:
case VK_RMENU:
case VK_NUMLOCK:
case VK_SNAPSHOT:
case VK_CANCEL:
return true;
default:
return false;
switch (key)
{
case VK_LWIN:
case VK_RWIN:
return KeyType::Win;
case VK_CONTROL:
case VK_LCONTROL:
case VK_RCONTROL:
return KeyType::Ctrl;
case VK_MENU:
case VK_LMENU:
case VK_RMENU:
return KeyType::Alt;
case VK_SHIFT:
case VK_LSHIFT:
case VK_RSHIFT:
return KeyType::Shift;
default:
return KeyType::Action;
}
}
// Function to return if the key is an extended key which requires the use of the extended key flag
bool isExtendedKey(DWORD key)
{
switch (key)
{
case VK_RCONTROL:
case VK_RMENU:
case VK_NUMLOCK:
case VK_SNAPSHOT:
case VK_CANCEL:
return true;
default:
return false;
}
}
}

View File

@@ -2,52 +2,58 @@
#include <vector>
#include <winrt/Windows.System.h>
// Type to distinguish between keys
enum class KeyType
namespace KeyboardManagerHelper
{
Win,
Ctrl,
Alt,
Shift,
Action
};
// Function to split a wstring based on a delimiter and return a vector of split strings
std::vector<std::wstring> splitwstring(const std::wstring& input, wchar_t delimiter);
// Function to return the next sibling element for an element under a stack panel
winrt::Windows::Foundation::IInspectable getSiblingElement(winrt::Windows::Foundation::IInspectable const& element);
// Function to convert an unsigned int vector to hstring by concatenating them
template<typename T>
winrt::hstring convertVectorToHstring(const std::vector<T>& input)
{
winrt::hstring output;
for (int i = 0; i < input.size(); i++)
// Type to distinguish between keys
enum class KeyType
{
output = output + winrt::to_hstring((unsigned int)input[i]) + winrt::to_hstring(L" ");
}
return output;
}
Win,
Ctrl,
Alt,
Shift,
Action
};
// Function to split a wstring based on a delimiter and return a vector of split strings
std::vector<std::wstring> splitwstring(const std::wstring& input, wchar_t delimiter);
// Function to return the next sibling element for an element under a stack panel
winrt::Windows::Foundation::IInspectable getSiblingElement(winrt::Windows::Foundation::IInspectable const& element);
// Function to convert a wstring vector to a integer vector
template<typename T>
std::vector<T> convertWStringVectorToIntegerVector(const std::vector<std::wstring>& input)
{
std::vector<T> typeVector;
for (int i = 0; i < input.size(); i++)
// Function to convert an unsigned int vector to hstring by concatenating them
template<typename T>
winrt::hstring convertVectorToHstring(const std::vector<T>& input)
{
typeVector.push_back((T)std::stoi(input[i]));
winrt::hstring output;
for (int i = 0; i < input.size(); i++)
{
output = output + winrt::to_hstring((unsigned int)input[i]) + winrt::to_hstring(L" ");
}
return output;
}
return typeVector;
// Function to convert a wstring vector to a integer vector
template<typename T>
std::vector<T> convertWStringVectorToIntegerVector(const std::vector<std::wstring>& input)
{
std::vector<T> typeVector;
for (int i = 0; i < input.size(); i++)
{
typeVector.push_back((T)std::stoi(input[i]));
}
return typeVector;
}
// Function to return if the key is an extended key which requires the use of the extended key flag
bool isExtendedKey(DWORD key);
// Function to check if the key is a modifier key
bool IsModifierKey(DWORD key);
// Function to get the type of the key
KeyType GetKeyType(DWORD key);
// Function to return if the key is an extended key which requires the use of the extended key flag
bool isExtendedKey(DWORD key);
}
// Function to check if the key is a modifier key
bool IsModifierKey(DWORD key);
// Function to get the type of the key
KeyType GetKeyType(DWORD key);
// Function to return if the key is an extended key which requires the use of the extended key flag
bool isExtendedKey(DWORD key);

View File

@@ -55,8 +55,8 @@
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalIncludeDirectories>..\;..\..\..\common;..\..\..\common\telemetry;..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>$(SolutionDir)src\;$(SolutionDir)src\modules;$(SolutionDir)src\common\Telemetry;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
@@ -74,7 +74,7 @@
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalIncludeDirectories>$(SolutionDir)src\;$(SolutionDir)src\modules;$(SolutionDir)src\common\Telemetry;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>..\;..\..\..\common;..\..\..\common\telemetry;..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
@@ -100,6 +100,7 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="Helpers.h" />
<ClInclude Include="KeyboardManagerConstants.h" />
<ClInclude Include="KeyboardManagerState.h" />
<ClInclude Include="KeyDelay.h" />
<ClInclude Include="LayoutMap.h" />

View File

@@ -59,5 +59,8 @@
<ClInclude Include="KeyDelay.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="KeyboardManagerConstants.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,41 @@
#pragma once
#include <string>
namespace KeyboardManagerConstants
{
// Name of the powertoy module.
inline const std::wstring ModuleName = L"Keyboard Manager";
// Name of the property use to store current active configuration.
inline const std::wstring ActiveConfigurationSettingName = L"activeConfiguration";
// Name of the property use to store single keyremaps.
inline const std::wstring RemapKeysSettingName = L"remapKeys";
// Name of the property use to store single keyremaps array in case of in process approach.
inline const std::wstring InProcessRemapKeysSettingName = L"inProcess";
// Name of the property use to store shortcut remaps.
inline const std::wstring RemapShortcutsSettingName = L"remapShortcuts";
// Name of the property use to store global shortcut remaps array.
inline const std::wstring GlobalRemapShortcutsSettingName = L"global";
// Name of the property use to store original keys.
inline const std::wstring OriginalKeysSettingName = L"originalKeys";
// Name of the property use to store new remap keys.
inline const std::wstring NewRemapKeysSettingName = L"newRemapKeys";
// Name of the default configuration.
inline const std::wstring DefaultConfiguration = L"default";
// Name of the named mutex used for configuration file.
inline const std::wstring ConfigFileMutexName = L"PowerToys.KeyboardManager.ConfigMutex";
// Name of the dummy update file.
inline const std::wstring DummyUpdateFileName = L"settings-updated.json";
// Fake key code to represent VK_WIN.
inline const DWORD VK_WIN_BOTH = 0x104;
}

View File

@@ -5,6 +5,19 @@
KeyboardManagerState::KeyboardManagerState() :
uiState(KeyboardManagerUIState::Deactivated), currentUIWindow(nullptr), currentShortcutUI(nullptr), currentSingleKeyUI(nullptr), detectedRemapKey(NULL)
{
configFile_mutex = CreateMutex(
NULL, // default security descriptor
FALSE, // mutex not owned
KeyboardManagerConstants::ConfigFileMutexName.c_str());
}
// Destructor
KeyboardManagerState::~KeyboardManagerState()
{
if (configFile_mutex)
{
CloseHandle(configFile_mutex);
}
}
// Function to check the if the UI state matches the argument state. For states with activated windows it also checks if the window is in focus.
@@ -344,4 +357,79 @@ bool KeyboardManagerState::HandleKeyDelayEvent(LowlevelKeyboardEvent* ev)
keyDelays[ev->lParam->vkCode]->KeyEvent(ev);
return true;
}
// Save the updated configuration.
bool KeyboardManagerState::SaveConfigToFile()
{
bool result = true;
json::JsonObject configJson;
json::JsonObject remapShortcuts;
json::JsonObject remapKeys;
json::JsonArray inProcessRemapKeysArray;
json::JsonArray globalRemapShortcutsArray;
std::unique_lock<std::mutex> lockSingleKeyReMap(singleKeyReMap_mutex);
for (const auto &it : singleKeyReMap)
{
json::JsonObject keys;
keys.SetNamedValue(KeyboardManagerConstants::OriginalKeysSettingName, json::value(winrt::to_hstring((unsigned int)it.first)));
keys.SetNamedValue(KeyboardManagerConstants::NewRemapKeysSettingName, json::value(winrt::to_hstring((unsigned int)it.second)));
inProcessRemapKeysArray.Append(keys);
}
lockSingleKeyReMap.unlock();
std::unique_lock<std::mutex> lockOsLevelShortcutReMap(osLevelShortcutReMap_mutex);
for (const auto &it : osLevelShortcutReMap)
{
json::JsonObject keys;
keys.SetNamedValue(KeyboardManagerConstants::OriginalKeysSettingName, json::value(it.first.ToHstringVK()));
keys.SetNamedValue(KeyboardManagerConstants::NewRemapKeysSettingName, json::value(it.second.targetShortcut.ToHstringVK()));
globalRemapShortcutsArray.Append(keys);
}
lockOsLevelShortcutReMap.unlock();
remapShortcuts.SetNamedValue(KeyboardManagerConstants::GlobalRemapShortcutsSettingName, globalRemapShortcutsArray);
remapKeys.SetNamedValue(KeyboardManagerConstants::InProcessRemapKeysSettingName, inProcessRemapKeysArray);
configJson.SetNamedValue(KeyboardManagerConstants::RemapKeysSettingName, remapKeys);
configJson.SetNamedValue(KeyboardManagerConstants::RemapShortcutsSettingName, remapShortcuts);
// Set timeout of 1sec to wait for file to get free.
DWORD timeout = 1000;
auto dwWaitResult = WaitForSingleObject(
configFile_mutex,
timeout);
if (dwWaitResult == WAIT_OBJECT_0)
{
try
{
json::to_file((PTSettingsHelper::get_module_save_folder_location(KeyboardManagerConstants::ModuleName) + L"\\" + GetCurrentConfigName() + L".json"), configJson);
}
catch (...)
{
result = false;
}
// Make sure to release the Mutex.
ReleaseMutex(configFile_mutex);
}
else
{
result = false;
}
return result;
}
void KeyboardManagerState::SetCurrentConfigName(const std::wstring& configName)
{
std::lock_guard<std::mutex> lock(currentConfig_mutex);
currentConfig = configName;
}
std::wstring KeyboardManagerState::GetCurrentConfigName()
{
std::lock_guard<std::mutex> lock(currentConfig_mutex);
return currentConfig;
}

View File

@@ -4,9 +4,11 @@
#include "Shortcut.h"
#include "RemapShortcut.h"
#include "KeyDelay.h"
#include "KeyboardManagerConstants.h"
#include <interface/lowlevel_keyboard_event_data.h>
#include <mutex>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <../common/settings_helpers.h>
using namespace winrt::Windows::UI::Xaml::Controls;
// Enum type to store different states of the UI
@@ -51,6 +53,13 @@ private:
// Stores the UI element which is to be updated based on the shortcut entered
StackPanel currentShortcutUI;
std::mutex currentShortcutUI_mutex;
// Stores the current configuration name.
std::wstring currentConfig = KeyboardManagerConstants::DefaultConfiguration;
std::mutex currentConfig_mutex;
// Handle of named mutex used for configuration file.
HANDLE configFile_mutex;
// Registered KeyDelay objects, used to notify delayed key events.
std::map<DWORD, std::unique_ptr<KeyDelay>> keyDelays;
@@ -84,6 +93,9 @@ public:
// Constructor
KeyboardManagerState();
// Destructor
~KeyboardManagerState();
// Function to reset the UI state members
void ResetUIState();
@@ -157,4 +169,13 @@ public:
// Reset the shortcut (backend) state after releasing a key.
void ResetDetectedShortcutKey(DWORD key);
// Save the updated configuration.
bool SaveConfigToFile();
// Sets the Current Active Configuartion Name.
void SetCurrentConfigName(const std::wstring& configName);
// Gets the Current Active Configuartion Name.
std::wstring GetCurrentConfigName();
};

View File

@@ -418,6 +418,43 @@ std::vector<winrt::hstring> Shortcut::GetKeyVector(LayoutMap& keyboardMap) const
return keys;
}
// Function to return the string representation of the shortcut in virtual key codes appended in a string by ";" separator.
winrt::hstring Shortcut::ToHstringVK() const
{
winrt::hstring output;
if (winKey != ModifierKey::Disabled && winKey != ModifierKey::Both)
{
output = output + winrt::to_hstring((unsigned int)GetWinKey(ModifierKey::Left)) + winrt::to_hstring(L";");
}
if (winKey == ModifierKey::Both)
{
output = output + winrt::to_hstring((unsigned int)KeyboardManagerConstants::VK_WIN_BOTH) + winrt::to_hstring(L";");
}
if (ctrlKey != ModifierKey::Disabled)
{
output = output + winrt::to_hstring((unsigned int)GetCtrlKey()) + winrt::to_hstring(L";");
}
if (altKey != ModifierKey::Disabled)
{
output = output + winrt::to_hstring((unsigned int)GetAltKey()) + winrt::to_hstring(L";");
}
if (shiftKey != ModifierKey::Disabled)
{
output = output + winrt::to_hstring((unsigned int)GetShiftKey()) + winrt::to_hstring(L";");
}
if (actionKey != NULL)
{
output = output + winrt::to_hstring((unsigned int)GetActionKey()) + winrt::to_hstring(L";");
}
if (!output.empty())
{
output = winrt::hstring(output.c_str(), output.size() - 1);
}
return output;
}
// Function to return a vector of key codes in the display order
std::vector<DWORD> Shortcut::GetKeyCodes()
{

View File

@@ -1,6 +1,7 @@
#pragma once
#include "Helpers.h"
#include "LayoutMap.h"
#include "KeyboardManagerConstants.h"
#include <interface/lowlevel_keyboard_event_data.h>
// Enum type to store different states of the win key
@@ -28,6 +29,25 @@ public:
{
}
// Constructor to intialize Shortcut from it's virtual key code string representation.
Shortcut(const std::wstring& shortcutVK) :
winKey(ModifierKey::Disabled), ctrlKey(ModifierKey::Disabled), altKey(ModifierKey::Disabled), shiftKey(ModifierKey::Disabled), actionKey(NULL)
{
auto keys = KeyboardManagerHelper::splitwstring(shortcutVK, ';');
for (auto it : keys)
{
auto vkKeyCode = std::stoul(it);
if (vkKeyCode == KeyboardManagerConstants::VK_WIN_BOTH)
{
SetKey(vkKeyCode, true);
}
else
{
SetKey(vkKeyCode);
}
}
}
// Less than operator must be defined to use with std::map.
inline bool operator<(const Shortcut& sc) const
{
@@ -135,6 +155,12 @@ public:
// Function to reset the state of a shortcut key based on the passed key code argument. Since there is no VK_WIN code, use the second argument for setting common win key.
void ResetKey(const DWORD& input, const bool& isWinBoth = false);
// Function to return the string representation of the shortcut
winrt::hstring ToHstring(LayoutMap& keyboardMap);
// Function to return the string representation of the shortcut in virtual key codes appended in a string by ";" separator.
winrt::hstring ToHstringVK() const;
// Function to return a vector of hstring for each key in the display order
std::vector<winrt::hstring> GetKeyVector(LayoutMap& keyboardMap) const;

View File

@@ -19,6 +19,5 @@ using namespace Windows::UI;
using namespace Windows::UI::Composition;
using namespace Windows::UI::Xaml::Hosting;
using namespace Windows::Foundation::Numerics;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;