我的 Hammerspoon 脚本中的按键重复出现延迟

axs*_*uul 4 lua hammerspoon

我将 CAPSLOCK 绑定到 F18(登山扣)以充当修改键。我正在尝试模拟 CAPSLOCK+h、j、k、l 作为 VIM 移动键。一切正常,但重复时存在延迟问题。也就是说,当我按下 CAPSLOCK+h 时,它非常慢,它应该模拟重复按下“<-”键,但它非常延迟,每秒只发送一个。关于为什么会发生这种情况有什么想法吗?我init.lua的如下:

-- A global variable for the Hyper Mode
k = hs.hotkey.modal.new({}, "F17")

-- Enter Hyper Mode when F18 (Hyper/Capslock) is pressed
pressedF18 = function()
  k.triggered = false
  k.modifier = false
  k:enter()

  trigger_modifier = function()
    k.modifier = true
  end

  -- Only trigger as modifier if held longer than thisj
  hs.timer.doAfter(0.35, trigger_modifier)
end

-- Arrow keys
k:bind({}, 'h', function()
  hs.eventtap.keyStroke({}, 'Left')
  k.triggered = true
end)

k:bind({}, 'j', function()
  hs.eventtap.keyStroke({}, 'Down')
  k.triggered = true
end)

k:bind({}, 'k', function()
  hs.eventtap.keyStroke({}, 'Up')
  k.triggered = true
end)

k:bind({}, 'l', function()
  hs.eventtap.keyStroke({}, 'Right')
  k.triggered = true
end)

-- Leave Hyper Mode when F18 (Hyper/Capslock) is pressed,
--   send ESCAPE if no other keys are pressed.
releasedF18 = function()
  k:exit()

  if not k.triggered then
    -- If hotkey held longer than this amount of time
    -- let it remain as modifier and don't send ESCAPE
    if not k.modifier then
      hs.eventtap.keyStroke({}, 'ESCAPE')
    else
      print("Modifier detected")
    end
  end
end

-- Bind the Hyper key
f18 = hs.hotkey.bind({}, 'F18', pressedF18, releasedF18)
Run Code Online (Sandbox Code Playgroud)

Ell*_*olf 6

我也有类似的缓慢。看起来最新版本之一引入了一些缓慢的情况。您可以使用以下函数调用较低级别的函数fastKeyStroke。我已经包含了我的hjkl实现,以便您可以看到它的使用情况。另请注意,我按照文档hs.hotkey.bind中指定的方式将 5 个参数传递给密钥重复。

local hyper = {"shift", "cmd", "alt", "ctrl"}

local fastKeyStroke = function(modifiers, character)
  local event = require("hs.eventtap").event
  event.newKeyEvent(modifiers, string.lower(character), true):post()
  event.newKeyEvent(modifiers, string.lower(character), false):post()
end

hs.fnutils.each({
  -- Movement
  { key='h', mod={}, direction='left'},
  { key='j', mod={}, direction='down'},
  { key='k', mod={}, direction='up'},
  { key='l', mod={}, direction='right'},
  { key='n', mod={'cmd'}, direction='left'},  -- beginning of line
  { key='p', mod={'cmd'}, direction='right'}, -- end of line
  { key='m', mod={'alt'}, direction='left'},  -- back word
  { key='.', mod={'alt'}, direction='right'}, -- forward word
}, function(hotkey)
  hs.hotkey.bind(hyper, hotkey.key, 
      function() fastKeyStroke(hotkey.mod, hotkey.direction) end,
      nil,
      function() fastKeyStroke(hotkey.mod, hotkey.direction) end
    )
  end
)
Run Code Online (Sandbox Code Playgroud)

关于缓慢的来源

  • 是的,这是现在的正确答案 - hs.eventtap.keyStroke() 实际上只是相同的 newKeyEvent() 对,中间有一个 hs.timer.usleep() 。我们添加了短暂的睡眠,以尽量避免关键事件无序到达。下一个版本将添加可配置的延迟,因此您可以根据需要将其关闭:) (2认同)