Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Created September 9, 2026 04:41
Show Gist options
  • Select an option

  • Save qianlifeng/a46c95ef4bd0e5f782e873260ed72491 to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/a46c95ef4bd0e5f782e873260ed72491 to your computer and use it in GitHub Desktop.
Wox.Plugin.LockKeybord
# {
# "Id": "b7e2c4a1-8f3d-4e91-9c6a-2d5b1a0e8f47",
# "Name": "Wox.Plugin.LockKeybord",
# "Author": "qianlifeng",
# "Version": "1.0.0",
# "MinWoxVersion": "2.4.2",
# "Runtime": "PYTHON",
# "Description": "i18n:plugin_description",
# "Icon": "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><defs><linearGradient id=\"kgBg\" x1=\"6\" y1=\"2\" x2=\"42\" y2=\"46\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#0ea5e9\"/><stop offset=\".55\" stop-color=\"#6366f1\"/><stop offset=\"1\" stop-color=\"#a855f7\"/></linearGradient></defs><rect width=\"48\" height=\"48\" rx=\"13\" fill=\"url(#kgBg)\"/><rect x=\"8\" y=\"14\" width=\"32\" height=\"20\" rx=\"5\" fill=\"#e0f2fe\"/><rect x=\"11\" y=\"17\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#38bdf8\"/><rect x=\"18\" y=\"17\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#22c55e\"/><rect x=\"25\" y=\"17\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#f59e0b\"/><rect x=\"32\" y=\"17\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#f43f5e\"/><rect x=\"11\" y=\"24\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#a78bfa\"/><rect x=\"18\" y=\"24\" width=\"12\" height=\"5\" rx=\"1.2\" fill=\"#64748b\"/><rect x=\"32\" y=\"24\" width=\"5\" height=\"5\" rx=\"1.2\" fill=\"#06b6d4\"/><path d=\"M34 10l1.2 2.6 2.8.4-2 2 .5 2.8L34 16.6 31.5 17.8l.5-2.8-2-2 2.8-.4z\" fill=\"#fde047\"/></svg>",
# "TriggerKeywords": ["lock"],
# "SupportedOS": ["Windows", "Linux", "Macos"],
# "Features": [
# { "Name": "ignoreAutoScore" }
# ],
# "SettingDefinitions": [
# {
# "Type": "checkbox",
# "Value": {
# "Key": "lock_fn_keys",
# "Label": "i18n:setting_lock_fn",
# "Tooltip": "i18n:setting_lock_fn_tip",
# "DefaultValue": "false"
# },
# "DisabledInPlatforms": ["windows", "linux"],
# "IsPlatformSpecific": true
# }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Wox.Plugin.LockKeybord",
# "plugin_description": "Lock the keyboard so you can wipe it without triggering shortcuts",
# "duration_15s": "15 seconds",
# "duration_30s": "30 seconds",
# "duration_1m": "1 minute",
# "duration_2m": "2 minutes",
# "duration_5m": "5 minutes",
# "duration_1h": "1 hour",
# "duration_24h": "24 hours",
# "duration_forever": "Until I unlock",
# "duration_sub": "Press Enter to lock the keyboard",
# "action_lock": "Lock keyboard",
# "action_unlock": "Unlock keyboard",
# "locked_title": "Keyboard locked",
# "locked_sub_timed": "Unlocks in %s · Ctrl+Shift+U to unlock now",
# "locked_sub_forever": "Press Ctrl+Shift+U or choose Unlock to restore typing",
# "unlock_hint": "Ctrl+Shift+U unlocks at any time",
# "notify_locked": "Keyboard locked. Press Ctrl+Shift+U to unlock.",
# "notify_unlocked": "Keyboard unlocked",
# "notify_lock_failed": "Could not lock the keyboard: %s",
# "notify_unlock_failed": "Could not unlock the keyboard: %s",
# "setting_lock_fn": "Also lock Fn / function-row keys",
# "setting_lock_fn_tip": "Temporarily treat the function row as standard F-keys while locked. Restored on unlock. macOS 26+ only.",
# "remaining_forever": "until you unlock",
# "linux_wayland": "Keyboard lock needs an X11 session on this computer"
# },
# "zh_CN": {
# "plugin_name": "Wox.Plugin.LockKeybord",
# "plugin_description": "锁定键盘,方便擦拭按键且不会误触快捷键",
# "duration_15s": "15 秒",
# "duration_30s": "30 秒",
# "duration_1m": "1 分钟",
# "duration_2m": "2 分钟",
# "duration_5m": "5 分钟",
# "duration_1h": "1 小时",
# "duration_24h": "24 小时",
# "duration_forever": "直到手动解锁",
# "duration_sub": "按回车锁定键盘",
# "action_lock": "锁定键盘",
# "action_unlock": "解锁键盘",
# "locked_title": "键盘已锁定",
# "locked_sub_timed": "%s 后自动解锁 · Ctrl+Shift+U 立即解锁",
# "locked_sub_forever": "按 Ctrl+Shift+U 或选择解锁即可恢复输入",
# "unlock_hint": "随时按 Ctrl+Shift+U 解锁",
# "notify_locked": "键盘已锁定,按 Ctrl+Shift+U 解锁",
# "notify_unlocked": "键盘已解锁",
# "notify_lock_failed": "无法锁定键盘:%s",
# "notify_unlock_failed": "无法解锁键盘:%s",
# "setting_lock_fn": "同时锁定 Fn / 功能键行",
# "setting_lock_fn_tip": "锁定期间将功能键行临时当作标准 F 键。解锁后恢复。仅 macOS 26+。",
# "remaining_forever": "直到手动解锁",
# "linux_wayland": "当前会话是 Wayland,键盘锁定需要 X11"
# }
# }
# }
"""
Wox.Plugin.LockKeybord single-file SDK plugin.
Locks keyboard input for a chosen duration so the keys can be wiped
without firing shortcuts. Ctrl+Shift+U (or the Unlock action) restores input.
"""
from __future__ import annotations
import asyncio
import ctypes
import ctypes.util
import os
import platform
import subprocess
import sys
import threading
import time
from ctypes import wintypes
from typing import Any
from wox_plugin import (
ActionContext,
Context,
LogLevel,
PluginInitParams,
Query,
QueryResponse,
RefreshQueryParam,
Result,
ResultAction,
ResultTail,
ResultTailType,
ResultTailTextCategory,
UpdatableResult,
WoxImage,
)
def _svg(data: str) -> WoxImage:
if data.startswith("svg:"):
data = data[4:]
return WoxImage.new_svg(data)
def _badge(fill: str, glyph: str) -> WoxImage:
return _svg(
f'<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" '
f'viewBox="0 0 48 48"><rect width="48" height="48" rx="12" fill="{fill}"/>'
f"{glyph}</svg>"
)
PLUGIN_ICON = _svg(
'<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">'
'<defs><linearGradient id="kgBg" x1="6" y1="2" x2="42" y2="46" '
'gradientUnits="userSpaceOnUse"><stop stop-color="#0ea5e9"/>'
'<stop offset=".55" stop-color="#6366f1"/><stop offset="1" stop-color="#a855f7"/>'
"</linearGradient></defs>"
'<rect width="48" height="48" rx="13" fill="url(#kgBg)"/>'
'<rect x="8" y="14" width="32" height="20" rx="5" fill="#e0f2fe"/>'
'<rect x="11" y="17" width="5" height="5" rx="1.2" fill="#38bdf8"/>'
'<rect x="18" y="17" width="5" height="5" rx="1.2" fill="#22c55e"/>'
'<rect x="25" y="17" width="5" height="5" rx="1.2" fill="#f59e0b"/>'
'<rect x="32" y="17" width="5" height="5" rx="1.2" fill="#f43f5e"/>'
'<rect x="11" y="24" width="5" height="5" rx="1.2" fill="#a78bfa"/>'
'<rect x="18" y="24" width="12" height="5" rx="1.2" fill="#64748b"/>'
'<rect x="32" y="24" width="5" height="5" rx="1.2" fill="#06b6d4"/>'
'<path d="M34 10l1.2 2.6 2.8.4-2 2 .5 2.8L34 16.6 31.5 17.8l.5-2.8-2-2 2.8-.4z" '
'fill="#fde047"/></svg>'
)
LOCK_ICON = _badge(
"#16a34a",
'<path d="M18 22v-3.5a6 6 0 1 1 12 0V22" fill="none" stroke="#bbf7d0" '
'stroke-width="2.8" stroke-linecap="round"/>'
'<rect x="15" y="22" width="18" height="14" rx="3" fill="#f0fdf4"/>'
'<circle cx="24" cy="29" r="2.2" fill="#16a34a"/>',
)
UNLOCK_ICON = _badge(
"#f59e0b",
'<path d="M18 22v-3.5a6 6 0 0 1 11.2-3.1" fill="none" stroke="#fde68a" '
'stroke-width="2.8" stroke-linecap="round"/>'
'<rect x="15" y="22" width="18" height="14" rx="3" fill="#fffbeb"/>'
'<circle cx="24" cy="29" r="2.2" fill="#d97706"/>',
)
CLOCK_15 = _badge(
"#0ea5e9",
'<circle cx="24" cy="24" r="11" fill="#e0f2fe"/>'
'<path d="M24 16v8l5 3" fill="none" stroke="#0284c7" stroke-width="2.6" '
'stroke-linecap="round"/>',
)
CLOCK_30 = _badge(
"#2563eb",
'<circle cx="24" cy="24" r="11" fill="#dbeafe"/>'
'<path d="M24 16v8h6" fill="none" stroke="#1d4ed8" stroke-width="2.6" '
'stroke-linecap="round"/>',
)
CLOCK_1M = _badge(
"#22c55e",
'<rect x="13" y="16" width="22" height="18" rx="4" fill="#dcfce7"/>'
'<path d="M18 16v-3h12v3M20 25h8" stroke="#15803d" stroke-width="2.4" '
'stroke-linecap="round"/>',
)
CLOCK_2M = _badge(
"#06b6d4",
'<path d="M16 18c0-4 8-8 12-2 3 4-1 8-4 10" fill="none" stroke="#a5f3fc" '
'stroke-width="3" stroke-linecap="round"/>'
'<circle cx="28" cy="30" r="5" fill="#ecfeff"/>',
)
CLOCK_5M = _badge(
"#6366f1",
'<ellipse cx="24" cy="28" rx="12" ry="7" fill="#c7d2fe"/>'
'<path d="M14 28c1-8 19-8 20 0" fill="#818cf8"/>'
'<circle cx="18" cy="27" r="1.4" fill="#eef2ff"/>'
'<circle cx="24" cy="26" r="1.4" fill="#eef2ff"/>',
)
CLOCK_1H = _badge(
"#f59e0b",
'<path d="M16 30h16l-2 6H18z" fill="#fde68a"/>'
'<path d="M20 16h8l3 14H17z" fill="#fffbeb"/>'
'<path d="M22 16V13h4v3" stroke="#d97706" stroke-width="2" stroke-linecap="round"/>',
)
CLOCK_24H = _badge(
"#a855f7",
'<circle cx="17" cy="20" r="4" fill="#f5d0fe"/>'
'<circle cx="26" cy="17" r="5" fill="#e9d5ff"/>'
'<circle cx="31" cy="26" r="6" fill="#ddd6fe"/>',
)
CLOCK_FOREVER = _badge(
"#f43f5e",
'<path d="M16 24c0-4 4-7 8-4 4-3 8 0 8 4s-4 7-8 4c-4 3-8 0-8-4z" fill="none" '
'stroke="#ffe4e6" stroke-width="2.8" stroke-linecap="round"/>',
)
LOCKED_RESULT_ID = "keyboard-guard-locked"
ACTIVATE_SETTINGS = (
"/System/Library/PrivateFrameworks/SystemAdministration.framework/"
"Resources/activateSettings"
)
DURATIONS: list[tuple[str, int | None, WoxImage]] = [
("duration_15s", 15, CLOCK_15),
("duration_30s", 30, CLOCK_30),
("duration_1m", 60, CLOCK_1M),
("duration_2m", 120, CLOCK_2M),
("duration_5m", 300, CLOCK_5M),
("duration_1h", 3600, CLOCK_1H),
("duration_24h", 86400, CLOCK_24H),
("duration_forever", None, CLOCK_FOREVER),
]
class _Runtime:
"""Process-wide lock state shared by query, actions, and the hook thread."""
api: Any = None
loop: asyncio.AbstractEventLoop | None = None
lock = threading.Lock()
active = False
left: int | None = None
duration_key = ""
stop = threading.Event()
unlock = threading.Event()
worker: threading.Thread | None = None
watch: asyncio.Task[None] | None = None
saved_fn: bool | None = None
lock_fn_keys = False
error = ""
silent_unlock = False
RUNTIME = _Runtime()
def _is_macos() -> bool:
return sys.platform == "darwin"
def _is_windows() -> bool:
return sys.platform == "win32"
def _is_linux() -> bool:
return sys.platform.startswith("linux")
def _is_tahoe() -> bool:
if not _is_macos():
return False
try:
return int(platform.release().split(".", 1)[0]) >= 25
except ValueError:
return False
def _is_truthy(raw: str | None) -> bool:
return (raw or "").strip().lower() in {"1", "true", "yes", "on"}
def _format_remaining(seconds: int | None) -> str:
if seconds is None:
return ""
hours, rem = divmod(max(0, seconds), 3600)
minutes, secs = divmod(rem, 60)
if hours:
return f"{hours}:{minutes:02d}:{secs:02d}"
return f"{minutes:02d}:{secs:02d}"
def _remaining_now() -> int | None:
with RUNTIME.lock:
if not RUNTIME.active:
return 0
return RUNTIME.left
def _read_fn_state() -> bool:
try:
out = subprocess.check_output(
["defaults", "read", "-g", "com.apple.keyboard.fnState"],
text=True,
timeout=3,
).strip()
return out == "1"
except (OSError, subprocess.SubprocessError):
return False
def _set_fn_state(standard: bool) -> None:
subprocess.check_call(
["defaults", "write", "-g", "com.apple.keyboard.fnState", "-bool", str(standard).lower()],
timeout=3,
)
if os.path.isfile(ACTIVATE_SETTINGS):
subprocess.check_call([ACTIVATE_SETTINGS, "-u"], timeout=3)
def _apply_fn_lock() -> None:
if not (RUNTIME.lock_fn_keys and _is_tahoe()):
return
try:
RUNTIME.saved_fn = _read_fn_state()
_set_fn_state(True)
except (OSError, subprocess.SubprocessError):
# Keep any partial write so unlock can still restore.
if RUNTIME.saved_fn is None:
RUNTIME.saved_fn = False
def _restore_fn_lock() -> None:
if RUNTIME.saved_fn is None:
return
try:
_set_fn_state(RUNTIME.saved_fn)
except (OSError, subprocess.SubprocessError):
pass
RUNTIME.saved_fn = None
class _WindowsLocker:
"""Swallow keyboard events with a low-level hook; Ctrl+Shift+U requests unlock."""
WH_KEYBOARD_LL = 13
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
WM_SYSKEYDOWN = 0x0104
WM_SYSKEYUP = 0x0105
VK_CONTROL = 0x11
VK_LCONTROL = 0xA2
VK_RCONTROL = 0xA3
VK_SHIFT = 0x10
VK_LSHIFT = 0xA0
VK_RSHIFT = 0xA1
VK_U = 0x55
LLKHF_UP = 0x80
QS_ALLINPUT = 0x04FF
class _Kbd(ctypes.Structure):
_fields_ = [
("vkCode", wintypes.DWORD),
("scanCode", wintypes.DWORD),
("flags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_size_t),
]
def __init__(self) -> None:
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
self._hook = None
self._proc = None
self._ctrl_keys: set[int] = set()
self._shift_keys: set[int] = set()
def _request_unlock(self) -> None:
RUNTIME.unlock.set()
RUNTIME.stop.set()
def _track_modifier(
self,
held: set[int],
vk_code: int,
is_up: bool,
keys: tuple[int, ...],
generic: int,
left: int,
right: int,
) -> None:
if vk_code not in keys:
return
if is_up:
held.discard(vk_code)
if vk_code == generic:
held.discard(left)
held.discard(right)
return
held.add(vk_code)
def _callback(self, ncode: int, wparam: int, lparam: int) -> int:
try:
if ncode < 0:
return int(self.user32.CallNextHookEx(None, ncode, wparam, lparam))
info = ctypes.cast(lparam, ctypes.POINTER(self._Kbd)).contents
vk_code = int(info.vkCode)
is_up = wparam in (self.WM_KEYUP, self.WM_SYSKEYUP) or bool(
info.flags & self.LLKHF_UP
)
self._track_modifier(
self._ctrl_keys,
vk_code,
is_up,
(self.VK_CONTROL, self.VK_LCONTROL, self.VK_RCONTROL),
self.VK_CONTROL,
self.VK_LCONTROL,
self.VK_RCONTROL,
)
self._track_modifier(
self._shift_keys,
vk_code,
is_up,
(self.VK_SHIFT, self.VK_LSHIFT, self.VK_RSHIFT),
self.VK_SHIFT,
self.VK_LSHIFT,
self.VK_RSHIFT,
)
if (
not is_up
and vk_code == self.VK_U
and self._ctrl_keys
and self._shift_keys
):
self._request_unlock()
return 1
except Exception:
return 1
def run(self, stop: threading.Event) -> None:
hook_fn = ctypes.WINFUNCTYPE(
ctypes.c_ssize_t, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM
)
self.kernel32.GetModuleHandleW.restype = wintypes.HINSTANCE
self.user32.SetWindowsHookExW.restype = ctypes.c_void_p
self.user32.SetWindowsHookExW.argtypes = [
ctypes.c_int,
hook_fn,
wintypes.HINSTANCE,
wintypes.DWORD,
]
self.user32.CallNextHookEx.restype = ctypes.c_ssize_t
self.user32.MsgWaitForMultipleObjects.restype = wintypes.DWORD
self.user32.MsgWaitForMultipleObjects.argtypes = [
wintypes.DWORD,
ctypes.POINTER(wintypes.HANDLE),
wintypes.BOOL,
wintypes.DWORD,
wintypes.DWORD,
]
self._proc = hook_fn(self._callback)
module = self.kernel32.GetModuleHandleW(None)
self._hook = self.user32.SetWindowsHookExW(
self.WH_KEYBOARD_LL, self._proc, module, 0
)
if not self._hook:
raise OSError(ctypes.get_last_error() or "SetWindowsHookExW failed")
msg = wintypes.MSG()
try:
while not stop.is_set() and not RUNTIME.unlock.is_set():
self.user32.MsgWaitForMultipleObjects(
0, None, False, 50, self.QS_ALLINPUT
)
while self.user32.PeekMessageW(ctypes.byref(msg), None, 0, 0, 1):
self.user32.TranslateMessage(ctypes.byref(msg))
self.user32.DispatchMessageW(ctypes.byref(msg))
finally:
if self._hook:
self.user32.UnhookWindowsHookEx(self._hook)
self._hook = None
class _MacLocker:
"""Block key-downs with a session event tap; Ctrl+Shift+U requests unlock."""
KEY_DOWN = 10
FLAGS_CHANGED = 12
CONTROL_MASK = 0x00040000
SHIFT_MASK = 0x00020000
KEYCODE_U = 32
def __init__(self) -> None:
self._callback = None
def run(self, stop: threading.Event) -> None:
quartz_name = ctypes.util.find_library("ApplicationServices") or (
"/System/Library/Frameworks/ApplicationServices.framework/"
"Frameworks/CoreGraphics.framework/CoreGraphics"
)
cf_name = ctypes.util.find_library("CoreFoundation") or (
"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
)
quartz = ctypes.CDLL(quartz_name)
cf = ctypes.CDLL(cf_name)
tap_cb = ctypes.CFUNCTYPE(
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint32,
ctypes.c_void_p,
ctypes.c_void_p,
)
quartz.CGEventGetFlags.restype = ctypes.c_uint64
quartz.CGEventGetFlags.argtypes = [ctypes.c_void_p]
quartz.CGEventGetIntegerValueField.restype = ctypes.c_int64
quartz.CGEventGetIntegerValueField.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
def _on_event(_proxy, etype, event, _ref):
if etype == self.KEY_DOWN:
flags = quartz.CGEventGetFlags(event)
keycode = quartz.CGEventGetIntegerValueField(event, 9)
if (
keycode == self.KEYCODE_U
and flags & self.CONTROL_MASK
and flags & self.SHIFT_MASK
):
RUNTIME.unlock.set()
return None
return event
callback = tap_cb(_on_event)
mask = (1 << self.KEY_DOWN) | (1 << self.FLAGS_CHANGED)
quartz.CGEventTapCreate.restype = ctypes.c_void_p
tap = quartz.CGEventTapCreate(1, 0, 0, mask, callback, None)
if not tap:
raise OSError("event tap unavailable; grant Accessibility to Wox")
cf.CFMachPortCreateRunLoopSource.restype = ctypes.c_void_p
source = cf.CFMachPortCreateRunLoopSource(None, tap, 0)
cf.CFRunLoopGetCurrent.restype = ctypes.c_void_p
loop = cf.CFRunLoopGetCurrent()
default_mode = ctypes.c_void_p.in_dll(cf, "kCFRunLoopDefaultMode")
common_modes = ctypes.c_void_p.in_dll(cf, "kCFRunLoopCommonModes")
cf.CFRunLoopAddSource(loop, source, common_modes)
quartz.CGEventTapEnable(tap, True)
cf.CFRunLoopRunInMode.argtypes = [ctypes.c_void_p, ctypes.c_double, ctypes.c_bool]
self._callback = callback
try:
while not stop.is_set() and not RUNTIME.unlock.is_set():
cf.CFRunLoopRunInMode(default_mode, 0.05, True)
finally:
quartz.CGEventTapEnable(tap, False)
cf.CFRunLoopRemoveSource(loop, source, common_modes)
if source:
cf.CFRelease(source)
if tap:
cf.CFRelease(tap)
class _XKeyEvent(ctypes.Structure):
_fields_ = [
("type", ctypes.c_int),
("serial", ctypes.c_ulong),
("send_event", ctypes.c_int),
("display", ctypes.c_void_p),
("window", ctypes.c_ulong),
("root", ctypes.c_ulong),
("subwindow", ctypes.c_ulong),
("time", ctypes.c_ulong),
("x", ctypes.c_int),
("y", ctypes.c_int),
("x_root", ctypes.c_int),
("y_root", ctypes.c_int),
("state", ctypes.c_uint),
("keycode", ctypes.c_uint),
("same_screen", ctypes.c_int),
]
class _LinuxLocker:
"""Grab the X11 keyboard. Wayland sessions cannot lock keys this way."""
def run(self, stop: threading.Event) -> None:
if os.environ.get("WAYLAND_DISPLAY") and not os.environ.get("DISPLAY"):
raise OSError("wayland")
x11 = ctypes.CDLL("libX11.so.6")
x11.XOpenDisplay.restype = ctypes.c_void_p
display = x11.XOpenDisplay(None)
if not display:
raise OSError("XOpenDisplay failed")
root = x11.XDefaultRootWindow(display)
grab = x11.XGrabKeyboard(display, root, True, 1, 1, 0)
if grab != 0:
x11.XCloseDisplay(display)
raise OSError("XGrabKeyboard failed")
x11.XLookupKeysym.restype = ctypes.c_ulong
x11.XLookupKeysym.argtypes = [ctypes.POINTER(_XKeyEvent), ctypes.c_int]
event = _XKeyEvent()
try:
while not stop.is_set() and not RUNTIME.unlock.is_set():
if x11.XPending(display):
x11.XNextEvent(display, ctypes.byref(event))
if event.type == 2:
keysym = x11.XLookupKeysym(ctypes.byref(event), 0)
if keysym in (0x75, 0x55) and event.state & 4 and event.state & 1:
RUNTIME.unlock.set()
else:
time.sleep(0.02)
finally:
x11.XUngrabKeyboard(display, 0)
x11.XCloseDisplay(display)
def _new_locker() -> Any:
if _is_windows():
return _WindowsLocker()
if _is_macos():
return _MacLocker()
if _is_linux():
return _LinuxLocker()
raise OSError(f"unsupported platform: {sys.platform}")
def _worker_main(seconds: int | None) -> None:
deadline = None if seconds is None else time.monotonic() + seconds
try:
locker = _new_locker()
_apply_fn_lock()
locker.run(RUNTIME.stop)
except Exception as exc: # noqa: BLE001 - surface any hook/grab failure
RUNTIME.error = "wayland" if str(exc) == "wayland" else str(exc)
RUNTIME.unlock.set()
finally:
if deadline is not None and time.monotonic() >= deadline:
RUNTIME.unlock.set()
_restore_fn_lock()
with RUNTIME.lock:
RUNTIME.active = False
RUNTIME.worker = None
def _start_lock(seconds: int | None, duration_key: str) -> None:
_stop_lock()
RUNTIME.error = ""
RUNTIME.silent_unlock = False
RUNTIME.stop.clear()
RUNTIME.unlock.clear()
with RUNTIME.lock:
RUNTIME.active = True
RUNTIME.duration_key = duration_key
RUNTIME.left = seconds
worker = threading.Thread(
target=_worker_main,
args=(seconds,),
name="keyboard-guard-hook",
daemon=True,
)
RUNTIME.worker = worker
worker.start()
worker.join(0.15)
if RUNTIME.error:
message = RUNTIME.error
_stop_lock()
raise RuntimeError(message)
def _stop_lock() -> None:
RUNTIME.stop.set()
RUNTIME.unlock.set()
worker = RUNTIME.worker
if worker is not None and worker.is_alive() and worker is not threading.current_thread():
worker.join(2.0)
_restore_fn_lock()
with RUNTIME.lock:
RUNTIME.active = False
RUNTIME.left = None
RUNTIME.duration_key = ""
RUNTIME.worker = None
def _duration_icon(key: str) -> WoxImage:
for item_key, _seconds, icon in DURATIONS:
if item_key == key:
return icon
return PLUGIN_ICON
class LockKeybordPlugin:
def __init__(self) -> None:
self._lock_i18n: dict[str, str] = {}
async def init(self, ctx: Context, params: PluginInitParams) -> None:
self.api = params.api
RUNTIME.api = params.api
RUNTIME.loop = asyncio.get_running_loop()
RUNTIME.lock_fn_keys = _is_truthy(await self.api.get_setting(ctx, "lock_fn_keys"))
await self.api.on_setting_changed(ctx, self._on_setting_changed)
await self.api.on_unload(ctx, self._on_unload)
async def _on_setting_changed(self, ctx: Context, key: str, value: str) -> None:
if key == "lock_fn_keys":
RUNTIME.lock_fn_keys = _is_truthy(value)
await self.api.log(ctx, LogLevel.INFO, f"setting {key}={value}")
async def _on_unload(self, _ctx: Context) -> None:
_stop_lock()
watch = RUNTIME.watch
if watch is not None:
watch.cancel()
async def _t(self, ctx: Context, key: str, *args: Any) -> str:
raw = self._lock_i18n.get(key)
if raw is None:
raw = await self.api.get_translation(ctx, key)
self._lock_i18n[key] = raw
if args:
try:
return raw % args
except TypeError:
return raw
return raw
async def query(self, ctx: Context, query: Query) -> QueryResponse:
if RUNTIME.active:
return QueryResponse(results=[await self._locked_result(ctx)])
if RUNTIME.error == "wayland":
return QueryResponse(
results=[
Result(
title="i18n:linux_wayland",
sub_title="i18n:unlock_hint",
icon=PLUGIN_ICON,
)
]
)
needle = (query.search or "").strip().lower()
results: list[Result] = []
for index, (key, seconds, icon) in enumerate(DURATIONS):
title = await self._t(ctx, key)
haystack = f"{title} {key} {seconds or 'forever'}".lower()
if needle and needle not in haystack:
continue
results.append(
Result(
id=f"keyboard-guard-{key}",
title=title,
sub_title="i18n:duration_sub",
icon=icon,
score=100 - index,
actions=[
ResultAction(
id=f"lock-{key}",
name="i18n:action_lock",
icon=LOCK_ICON,
is_default=True,
prevent_hide_after_action=True,
context_data={
"seconds": "" if seconds is None else str(seconds),
"duration_key": key,
},
action=self._on_lock,
)
],
)
)
return QueryResponse(results=results)
def _parse_lock_seconds(self, raw: str) -> int | None:
text = (raw or "").strip()
if not text:
return None
try:
return max(0, int(text))
except ValueError:
return None
async def _on_lock(self, ctx: Context, ac: ActionContext) -> None:
seconds = self._parse_lock_seconds(ac.context_data.get("seconds", ""))
duration_key = ac.context_data.get("duration_key", "")
try:
_start_lock(seconds, duration_key)
except RuntimeError as exc:
if str(exc) == "wayland":
RUNTIME.error = "wayland"
await self.api.notify(ctx, await self._t(ctx, "linux_wayland"))
else:
await self.api.notify(
ctx, await self._t(ctx, "notify_lock_failed", str(exc))
)
await self.api.refresh_query(
ctx, RefreshQueryParam(preserve_selected_index=False)
)
return
await self.api.notify(ctx, await self._t(ctx, "notify_locked"))
await self.api.refresh_query(
ctx, RefreshQueryParam(preserve_selected_index=False)
)
self._ensure_watch(ctx)
async def _on_unlock(self, ctx: Context, _ac: ActionContext) -> None:
RUNTIME.silent_unlock = True
try:
_stop_lock()
except Exception as exc: # noqa: BLE001
RUNTIME.silent_unlock = False
await self.api.notify(
ctx, await self._t(ctx, "notify_unlock_failed", str(exc))
)
return
await self.api.notify(ctx, await self._t(ctx, "notify_unlocked"))
await self.api.refresh_query(
ctx, RefreshQueryParam(preserve_selected_index=False)
)
async def _remaining_texts(self, ctx: Context) -> tuple[str, str]:
left = _remaining_now()
if left is None:
remaining = await self._t(ctx, "remaining_forever")
subtitle = await self._t(ctx, "locked_sub_forever")
return remaining, subtitle
remaining = _format_remaining(left)
subtitle = await self._t(ctx, "locked_sub_timed", remaining)
return remaining, subtitle
def _remaining_tail(self, remaining: str) -> ResultTail:
return ResultTail(
type=ResultTailType.TEXT,
text=remaining,
text_category=ResultTailTextCategory.WARNING,
)
async def _locked_result(self, ctx: Context) -> Result:
remaining, subtitle = await self._remaining_texts(ctx)
return Result(
id=LOCKED_RESULT_ID,
title="i18n:locked_title",
sub_title=subtitle,
icon=_duration_icon(RUNTIME.duration_key),
tails=[self._remaining_tail(remaining)],
actions=[
ResultAction(
id="unlock",
name="i18n:action_unlock",
icon=UNLOCK_ICON,
is_default=True,
prevent_hide_after_action=True,
hotkey="ctrl+shift+u",
action=self._on_unlock,
)
],
)
def _ensure_watch(self, ctx: Context) -> None:
if RUNTIME.watch is not None and not RUNTIME.watch.done():
RUNTIME.watch.cancel()
RUNTIME.watch = asyncio.create_task(self._watch_lock(ctx))
async def _push_locked_ui(self, ctx: Context) -> None:
remaining, subtitle = await self._remaining_texts(ctx)
await self.api.update_result(
ctx,
UpdatableResult(
id=LOCKED_RESULT_ID,
title="i18n:locked_title",
sub_title=subtitle,
tails=[self._remaining_tail(remaining)],
),
)
async def _sleep_or_unlock(self, seconds: float | None) -> bool:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, RUNTIME.unlock.wait, seconds)
async def _finish_watch(self, ctx: Context) -> None:
if RUNTIME.active:
_stop_lock()
await self.api.refresh_query(
ctx, RefreshQueryParam(preserve_selected_index=False)
)
if RUNTIME.error and RUNTIME.error != "wayland":
await self.api.notify(ctx, await self._t(ctx, "notify_lock_failed", RUNTIME.error))
return
if not RUNTIME.silent_unlock:
await self.api.notify(ctx, await self._t(ctx, "notify_unlocked"))
async def _watch_lock(self, ctx: Context) -> None:
try:
left = _remaining_now()
if left is None:
await self._sleep_or_unlock(None)
await self._finish_watch(ctx)
return
for remaining in range(left, 0, -1):
if not RUNTIME.active or RUNTIME.unlock.is_set():
break
with RUNTIME.lock:
RUNTIME.left = remaining
await self._push_locked_ui(ctx)
if await self._sleep_or_unlock(1):
break
await self._finish_watch(ctx)
except asyncio.CancelledError:
return
plugin = LockKeybordPlugin()
@qianlifeng

Copy link
Copy Markdown
Author
image

@qianlifeng

Copy link
Copy Markdown
Author
Wox Plugin LockKeybord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment