Last active
September 6, 2024 17:48
-
-
Save ibreathebsb/65fae9d742c5ebdb409960bceaf934de 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 function Chinese() | |
-- 简体拼音 | |
hs.keycodes.currentSourceID("com.apple.inputmethod.SCIM.ITABC") | |
end | |
local function English() | |
-- ABC | |
hs.keycodes.currentSourceID("com.apple.keylayout.ABC") | |
end | |
-- app to expected ime config | |
-- app和对应的输入法 | |
local app2Ime = { | |
{'/Applications/iTerm.app', 'English'}, | |
{'/Applications/Visual Studio Code.app', 'English'}, | |
{'/Applications/Xcode.app', 'English'}, | |
{'/Applications/Google Chrome.app', 'English'}, | |
{'/System/Library/CoreServices/Finder.app', 'English'}, | |
{'/Applications/Kindle.app', 'English'}, | |
{'/Applications/System Preferences.app', 'English'}, | |
{'/Applications/DingTalk.app', 'Chinese'}, | |
} | |
function updateFocusAppInputMethod() | |
local ime = 'English' | |
local focusAppPath = hs.window.frontmostWindow():application():path() | |
for index, app in pairs(app2Ime) do | |
local appPath = app[1] | |
local expectedIme = app[2] | |
if focusAppPath == appPath then | |
ime = expectedIme | |
break | |
end | |
end | |
if ime == 'English' then | |
English() | |
else | |
Chinese() | |
end | |
end | |
-- helper hotkey to figure out the app path and name of current focused window | |
-- 当选中某窗口按下ctrl+command+.时会显示应用的路径等信息 | |
hs.hotkey.bind({'ctrl', 'cmd'}, ".", function() | |
hs.alert.show("App path: " | |
..hs.window.focusedWindow():application():path() | |
.."\n" | |
.."App name: " | |
..hs.window.focusedWindow():application():name() | |
.."\n" | |
.."IM source id: " | |
..hs.keycodes.currentSourceID()) | |
end) | |
-- Handle cursor focus and application's screen manage. | |
-- 窗口激活时自动切换输入法 | |
function applicationWatcher(appName, eventType, appObject) | |
if (eventType == hs.application.watcher.activated or eventType == hs.application.watcher.launched) then | |
updateFocusAppInputMethod() | |
end | |
end | |
appWatcher = hs.application.watcher.new(applicationWatcher) | |
appWatcher:start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这个脚本当 Mac 刚被唤醒的时候会出错。问题在于:
这一行中,
hs.window.frontmostWindow()
这个接口是有可能返回nil
的。我推测是 Mac 刚被唤醒的时候,前台还没有可见的应用窗口导致的。其实我很好奇,为什么不直接用传进回调函数的
appName
参数,而是用比较复杂的appPath
呢? 😂