V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Dvel
V2EX  ›  输入法

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

  •  
  •   Dvel · 2023-01-09 19:03:17 +08:00 · 856 次点击
    这是一个创建于 465 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我就是想加入一个功能:从 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)
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1175 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:22 · PVG 02:22 · LAX 11:22 · JFK 14:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.