编写 Lua 脚本为 Linux 中文输入法 Fcitx 增加桌面通知功能

我在 Linux 下面用中文输入法,有一个问题是,由于我把输入法切换设成了比较容易碰到的左 Shift 键,所以有的时候会无意中切换输入法,而不自知。

这个问题在我使用终端时,常常会引起一些问题。我觉得比较好的是切换时,把提示弄得显著一点。甚至时最好可以弄点声音出来。

在 Github 上面咨询了一下 Fcitx 的作者,显然最简单的方式是通过 Fcitx 自有的 Lua 脚本加载实现这样的功能。具体实现就两个文件:

Lua 脚本,具体文件名: ~/.local/share/fcitx5/lua/dunstify/dunstify.lua

local fcitx = require("fcitx")

fcitx.watchEvent(fcitx.EventType.KeyEvent, "caps_lock")
fcitx.watchEvent(fcitx.EventType.SwitchInputMethod, "switch_im")

local enable = false

function caps_lock(sym, state, release)
   if sym == 65509 and not release then
      enable = not enable
      if enable then
         h = io.popen("dunstify -t 2000 'CapsLock opened!'")
         o = h:read("*all")
         print(o)
         h:close()
      else
         h = io.popen("dunstify -t 2000 'CapsLock closed!'")
         o = h:read("*all")
         print(o)
         h:close()
      end
      print(string.format("change state of CapsLock: %s", enable))
   end
end

function switch_im()
   h = io.popen(string.format("dunstify -t 2000 'InputMethod switched to %s'", fcitx.currentInputMethod()))
   o = h:read("*all")
   print(o)
   h:close()
end

插件配置文件,具体文件名: ~/.local/share/fcitx5/addon/dunstify.conf

[Addon]
Name=Dunstify Lua
Comment=Lua script for displaying messages
Category=Module
Type=Lua
OnDemand=False
Configurable=False
Library=dunstify.lua

[Addon/Dependencies]
0=luaaddonloader

当然,你还需要安装 fcitx5-lua 包。


308 字

更新于 2022-10-30 19:02 +0800