hchunhui / librime-lua

Extending RIME with Lua scripts
BSD 3-Clause "New" or "Revised" License
293 stars 43 forks source link

请求增加获取系统毫秒时间戳的api #311

Closed Urie96 closed 5 months ago

Urie96 commented 5 months ago

我想实现一个快速连按两下冒号输出:=的lua_processor,但是似乎现在无法从lua中获取毫秒时间戳,请问有办法实现吗

shewer commented 5 months ago

可以用 os.clock() 每次 processor::processorkeyevent() 時 記錄時間()

function P.init(env)
   env.timestmp = os.clock()
end

function P.func(key, env)
    local stmp = os.clock()
    local ltime = stmp - env.timestmp
    env.timestmp = stmp

     ......
end

return P
shewer commented 5 months ago

忘了說明processorKeyEvent() 是 包含 Release 的 按下 a 鬆開 a 按下 a 所以 刷新 timestmp 機制 要調整一下

Shift+Release+F12 Shift+Release+Shift_L a Release+a b Release+b c Release+c d Release+d e Release+e f Release+f g Release+g g g g g g g g g g g g g g g g g Release+g Shift_L 
shewer commented 5 months ago

發覺我錯了 os.clock() 用不了

你可以用luarocks 裝 socket 裏頭有 gettime() 可以用

shewer commented 5 months ago

需要 luasocket 的gettime()

#! /usr/bin/env lua
--
-- pack.lua
-- Copyright (C) 2024 Shewer Lu <shewer@gmail.com>
--
-- Distributed under terms of the MIT license.
--
local P={}

local socket= require 'socket'
local tmt = {}
tmt.msize = 10
tmt.__index = tmt
function tmt.comp(key1, key2)
  return key1 == key2
end
function tmt.update(tab,key)
  table.insert(tab,1, {key=key,stmp=socket.gettime()})
  if #tab <= tab.msize then return end
  for i=tab.msize+1,#tab do
    tab[i] = nil
  end
end
function tmt.reset(tab)
  tab[1].key= KeyEvent("")
  for i=2,#tab do 
    tab[i] = nil
  end
end
--  a releas a  : _start 2 
--  Shift+A Shift+Release+A Shift+A  : _start 2
--
function tmt.last_time(tab,key,_start,_end)
  key = key or tab[1].key
  local time= tab[1].stmp
  for i=(_start or 2) ,(_end or #tab) do 
    if tab.comp(key, tab[i].key) then
      time=time - tab[i].stmp
      return time, i
    end
  end
  return time - tab[#tab].stmp, -1
end

local function TimeStmp(comp_func)
  return setmetatable( {
    {stmp=os.time() + os.clock(),key=KeyEvent("~")},
    comp = type(comp_func) == "function" and func or nil,
  }, tmt) 
end

function P.init(env)
  env.timestmp= TimeStmp(
    function(k1,k2) return k1:eq(k2) end)
  env.key=KeyEvent('Shift+colon')
end

function P.func(key,env)
  env.timestmp:update(key)
  if key:ctrl() or key:alt() or key:super() then return 2 end
  local tm , count = env.timestmp:last_time()

  if key:eq(env.key) then
    local tm,count =env.timestmp:last_time(key,2,4)
    log.error( "-------count".. count  .. " tm: " ..tm  .." key: " .. key:repr() )
    if tm < 0.25 then
      env.engine.context:pop_input(1)
      env.engine:commit_text(":="..count)
      env.timestmp:reset()
      return 1
    end
  end
  return 2
end 
return P