Created
July 11, 2020 15:04
-
-
Save dbalatero/4c05524144c048f5b5251de2daf81702 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Remapper = {} | |
function Remapper:new() | |
local remapper = {} | |
setmetatable(remapper, self) | |
self.__index = self | |
remapper.keyMaps = {} | |
remapper.eventTap = remapper:_createEventTap() | |
return remapper | |
end | |
function Remapper:map(mapModifiers, mapKey) | |
local remapper = self | |
return { | |
to = function(destinationModifiers, destinationKey) | |
if not remapper.keyMaps[mapKey] then | |
remapper.keyMaps[mapKey] = {} | |
end | |
local modifiersMatchEvent = function(event) | |
return event:getFlags():containExactly(mapModifiers) | |
end | |
table.insert( | |
remapper.keyMaps[mapKey], | |
{ | |
modifiersMatchEvent = modifiersMatchEvent, | |
destination = { | |
key = destinationKey, | |
modifiers = destinationModifiers | |
} | |
} | |
) | |
end | |
} | |
end | |
function Remapper:_findRemapByEvent(event) | |
local keyCode = event:getKeyCode() | |
local keyPressed = hs.keycodes.map[keyCode] | |
local maps = self.keyMaps[keyPressed] | |
if not maps then return nil end | |
for _, remap in ipairs(maps) do | |
if remap.modifiersMatchEvent(event) then | |
return remap | |
end | |
end | |
return nil | |
end | |
function Remapper:_createEventTap() | |
local tap = hs.eventtap.new( | |
{ hs.eventtap.event.types.keyDown }, | |
self:_getKeyEventHandler() | |
) | |
tap:start() | |
return tap | |
end | |
function Remapper:_getKeyEventHandler() | |
return function(event) | |
local remap = self:_findRemapByEvent(event) | |
if remap then | |
local destinationKey = remap.destination.key | |
local destinationModifiers = remap.destination.modifiers | |
return true, { | |
hs.eventtap.event.newKeyEvent(destinationModifiers, destinationKey, true), -- key down | |
hs.eventtap.event.newKeyEvent(destinationModifiers, destinationKey, false) -- key up | |
} | |
end | |
return false | |
end | |
end | |
local remapper = Remapper:new() | |
remapper:map({'alt'}, 'r').to({'cmd'}, 'space') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment