用 Hammerspoon 切换输入法时,为什么会发生很多次切换?

2023-01-09 19:03:17 +08:00
 Dvel

我就是想加入一个功能:从 xxx 软件切换到 iTerm ,输入法切换到英文;从 iTerm 回到 xxx 软件,将输入法调回原来的状态。
不会 lua ,代码都是照猫画虎的,但是感觉应该没问题。结果也没问题,可是发生了很多次切换,菜单栏输入法图标会有一阵短暂而急促的抖动,有点逼死强迫症了。
不知道为什么 Hammerspoon 监测不到 Alfred ,然后我发现 Alfred 自己的 Force Keyboard 功能也有这个问题。

如图,在 VSCode (不设定)和 iTerm (设定为切换到 ABC 输入法)之间切换时:

所有代码如下:

-- 切换输入法
local function Chinese()
    hs.keycodes.currentSourceID("im.rime.inputmethod.Squirrel.Rime")
end

local function English()
    hs.keycodes.currentSourceID("com.apple.keylayout.ABC")
end

local appInputMethod = {
    iTerm2 = English,
    Alfred = English,
    ['Sublime Text'] = English,
    ['EuDic LightPeek'] = English,
    ['微信'] = Chinese
}

-- activated 时切换到设定的输入法,deactivated 时恢复输入法
currentID = ""
function applicationWatcher(appName, eventType, appObject)
    if (eventType == hs.application.watcher.activated) then
        for app, fn in pairs(appInputMethod) do
            if app == appName then
                currentID = hs.keycodes.currentSourceID()
                fn()
            end
        end
    end
    if eventType == hs.application.watcher.deactivated then
        for app, fn in pairs(appInputMethod) do
            if app == appName then
                hs.keycodes.currentSourceID(currentID)
                currentID = hs.keycodes.currentSourceID()
            end
        end
    end
end

appWatcher = hs.application.watcher.new(applicationWatcher):start()

-- 输入法切换提示
hs.keycodes.inputSourceChanged(function()
    if hs.keycodes.currentMethod() == nil then
        hs.alert.show("ABC", hs.alert.defaultStyle, hs.screen.mainScreen(), 2)
    else
        hs.alert.show("拼音", hs.alert.defaultStyle, hs.screen.mainScreen(), 2)
    end
end)
866 次点击
所在节点   输入法
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/907699

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX