Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active November 3, 2026 09:22
Show Gist options
  • Select an option

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

Select an option

Save qianlifeng/75ee2660ab0bd347623a752b0f2d4cd9 to your computer and use it in GitHub Desktop.
Wox.Plugin.Script.Scoop
#!/usr/bin/env python3
# {
# "Id": "c3e8a7d2-4b1f-4e6a-9d2c-8f5a1b0e7c34",
# "Name": "i18n:plugin_name",
# "Author": "qianlifeng",
# "Version": "1.1.0",
# "MinWoxVersion": "2.4.9",
# "Runtime": "PYTHON",
# "Description": "i18n:plugin_description",
# "Website": "https://scoop.sh",
# "Icon": "url:https://avatars.githubusercontent.com/u/16618068?s=128",
# "TriggerKeywords": ["scoop"],
# "SupportedOS": ["Windows"],
# "Commands": [
# { "Command": "list", "Description": "i18n:cmd_list" },
# { "Command": "search", "Description": "i18n:cmd_search" },
# { "Command": "update", "Description": "i18n:cmd_update" }
# ],
# "Features": [
# { "Name": "debounce", "Params": { "IntervalMs": 250 } },
# { "Name": "ignoreAutoScore" }
# ],
# "SettingDefinitions": [
# {
# "Type": "textbox",
# "Value": {
# "Key": "scoop_home",
# "Label": "i18n:setting_scoop_home",
# "Tooltip": "i18n:setting_scoop_home_tip",
# "DefaultValue": "",
# "Style": { "Width": 420 }
# },
# "IsPlatformSpecific": true
# },
# {
# "Type": "textbox",
# "Value": {
# "Key": "scoop_global_home",
# "Label": "i18n:setting_scoop_global_home",
# "Tooltip": "i18n:setting_scoop_global_home_tip",
# "DefaultValue": "",
# "Style": { "Width": 420 }
# },
# "IsPlatformSpecific": true
# }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Scoop",
# "plugin_description": "Search and manage Windows apps with Scoop",
# "cmd_list": "List installed Scoop apps",
# "cmd_search": "Search apps in added buckets",
# "cmd_update": "Show and update available apps",
# "setting_scoop_home": "Scoop Home user root",
# "setting_scoop_home_tip": "Optional. Leave empty to detect the user Scoop root automatically.",
# "setting_scoop_global_home": "Scoop Home global root",
# "setting_scoop_global_home_tip": "Optional. Only needed when the global root cannot be detected.",
# "missing_title": "Scoop is not installed",
# "missing_subtitle": "Install Scoop first, or set the Scoop root in plugin settings",
# "missing_open": "Open scoop.sh",
# "search_need_keyword": "Enter an app name to search",
# "search_need_keyword_sub": "You can also use bucket/name, for example extras/firefox",
# "search_empty": "No matching apps in local buckets",
# "search_subtitle": "bucket: %s, version: %s",
# "group_updates": "Updates available",
# "group_installed": "Installed",
# "list_empty": "No installed Scoop apps",
# "list_subtitle": "%s",
# "open_app": "Open",
# "open_dir": "Open install directory",
# "open_manifest": "Open manifest directory",
# "open_homepage": "Open homepage",
# "copy_name": "Copy name",
# "install": "Install",
# "install_global": "Install global",
# "install_to": "Install to %s",
# "update": "Update",
# "uninstall": "Uninstall",
# "reset": "Reset",
# "update_scoop": "Update Scoop and buckets",
# "update_scoop_sub": "scoop update",
# "update_all_user": "Update all user applications",
# "update_all_user_sub": "scoop update --all",
# "update_all_global": "Update all global applications",
# "update_all_global_sub": "scoop update --all --global",
# "update_none": "No application updates available",
# "update_admin": "Global application updates require administrator privileges",
# "update_subtitle": "%s -> %s",
# "need_admin": "Administrator privileges are required for global Scoop operations",
# "running": "Running",
# "starting": "Starting...",
# "completed": "Completed",
# "failed": "Failed",
# "already_running": "Operation is already running",
# "tool_list": "List installed Scoop packages"
# },
# "zh_CN": {
# "plugin_name": "Scoop",
# "plugin_description": "用 Scoop 搜索和管理 Windows 应用",
# "cmd_list": "列出已安装的 Scoop 应用",
# "cmd_search": "在已添加的 bucket 中搜索应用",
# "cmd_update": "查看并更新可升级的应用",
# "setting_scoop_home": "Scoop 用户根目录",
# "setting_scoop_home_tip": "可选。留空则自动检测用户级 Scoop 根目录。",
# "setting_scoop_global_home": "Scoop 全局根目录",
# "setting_scoop_global_home_tip": "可选。仅在无法自动检测全局根目录时填写。",
# "missing_title": "未检测到 Scoop",
# "missing_subtitle": "请先安装 Scoop,或在插件设置中指定 Scoop 根目录",
# "missing_open": "打开 scoop.sh",
# "search_need_keyword": "请输入要搜索的应用名",
# "search_need_keyword_sub": "也支持 bucket/name,例如 extras/firefox",
# "search_empty": "本地 bucket 中没有匹配的应用",
# "search_subtitle": "bucket: %s, version: %s",
# "group_updates": "可更新",
# "group_installed": "已安装",
# "list_empty": "没有已安装的 Scoop 应用",
# "list_subtitle": "%s",
# "open_app": "打开",
# "open_dir": "打开安装目录",
# "open_manifest": "打开清单目录",
# "open_homepage": "打开主页",
# "copy_name": "复制名称",
# "install": "安装",
# "install_global": "全局安装",
# "install_to": "安装到 %s",
# "update": "更新",
# "uninstall": "卸载",
# "reset": "重置",
# "update_scoop": "更新 Scoop 和 buckets",
# "update_scoop_sub": "scoop update",
# "update_all_user": "更新全部用户应用",
# "update_all_user_sub": "scoop update --all",
# "update_all_global": "更新全部全局应用",
# "update_all_global_sub": "scoop update --all --global",
# "update_none": "没有可更新的应用",
# "update_admin": "更新全局应用需要管理员权限",
# "update_subtitle": "%s -> %s",
# "need_admin": "全局 Scoop 操作需要管理员权限",
# "running": "执行中",
# "starting": "正在启动…",
# "completed": "已完成",
# "failed": "执行失败",
# "already_running": "操作正在执行",
# "tool_list": "列出已安装的 Scoop 软件包"
# }
# }
# }
"""
Wox Python script plugin for Scoop.
Inspired by Flow.Launcher.Plugin.Scoop. Script plugins are short-lived, so
install/update/uninstall commands are started in a new console window instead of
waiting for Scoop to finish inside the 10s script timeout.
"""
from __future__ import annotations
import asyncio
import ctypes
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import time
import threading
import uuid
import webbrowser
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Iterable, List, TypedDict
from wox_plugin import (
ActionContext, ChangeQueryParam, Context, CopyParams, CopyType,
InvokePluginToolHandlerResult, LogLevel, PluginToolAnnotations, PluginToolDescriptor,
Query, QueryResponse, QueryType, RefreshQueryParam, RegisterPluginToolOption, Result,
ResultAction, ResultTail, ResultTailType, UpdatableResult, WoxImage, WoxImageType,
)
_SDK_CACHE_FOLDER = ""
SCOPE_USER = "user"
SCOPE_GLOBAL = "global"
SEARCH_LIMIT = 50
CACHE_SCHEMA = 1
CREATE_NO_WINDOW = 0x08000000
ANSI_ESCAPE = re.compile(r"(?:\x1b\[[0-?]*[ -/]*[@-~]|\x9b[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[ -/]*[@-~])")
PLUGIN_ICON = "url:https://avatars.githubusercontent.com/u/16618068?s=128"
LIST_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 32 32\"><g fill=\"none\"><path fill=\"url(#scoopListLine)\" d=\"M14 5a1 1 0 1 0 0 2h15a1 1 0 1 0 0-2z\"/><path fill=\"url(#scoopListLine)\" d=\"M13 16a1 1 0 0 1 1-1h15a1 1 0 1 1 0 2H14a1 1 0 0 1-1-1\"/><path fill=\"url(#scoopListLine)\" d=\"M13 26a1 1 0 0 1 1-1h15a1 1 0 1 1 0 2H14a1 1 0 0 1-1-1\"/><path fill=\"url(#scoopListTile)\" d=\"M5 2a3 3 0 0 0-3 3v2a3 3 0 0 0 3 3h2a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3z\"/><path fill=\"url(#scoopListTile)\" d=\"M2 15a3 3 0 0 1 3-3h2a3 3 0 0 1 3 3v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3z\"/><path fill=\"url(#scoopListTile)\" d=\"M5 22a3 3 0 0 0-3 3v2a3 3 0 0 0 3 3h2a3 3 0 0 0 3-3v-2a3 3 0 0 0-3-3z\"/><defs><linearGradient id=\"scoopListLine\" x1=\"10.45\" x2=\"29.466\" y1=\"1.857\" y2=\"26.085\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#36dff1\"/><stop offset=\"1\" stop-color=\"#0094f0\"/></linearGradient><linearGradient id=\"scoopListTile\" x1=\"3.902\" x2=\"8.379\" y1=\"5.722\" y2=\"28.429\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".125\" stop-color=\"#9c6cfe\"/><stop offset=\"1\" stop-color=\"#7a41dc\"/></linearGradient></defs></g></svg>"
SEARCH_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><g fill=\"none\"><path fill=\"url(#scoopSearchFill)\" d=\"M35 21c0 7.732-6.268 14-14 14S7 28.732 7 21S13.268 7 21 7s14 6.268 14 14\"/><path fill=\"url(#scoopSearchRing)\" d=\"M31.204 33.325A15.94 15.94 0 0 1 21 37c-8.837 0-16-7.163-16-16S12.163 5 21 5s16 7.163 16 16c0 3.878-1.38 7.434-3.675 10.203l9.236 9.236a1.5 1.5 0 0 1-2.122 2.122zM34 21c0-7.18-5.82-13-13-13S8 13.82 8 21s5.82 13 13 13s13-5.82 13-13\"/><path fill=\"url(#scoopSearchStarA)\" d=\"m41.232 18.536l1.377.448l.028.007a.544.544 0 0 1 0 1.025l-1.378.448a2.84 2.84 0 0 0-1.798 1.796l-.448 1.377l-.016.04v.009a.544.544 0 0 1-1.01-.039l-.448-1.377a2.84 2.84 0 0 0-1.357-1.61l-.003-.015a3 3 0 0 0-.438-.188l-1.378-.448a.544.544 0 0 1 0-1.025l1.378-.448a2.84 2.84 0 0 0 1.77-1.796l.448-1.377a.544.544 0 0 1 1.027 0l.448 1.377a2.83 2.83 0 0 0 1.797 1.796\"/><path fill=\"url(#scoopSearchStarB)\" d=\"M27.39 11.609a5.36 5.36 0 0 1 1.295 2.105l.846 2.6a1.027 1.027 0 0 0 1.938 0l.846-2.6a5.36 5.36 0 0 1 3.397-3.394l2.602-.845a1.028 1.028 0 0 0 0-1.937l-.052-.013l-2.602-.845a5.36 5.36 0 0 1-3.397-3.394l-.846-2.6a1.027 1.027 0 0 0-1.939 0l-.845 2.6l-.022.064a5.36 5.36 0 0 1-3.323 3.33l-2.602.845a1.028 1.028 0 0 0 0 1.937l2.602.845a5.36 5.36 0 0 1 2.103 1.301\"/><defs><radialGradient id=\"scoopSearchStarA\" cx=\"0\" cy=\"0\" r=\"1\" gradientTransform=\"rotate(63.404 24.537 5.506)scale(51.5503 40.1144)\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".718\" stop-color=\"#ffcd0f\"/><stop offset=\".991\" stop-color=\"#e67505\"/></radialGradient><radialGradient id=\"scoopSearchStarB\" cx=\"0\" cy=\"0\" r=\"1\" gradientTransform=\"rotate(61.2 36.64 -20.64)scale(73.0951 56.9175)\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".698\" stop-color=\"#ffcd0f\"/><stop offset=\".991\" stop-color=\"#e67505\"/></radialGradient><linearGradient id=\"scoopSearchFill\" x1=\"28\" x2=\"7\" y1=\"11.667\" y2=\"35\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#fdfdfd\"/><stop offset=\"1\" stop-color=\"#b3e0ff\"/></linearGradient><linearGradient id=\"scoopSearchRing\" x1=\"7\" x2=\"39\" y1=\"39\" y2=\"13\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#0094f0\"/><stop offset=\"1\" stop-color=\"#29c3ff\"/></linearGradient></defs></g></svg>"
UPDATE_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\"><g fill=\"none\"><path fill=\"url(#scoopUpdateArrow)\" d=\"M16.052 5.029a1 1 0 0 0 .189 1.401a7.002 7.002 0 0 1-3.157 12.487l.709-.71a1 1 0 0 0-1.414-1.414l-2.5 2.5a1 1 0 0 0 0 1.414l2.5 2.5a1 1 0 0 0 1.414-1.414l-.843-.842A9.001 9.001 0 0 0 17.453 4.84a1 1 0 0 0-1.401.189m-1.93-1.736l-2.5-2.5a1 1 0 0 0-1.498 1.32l.083.094l.843.843a9.001 9.001 0 0 0-4.778 15.892A1 1 0 0 0 7.545 17.4a7.002 7.002 0 0 1 3.37-12.316l-.708.709a1 1 0 0 0 1.32 1.497l.094-.083l2.5-2.5a1 1 0 0 0 .083-1.32z\"/><defs><linearGradient id=\"scoopUpdateArrow\" x1=\"16.8\" x2=\"7.2\" y1=\"19.475\" y2=\".5\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#22918b\"/><stop offset=\"1\" stop-color=\"#20ac9d\"/></linearGradient></defs></g></svg>"
INSTALL_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 32 32\"><g fill=\"none\"><path fill=\"url(#scoopInstallBg)\" d=\"M3 7.5A4.5 4.5 0 0 1 7.5 3h17A4.5 4.5 0 0 1 29 7.5v17a4.5 4.5 0 0 1-4.5 4.5h-17A4.5 4.5 0 0 1 3 24.5z\"/><path fill=\"url(#scoopInstallArrow)\" d=\"M22.707 15.293a1 1 0 0 0-1.414 0L17 19.586V10a1 1 0 1 0-2 0v9.586l-4.293-4.293a1 1 0 0 0-1.414 1.414l6 6a1 1 0 0 0 1.414 0l6-6a1 1 0 0 0 0-1.414\"/><defs><linearGradient id=\"scoopInstallBg\" x1=\"3.929\" x2=\"24.357\" y1=\"7.875\" y2=\"24.125\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#36dff1\"/><stop offset=\"1\" stop-color=\"#2764e7\"/></linearGradient><linearGradient id=\"scoopInstallArrow\" x1=\"11.692\" x2=\"23\" y1=\"10.077\" y2=\"34.577\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#fff\"/><stop offset=\"1\" stop-color=\"#b3e0ff\"/></linearGradient></defs></g></svg>"
UNINSTALL_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><path fill=\"#FF8A65\" d=\"M24 21.3L12.7 10L26 1.7L38.3 10z\"/><path fill=\"#FFAB91\" d=\"M24 21.3L12.7 10L17 4.7L38.3 10z\"/><path fill=\"#B39DDB\" d=\"M30.6 44H17.4c-2 0-3.7-1.4-4-3.4L9 11h30l-4.5 29.6c-.3 2-2 3.4-3.9 3.4\"/><path fill=\"#7E57C2\" d=\"M38 13H10c-1.1 0-2-.9-2-2s.9-2 2-2h28c1.1 0 2 .9 2 2s-.9 2-2 2\"/></svg>"
RESET_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\"><g fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\"><path d=\"M3.06 13a9 9 0 1 0 .49-4.087\"/><path d=\"M3 4.001v5h5M11 12a1 1 0 1 0 2 0a1 1 0 1 0-2 0\"/></g></svg>"
HOME_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><g fill=\"none\"><path fill=\"url(#scoopHomeDoor)\" d=\"M18.067 27h12v16h-12z\"/><path fill=\"url(#scoopHomeWall)\" d=\"M26.461 7.855a3.78 3.78 0 0 0-4.787 0L8.499 18.597a3.91 3.91 0 0 0-1.432 3.031v17.485C7.067 41.26 8.78 43 10.892 43h8.175V30.5a2.5 2.5 0 0 1 2.5-2.5h5a2.5 2.5 0 0 1 2.5 2.5V43h8.175c2.113 0 3.825-1.74 3.825-3.887V21.628a3.91 3.91 0 0 0-1.43-3.031z\"/><path fill=\"url(#scoopHomeRoof)\" fill-rule=\"evenodd\" d=\"m24.068 9.329l-16 13.215a2.054 2.054 0 0 1-2.852-.262a1.956 1.956 0 0 1 .267-2.794L22.28 5.628a2.83 2.83 0 0 1 3.523-.024l16.805 13.588a1.957 1.957 0 0 1 .307 2.79a2.054 2.054 0 0 1-2.848.3z\" clip-rule=\"evenodd\"/><defs><linearGradient id=\"scoopHomeDoor\" x1=\"24.067\" x2=\"13.481\" y1=\"27\" y2=\"44.65\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#944600\"/><stop offset=\"1\" stop-color=\"#cd8e02\"/></linearGradient><linearGradient id=\"scoopHomeWall\" x1=\"10.313\" x2=\"45.173\" y1=\"5.24\" y2=\"32\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#ffd394\"/><stop offset=\"1\" stop-color=\"#ffb357\"/></linearGradient><linearGradient id=\"scoopHomeRoof\" x1=\"17.817\" x2=\"25.308\" y1=\".725\" y2=\"22.452\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#ff921f\"/><stop offset=\"1\" stop-color=\"#eb4824\"/></linearGradient></defs></g></svg>"
OPEN_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\"><g fill=\"none\"><path fill=\"url(#scoopFolderA)\" d=\"M8 6.25A2.25 2.25 0 0 1 10.25 4h7.5A2.25 2.25 0 0 1 20 6.25v8.5A2.25 2.25 0 0 1 17.75 17h-7.5A2.25 2.25 0 0 1 8 14.75z\"/><path fill=\"url(#scoopFolderB)\" d=\"M8 6.25A2.25 2.25 0 0 1 10.25 4h7.5A2.25 2.25 0 0 1 20 6.25v8.5A2.25 2.25 0 0 1 17.75 17h-7.5A2.25 2.25 0 0 1 8 14.75z\"/><path fill=\"url(#scoopFolderC)\" d=\"M4 4.25A2.25 2.25 0 0 1 6.25 2h9a2.25 2.25 0 0 1 2.25 2.25v10.5A2.25 2.25 0 0 1 15.25 17h-9A2.25 2.25 0 0 1 4 14.75z\"/><path fill=\"url(#scoopFolderD)\" d=\"M5.25 8A2.25 2.25 0 0 0 3 10.25v8.5A3.25 3.25 0 0 0 6.25 22h11.5A3.25 3.25 0 0 0 21 18.75v-1.5A2.25 2.25 0 0 0 18.75 15h-2.846a.75.75 0 0 1-.55-.24l-5.61-6.04A2.25 2.25 0 0 0 8.097 8z\"/><defs><linearGradient id=\"scoopFolderA\" x1=\"21.8\" x2=\"23.639\" y1=\"19.5\" y2=\"5.773\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#bb45ea\"/><stop offset=\"1\" stop-color=\"#9c6cfe\"/></linearGradient><linearGradient id=\"scoopFolderB\" x1=\"20\" x2=\"17\" y1=\"8.5\" y2=\"8.5\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".338\" stop-color=\"#5750e2\" stop-opacity=\"0\"/><stop offset=\"1\" stop-color=\"#5750e2\"/></linearGradient><linearGradient id=\"scoopFolderD\" x1=\"6.857\" x2=\"6.857\" y1=\"8\" y2=\"27.091\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".241\" stop-color=\"#ffd638\"/><stop offset=\".637\" stop-color=\"#fab500\"/><stop offset=\".985\" stop-color=\"#ca6407\"/></linearGradient><radialGradient id=\"scoopFolderC\" cx=\"0\" cy=\"0\" r=\"1\" gradientTransform=\"matrix(8.775 -11.5 18.53666 14.14428 8.05 14)\" gradientUnits=\"userSpaceOnUse\"><stop offset=\".228\" stop-color=\"#2764e7\"/><stop offset=\".685\" stop-color=\"#5cd1ff\"/><stop offset=\"1\" stop-color=\"#6ce0ff\"/></radialGradient></defs></g></svg>"
COPY_ICON = "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" height=\"80\" viewBox=\"0 0 80 80\"><g fill=\"none\"><path fill=\"#f2c94c\" fill-rule=\"evenodd\" d=\"M30 55V39.57a4 4 0 0 1 1.158-2.816l10.47-10.568a4 4 0 0 1 2.84-1.185H50v-8a4 4 0 0 0-4-4h-8.19L22 13a4 4 0 0 0-4 4v34a4 4 0 0 0 4 4z\" clip-rule=\"evenodd\"/><path fill=\"#f2994a\" fill-rule=\"evenodd\" d=\"M41.73 26.087a4 4 0 0 1 2.739-1.085L57.999 25A4 4 0 0 1 62 29v34a4 4 0 0 1-4 4H34a4 4 0 0 1-4-4V39.57a4 4 0 0 1 1.08-2.734a.667.667 0 0 0 .52 1.086h7.2a4 4 0 0 0 4-4v-7.308a.665.665 0 0 0-1.07-.527\" clip-rule=\"evenodd\"/><path fill=\"#f2f2f2\" d=\"m31.126 36.785l10.537-10.64a.665.665 0 0 1 1.137.468v7.308a4 4 0 0 1-4 4h-7.2a.667.667 0 0 1-.474-1.136\"/></g></svg>"
class WoxPluginBase:
"""Wox plugin base class for script plugins. Do not modify this class."""
class Preview(TypedDict, total=False):
"""Type hint for preview content in a result."""
preview_type: str # "markdown", "text"
preview_data: str
preview_properties: dict[str, str]
class ActionItem(TypedDict, total=False):
"""Type hint for an action in a result."""
id: str
name: str
icon: str
"""
support following icon formats:
- "base64:data:image/png;base64,xxx"
- "emoji:😀"
- "svg:<svg>...</svg>"
- "fileicon:/absolute/path/to/file" (get system file icon)
- "absolute:/absolute/path/to/image.png"
- "url:https://example.com/image.png"
"""
text: str
url: str
path: str
message: str
data: dict[str, str]
class TailItem(TypedDict, total=False):
"""Type hint for a tail in a result."""
id: str
type: str # "text" or "image"
text: str
image: str
contextData: dict[str, str]
class QueryResult(TypedDict, total=False):
"""Type hint for a query result item."""
title: str
subtitle: str
icon: str
"""
support following icon formats:
- "base64:data:image/png;base64,xxx"
- "emoji:😀"
- "svg:<svg>...</svg>"
- "fileicon:/absolute/path/to/file" (get system file icon)
- "absolute:/absolute/path/to/image.png"
- "url:https://example.com/image.png"
"""
preview: WoxPluginBase.Preview
tails: List[WoxPluginBase.TailItem]
score: int
identity_key: str
group: str
group_score: int
actions: List[WoxPluginBase.ActionItem]
class ActionResult(TypedDict, total=False):
"""Type hint for action method return value."""
action: str
message: str
def __init__(self):
self.log_file_path = __file__ + ".log"
def log(self, message: str) -> None:
"""Log message to log file for debugging."""
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = f"[{ts}] {message}"
if self.is_invoke_from_wox():
with open(self.log_file_path, "a", encoding="utf-8") as f:
f.write(f"{message}\n")
else:
print(f"LOG: {message}")
def is_invoke_from_wox(self) -> bool:
"""Check if the script is invoked from Wox."""
return "WOX_PLUGIN_ID" in os.environ
def _build_response(self, result: Any, request_id: Any) -> dict:
"""Build a successful JSON-RPC 2.0 response."""
return {"jsonrpc": "2.0", "result": result, "id": request_id}
def _build_error_response(
self, code: int, message: str, data: Any = None, request_id: Any = None
) -> dict:
"""Build a JSON-RPC 2.0 error response."""
error = {"code": code, "message": message}
if data is not None:
error["data"] = data
return {"jsonrpc": "2.0", "error": error, "id": request_id}
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
"""
Process user queries and return results.
Args:
raw_query: The full raw query string entered by the user
trigger_keyword: The trigger keyword that activated this plugin
command: The command part of the query (after trigger keyword)
search: The search part of the query (after command)
take `wpm install plugin-name` as an example
raw_query: wpm install plugin-name
trigger_keyword: wpm
command: install
search: plugin-name
Returns:
List of result dictionaries
"""
# Default implementation - override in your plugin class
return [
{
"title": "Hello Wox!",
"subtitle": "This is a default result. Override the query method in your plugin class.",
"score": 100,
"actions": [
{"name": "Copy", "id": "copy-to-clipboard", "text": "Hello Wox!"}
],
}
]
def action(self, action_id: str, data: Any) -> None:
"""
Handle action requests (OPTIONAL - only needed for custom actions)
Built-in actions (copy-to-clipboard, open-url, open-directory, notify) are handled
automatically by Wox. You only need to implement this method if you have custom actions.
Note: This method is called as a hook for ALL actions (built-in and custom), so you can
optionally add additional logic for built-in actions if needed.
Args:
action_id: The ID of the action
data: Additional data for the action
"""
# Default implementation - override for custom actions
if action_id == "custom-action":
# Custom action handling logic can be added here
pass
def handle_query(self, params, request_id):
"""Internal method to handle query requests"""
search = params.get("search", "")
trigger_keyword = params.get("trigger_keyword", "")
command = params.get("command", "")
raw_query = params.get("raw_query", "")
results = self.query(raw_query, trigger_keyword, command, search)
return self._build_response({"items": results}, request_id)
def handle_action(self, params, request_id):
"""Internal method to handle action requests"""
action_id = params.get("id", "")
action_data = params.get("data", "")
self.action(action_id, action_data)
return self._build_response({}, request_id)
def run(self):
"""Main entry point for the script plugin"""
# Parse input
if self.is_invoke_from_wox():
# Running from Wox - read from stdin
try:
stdin_text = sys.stdin.read()
except Exception:
return 1
else:
# Manual testing mode
print("Manual mode - please enter query:")
query_input = input()
stdin_text = (
'{"jsonrpc": "2.0", "method": "query", "params": {"query": "'
+ query_input
+ '"}, "id": 1}'
)
# Parse JSON-RPC 2.0 request
try:
request = json.loads(stdin_text)
except json.JSONDecodeError as e:
error_response = self._build_error_response(
-32700, "Parse error", str(e), None
)
print(json.dumps(error_response, ensure_ascii=False))
return 1
# Validate JSON-RPC 2.0 format
if request.get("jsonrpc") != "2.0":
error_response = self._build_error_response(
-32600, "Invalid Request", None, request.get("id")
)
print(json.dumps(error_response, ensure_ascii=False))
return 1
method = request.get("method")
params = request.get("params", {})
request_id = request.get("id")
# Handle different methods
if method == "query":
response = self.handle_query(params, request_id)
elif method == "action":
response = self.handle_action(params, request_id)
else:
# Method not found
response = self._build_error_response(
-32601,
"Method not found",
f"Method '{method}' not supported",
request_id,
)
# Output response
print(json.dumps(response, ensure_ascii=False))
return 0
def _is_admin() -> bool:
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def _paths_equal(left: str, right: str) -> bool:
try:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
except Exception:
return left.lower() == right.lower()
def _valid_scoop_root(path: str | None) -> str | None:
if not path or not os.path.isdir(path):
return None
if os.path.isdir(os.path.join(path, "apps")):
return os.path.abspath(path)
return None
def _load_scoop_config() -> dict[str, Any]:
home = os.environ.get("USERPROFILE") or os.path.expanduser("~")
xdg = os.environ.get("XDG_CONFIG_HOME")
config_path = (
os.path.join(xdg, "scoop", "config.json")
if xdg
else os.path.join(home, ".config", "scoop", "config.json")
)
if not os.path.isfile(config_path):
return {}
try:
with open(config_path, encoding="utf-8") as handle:
data = json.load(handle)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _scoop_command_roots() -> list[str]:
roots: list[str] = []
command = shutil.which("scoop")
if not command:
return roots
directory = os.path.dirname(command)
root = (
os.path.dirname(directory)
if os.path.basename(directory).lower() == "shims"
else directory
)
valid = _valid_scoop_root(root)
if valid:
roots.append(valid)
return roots
def _detect_installations(configured_user: str = "", configured_global: str = "") -> list[dict[str, str]]:
"""Resolve user and global Scoop roots the same way Scoop itself does."""
configured_user = configured_user.strip()
configured_global = configured_global.strip()
config = _load_scoop_config()
home = os.environ.get("USERPROFILE") or os.path.expanduser("~")
global_root = (
_valid_scoop_root(configured_global)
or _valid_scoop_root(os.environ.get("SCOOP_GLOBAL"))
or _valid_scoop_root(str(config.get("global_path") or ""))
or _valid_scoop_root(os.path.join(os.environ.get("ProgramData", r"C:\ProgramData"), "scoop"))
)
user_candidates = [
configured_user,
os.environ.get("SCOOP", ""),
str(config.get("root_path") or ""),
*_scoop_command_roots(),
os.path.join(home, "scoop"),
]
user_root = None
for candidate in user_candidates:
valid = _valid_scoop_root(candidate)
if valid and (global_root is None or not _paths_equal(valid, global_root)):
user_root = valid
break
installations: list[dict[str, str]] = []
if user_root:
installations.append({"scope": SCOPE_USER, "root": user_root})
if global_root and (
user_root is None or not _paths_equal(global_root, user_root)
):
installations.append({"scope": SCOPE_GLOBAL, "root": global_root})
return installations
def _primary_root(installations: list[dict[str, str]]) -> str | None:
return installations[0]["root"] if installations else None
def _apps_path(installation: dict[str, str]) -> str:
return os.path.join(installation["root"], "apps")
def _json_text(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, list) and value and isinstance(value[0], str):
return value[0]
return ""
def _collect_strings(value: Any, acc: set[str]) -> None:
if isinstance(value, str):
text = value.strip()
if not text:
return
acc.add(text)
name = os.path.splitext(os.path.basename(text.replace("\\", "/")))[0]
if name:
acc.add(name)
return
if isinstance(value, list):
for item in value:
_collect_strings(item, acc)
return
if isinstance(value, dict):
for item in value.values():
_collect_strings(item, acc)
def _first_launch_relpath(manifest: dict[str, Any]) -> str:
for key in ("shortcuts", "bin"):
value = manifest.get(key)
if isinstance(value, str):
return value
if isinstance(value, list) and value:
first = value[0]
if isinstance(first, str):
return first
if isinstance(first, list) and first and isinstance(first[0], str):
return first[0]
return ""
def _read_json(path: str) -> Any:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
def _manifest_object(data: Any) -> dict[str, Any] | None:
if isinstance(data, list) and data and isinstance(data[0], dict):
return data[0]
if isinstance(data, dict):
return data
return None
def _iter_installed_apps(
installations: list[dict[str, str]],
) -> Iterable[dict[str, Any]]:
for installation in installations:
apps_dir = _apps_path(installation)
if not os.path.isdir(apps_dir):
continue
try:
names = os.listdir(apps_dir)
except OSError:
continue
for name in names:
app_dir = os.path.join(apps_dir, name)
current_dir = os.path.join(app_dir, "current")
# Scoop uses both prefixed and legacy metadata names across installations.
manifest_path = os.path.join(current_dir, "scoop-manifest.json")
if not os.path.isfile(manifest_path):
manifest_path = os.path.join(current_dir, "manifest.json")
install_path = os.path.join(current_dir, "scoop-install.json")
if not os.path.isfile(install_path):
install_path = os.path.join(current_dir, "install.json")
if not os.path.isfile(manifest_path):
continue
try:
manifest = _manifest_object(_read_json(manifest_path))
install = (
_read_json(install_path)
if os.path.isfile(install_path)
else {}
)
except Exception:
continue
if not manifest:
continue
bucket = ""
if isinstance(install, dict):
bucket = str(install.get("bucket") or "")
launch_rel = _first_launch_relpath(manifest)
launch_path = (
os.path.join(current_dir, launch_rel) if launch_rel else ""
)
yield {
"name": name,
"version": str(manifest.get("version") or "unknown"),
"bucket": bucket or "unknown",
"homepage": _json_text(manifest.get("homepage")),
"description": _json_text(manifest.get("description")),
"scope": installation["scope"],
"root": installation["root"],
"current": current_dir,
"launch": launch_path if os.path.isfile(launch_path) else "",
}
def _cache_path() -> str:
if not _SDK_CACHE_FOLDER:
raise RuntimeError("Wox plugin cache folder is unavailable")
return os.path.join(_SDK_CACHE_FOLDER, "search-index.json")
def _bucket_fingerprint(root: str) -> str:
buckets_dir = os.path.join(root, "buckets")
parts: list[str] = []
if not os.path.isdir(buckets_dir):
return ""
try:
names = sorted(os.listdir(buckets_dir))
except OSError:
return ""
for name in names:
bucket_dir = os.path.join(buckets_dir, name, "bucket")
if not os.path.isdir(bucket_dir):
continue
try:
mtime = int(os.path.getmtime(bucket_dir))
except OSError:
mtime = 0
parts.append(f"{name}:{mtime}")
return "|".join(parts)
def _iter_manifest_files(root: str) -> list[tuple[str, str, str]]:
buckets_dir = os.path.join(root, "buckets")
files: list[tuple[str, str, str]] = []
if not os.path.isdir(buckets_dir):
return files
try:
bucket_names = os.listdir(buckets_dir)
except OSError:
return files
for bucket in bucket_names:
manifest_dir = os.path.join(buckets_dir, bucket, "bucket")
if not os.path.isdir(manifest_dir):
continue
for dirpath, _dirnames, filenames in os.walk(manifest_dir):
for filename in filenames:
if not filename.lower().endswith(".json"):
continue
files.append(
(
os.path.join(dirpath, filename),
bucket,
os.path.splitext(filename)[0],
)
)
return files
def _load_manifest_entry(item: tuple[str, str, str]) -> dict[str, Any] | None:
path, bucket, name = item
try:
manifest = _manifest_object(_read_json(path))
except Exception:
return None
if not manifest:
return None
terms: set[str] = {name}
_collect_strings(manifest.get("name"), terms)
_collect_strings(manifest.get("bin"), terms)
_collect_strings(manifest.get("shortcuts"), terms)
_collect_strings(manifest.get("aliases"), terms)
architecture = manifest.get("architecture")
if isinstance(architecture, dict):
for arch in architecture.values():
if isinstance(arch, dict):
_collect_strings(arch.get("bin"), terms)
_collect_strings(arch.get("shortcuts"), terms)
return {
"name": name,
"version": str(manifest.get("version") or "unknown"),
"bucket": bucket,
"path": os.path.dirname(path),
"file": os.path.basename(path),
"homepage": _json_text(manifest.get("homepage")),
"description": _json_text(manifest.get("description")),
"terms": sorted(terms),
}
def _build_search_index(root: str) -> list[dict[str, Any]]:
files = _iter_manifest_files(root)
if not files:
return []
workers = min(8, max(1, os.cpu_count() or 4))
with ThreadPoolExecutor(max_workers=workers) as pool:
entries = [
entry
for entry in pool.map(_load_manifest_entry, files, chunksize=32)
if entry
]
return entries
def _read_search_index(root: str) -> list[dict[str, Any]] | None:
fingerprint = _bucket_fingerprint(root)
cache_file = _cache_path()
try:
with open(cache_file, encoding="utf-8") as handle:
cache = json.load(handle)
if (
isinstance(cache, dict)
and cache.get("schema") == CACHE_SCHEMA
and cache.get("root")
and _paths_equal(str(cache.get("root")), root)
and cache.get("fingerprint") == fingerprint
and isinstance(cache.get("entries"), list)
):
return cache["entries"]
except Exception:
return None
return None
def _write_search_index(root: str, entries: list[dict[str, Any]]) -> None:
cache_file = _cache_path()
os.makedirs(os.path.dirname(cache_file), exist_ok=True)
tmp_path = cache_file + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as handle:
json.dump(
{
"schema": CACHE_SCHEMA,
"root": root,
"fingerprint": _bucket_fingerprint(root),
"entries": entries,
},
handle,
ensure_ascii=False,
)
os.replace(tmp_path, cache_file)
def _schedule_index_build(root: str) -> None:
"""Build the full bucket index in a detached process so queries stay under timeout."""
if _read_search_index(root) is not None:
return
lock_path = _cache_path() + ".building"
try:
os.makedirs(os.path.dirname(lock_path), exist_ok=True)
lock_fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.close(lock_fd)
except FileExistsError:
return
except OSError:
return
# The persistent SDK host can build the index without starting another Python runtime.
threading.Thread(target=_build_index_main, args=(root,), daemon=True).start()
def _search_by_filename(
root: str, query: str, bucket_filter: str
) -> list[tuple[int, dict[str, Any]]]:
"""Cold-start search that only parses filename matches."""
matches: list[tuple[int, dict[str, Any]]] = []
for path, bucket, name in _iter_manifest_files(root):
if bucket_filter and bucket.lower() != bucket_filter.lower():
continue
score = _match_score(query, name, [name])
if score <= 0:
continue
entry = _load_manifest_entry((path, bucket, name))
if entry:
matches.append((score, entry))
matches.sort(key=lambda item: (-item[0], str(item[1]["name"]).lower()))
return matches[:SEARCH_LIMIT]
def _lookup_latest_version(root: str, name: str, bucket: str) -> str:
buckets_dir = os.path.join(root, "buckets")
candidates: list[str] = []
if bucket and bucket.lower() != "unknown":
candidates.append(os.path.join(buckets_dir, bucket, "bucket", f"{name}.json"))
if os.path.isdir(buckets_dir):
try:
bucket_names = os.listdir(buckets_dir)
except OSError:
bucket_names = []
for bucket_name in bucket_names:
candidates.append(
os.path.join(buckets_dir, bucket_name, "bucket", f"{name}.json")
)
seen: set[str] = set()
for path in candidates:
normalized = os.path.normcase(path)
if normalized in seen or not os.path.isfile(path):
continue
seen.add(normalized)
entry = _load_manifest_entry(
(path, os.path.basename(os.path.dirname(os.path.dirname(path))), name)
)
if entry and entry.get("version"):
return str(entry["version"])
return ""
def _invalidate_search_cache() -> None:
cache_file = _cache_path()
for path in (cache_file, cache_file + ".building", cache_file + ".tmp"):
try:
if os.path.isfile(path):
os.remove(path)
except OSError:
pass
def _match_score(query: str, name: str, terms: list[str]) -> int:
needle = query.lower()
name_lower = name.lower()
if name_lower == needle:
return 100
if name_lower.startswith(needle):
return 90
if needle in name_lower:
return 75
for term in terms:
if needle in term.lower():
return 50
return 0
def _ps_quote(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def _powershell_exe() -> str:
return shutil.which("pwsh") or shutil.which("powershell") or "powershell.exe"
def _scope_arg(scope: str) -> str:
return " --global" if scope == SCOPE_GLOBAL else ""
def _as_data_map(data: Any) -> dict[str, str]:
if isinstance(data, dict):
return {str(key): str(value) for key, value in data.items()}
return {}
def _message_result(
title: str, subtitle: str, icon: str = PLUGIN_ICON
) -> WoxPluginBase.QueryResult:
return {
"title": title,
"subtitle": subtitle,
"icon": icon,
"score": 10,
"actions": [],
}
class ScoopPlugin(WoxPluginBase):
def __init__(self, scoop_home: str = "", scoop_global_home: str = ""):
super().__init__()
self.scoop_home = scoop_home
self.scoop_global_home = scoop_global_home
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
command, search = self._normalize_query(command, search)
installations = _detect_installations(self.scoop_home, self.scoop_global_home)
if not installations:
return [
{
"title": "i18n:missing_title",
"subtitle": "i18n:missing_subtitle",
"icon": PLUGIN_ICON,
"score": 100,
"actions": [
{
"name": "i18n:missing_open",
"id": "open-url",
"icon": OPEN_ICON,
"url": "https://scoop.sh",
}
],
}
]
if command == "list":
return self._query_list(installations, search)
if command == "search":
return self._query_search(installations, search)
if command == "update":
return self._query_update(installations, search)
if search:
commands = self._command_results(trigger_keyword, search)
return commands or self._query_search(installations, search)
updates = self._query_update(installations, "", overview=True)
updated_by_key = {result["identity_key"]: result for result in updates if result.get("identity_key")}
installed = []
for result in self._query_list(installations, ""):
update = updated_by_key.get(result.get("identity_key", ""))
if update is None:
installed.append(result)
continue
# Keep app management actions when the update row replaces its installed row.
update["actions"].extend(
action for action in result.get("actions", [])
if not action.get("data", {}).get("command", "").startswith("scoop update ")
)
for result in updates:
result["group"] = "i18n:group_updates"
result["group_score"] = 100
for result in installed:
result["group"] = "i18n:group_installed"
result["group_score"] = 50
return updates + installed
def _normalize_query(self, command: str, search: str) -> tuple[str, str]:
command = (command or "").strip().lower()
search = (search or "").strip()
if not command and search:
parts = search.split(None, 1)
if parts[0].lower() in {"list", "search", "update"}:
return parts[0].lower(), parts[1] if len(parts) > 1 else ""
return command, search
def _command_results(
self, trigger_keyword: str, search: str
) -> List[WoxPluginBase.QueryResult]:
keyword = trigger_keyword or "scoop"
needle = search.lower()
commands = (
("list", "i18n:cmd_list", LIST_ICON),
("search", "i18n:cmd_search", SEARCH_ICON),
("update", "i18n:cmd_update", UPDATE_ICON),
)
results: List[WoxPluginBase.QueryResult] = []
for name, subtitle, icon in commands:
if needle and needle not in name:
continue
results.append(
{
"title": name,
"subtitle": subtitle,
"icon": icon,
"score": 200,
"actions": [
{
"name": name,
"id": "change-query",
"icon": icon,
"query": f"{keyword} {name} ",
"preventHideAfterAction": True,
}
],
}
)
return results
def _query_list(
self, installations: list[dict[str, str]], keyword: str
) -> List[WoxPluginBase.QueryResult]:
results: List[WoxPluginBase.QueryResult] = []
needle = keyword.lower()
for app in _iter_installed_apps(installations):
name = str(app["name"])
if needle and needle not in name.lower():
continue
title = f"{name} (global)" if app["scope"] == SCOPE_GLOBAL else name
description = str(app.get("description") or "")
subtitle = description or f"{app['bucket']} {app['version']}"
icon = f"fileicon:{app['launch']}" if app.get("launch") else PLUGIN_ICON
actions: List[WoxPluginBase.ActionItem] = []
if app.get("launch"):
actions.append(
{
"name": "i18n:open_app",
"id": "scoop-open-app",
"icon": OPEN_ICON,
"data": {"path": str(app["launch"])},
}
)
actions.append(
{
"name": "i18n:open_dir",
"id": "open-directory",
"icon": OPEN_ICON,
"path": str(app["current"]),
}
)
if app.get("homepage"):
actions.append(
{
"name": "i18n:open_homepage",
"id": "open-url",
"icon": HOME_ICON,
"url": str(app["homepage"]),
}
)
actions.append(
{
"name": "i18n:copy_name",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": name,
}
)
can_mutate = app["scope"] != SCOPE_GLOBAL or _is_admin()
target = f"{app['bucket']}/{name}" if app["bucket"] != "unknown" else name
if can_mutate:
actions.append(
self._run_action(
"i18n:update",
UPDATE_ICON,
f"scoop update {_ps_quote(target)}{_scope_arg(str(app['scope']))}",
str(app["scope"]),
)
)
actions.append(
self._run_action(
"i18n:uninstall",
UNINSTALL_ICON,
f"scoop uninstall {_ps_quote(target)}{_scope_arg(str(app['scope']))}",
str(app["scope"]),
)
)
if app["scope"] != SCOPE_GLOBAL:
actions.append(
self._run_action(
"i18n:reset",
RESET_ICON,
f"scoop reset {_ps_quote(target)}",
SCOPE_USER,
)
)
results.append(
{
"title": title,
"subtitle": subtitle,
"icon": icon,
"identity_key": f"{app['scope']}:{name.lower()}",
"score": _match_score(keyword, name, [name]) if keyword else 80,
"tails": [
{"id": "version", "type": "text", "text": str(app["version"])}
],
"actions": actions,
}
)
if not results:
return [_message_result("i18n:list_empty", keyword or "scoop list")]
results.sort(key=lambda item: item.get("title", "").lower())
return results
def _query_search(
self, installations: list[dict[str, str]], keyword: str
) -> List[WoxPluginBase.QueryResult]:
if not keyword:
return [
_message_result(
"i18n:search_need_keyword",
"i18n:search_need_keyword_sub",
SEARCH_ICON,
)
]
bucket_filter = ""
query = keyword
if "/" in keyword:
bucket_filter, query = keyword.split("/", 1)
bucket_filter = bucket_filter.strip()
query = query.strip() or keyword
if not query:
return [
_message_result(
"i18n:search_need_keyword",
"i18n:search_need_keyword_sub",
SEARCH_ICON,
)
]
root = _primary_root(installations)
if not root:
return [_message_result("i18n:missing_title", "i18n:missing_subtitle")]
cached = _read_search_index(root)
matches: list[tuple[int, dict[str, Any]]] = []
if cached is None:
matches = _search_by_filename(root, query, bucket_filter)
_schedule_index_build(root)
else:
for entry in cached:
if bucket_filter and str(entry.get("bucket", "")).lower() != bucket_filter.lower():
continue
score = _match_score(query, str(entry["name"]), list(entry.get("terms") or []))
if score <= 0:
continue
matches.append((score, entry))
matches.sort(key=lambda item: (-item[0], str(item[1]["name"]).lower()))
matches = matches[:SEARCH_LIMIT]
if not matches:
return [_message_result("i18n:search_empty", keyword, SEARCH_ICON)]
results: List[WoxPluginBase.QueryResult] = []
admin = _is_admin()
installed_apps = list(_iter_installed_apps(installations))
installed_results = {
result["identity_key"]: result
for result in self._query_list(installations, "")
if result.get("identity_key")
}
for score, entry in matches:
name = str(entry["name"])
bucket = str(entry["bucket"])
installed = [
app for app in installed_apps
if str(app["name"]).lower() == name.lower()
and str(app["bucket"]).lower() in {bucket.lower(), "unknown"}
]
if installed:
for app in installed:
key = f"{app['scope']}:{name.lower()}"
installed_result = installed_results.get(key)
if installed_result is None:
continue
result = dict(installed_result)
result["score"] = score
result["tails"] = [*result.get("tails", []), {"type": "text", "text": "i18n:group_installed"}]
results.append(result)
continue
target = f"{bucket}/{name}"
actions: List[WoxPluginBase.ActionItem] = []
actions.append(
{
**self._run_action(
"i18n:install",
INSTALL_ICON,
f"scoop install {_ps_quote(target)}",
SCOPE_USER,
),
"isDefault": True,
}
)
if admin:
actions.append(
self._run_action(
"i18n:install_global",
INSTALL_ICON,
f"scoop install {_ps_quote(target)} --global",
SCOPE_GLOBAL,
)
)
if entry.get("homepage"):
actions.append(
{
"name": "i18n:open_homepage",
"id": "open-url",
"icon": HOME_ICON,
"url": str(entry["homepage"]),
"hotkey": "ctrl+enter",
}
)
actions.append(
{
"name": "i18n:open_manifest",
"id": "open-directory",
"icon": OPEN_ICON,
"path": str(entry["path"]),
}
)
actions.append(
{
"name": "i18n:copy_name",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": name,
}
)
results.append(
{
"title": name,
"subtitle": f"bucket: {bucket}, version: {entry['version']}",
"icon": SEARCH_ICON,
"score": score,
"tails": [
{"id": "version", "type": "text", "text": str(entry["version"])}
],
"actions": actions,
}
)
return results
def _query_update(
self, installations: list[dict[str, str]], target: str, overview: bool = False
) -> List[WoxPluginBase.QueryResult]:
admin = _is_admin()
installed = [
app
for app in _iter_installed_apps(installations)
if str(app["name"]).lower() != "scoop"
]
results: List[WoxPluginBase.QueryResult] = []
if not overview and (target == "*" or not target):
results.append(
{
"title": "i18n:update_scoop",
"subtitle": "i18n:update_scoop_sub",
"icon": UPDATE_ICON,
"score": 100,
"actions": [
self._run_action(
"i18n:update", UPDATE_ICON, "scoop update", SCOPE_USER
)
],
}
)
if any(app["scope"] == SCOPE_USER for app in installed):
results.append(
{
"title": "i18n:update_all_user",
"subtitle": "i18n:update_all_user_sub",
"icon": UPDATE_ICON,
"score": 95,
"actions": [
self._run_action(
"i18n:update",
UPDATE_ICON,
"scoop update --all",
SCOPE_USER,
)
],
}
)
if admin and any(app["scope"] == SCOPE_GLOBAL for app in installed):
results.append(
{
"title": "i18n:update_all_global",
"subtitle": "i18n:update_all_global_sub",
"icon": UPDATE_ICON,
"score": 94,
"actions": [
self._run_action(
"i18n:update",
UPDATE_ICON,
"scoop update --all --global",
SCOPE_GLOBAL,
)
],
}
)
if target == "*":
return results
root = _primary_root(installations)
latest_by_key: dict[tuple[str, str], str] = {}
latest_by_name: dict[str, str] = {}
cached = _read_search_index(root) if root else None
if cached is not None:
for entry in cached:
name = str(entry["name"]).lower()
bucket = str(entry["bucket"]).lower()
version = str(entry["version"])
latest_by_key[(bucket, name)] = version
latest_by_name.setdefault(name, version)
elif root:
_schedule_index_build(root)
updates: list[tuple[dict[str, Any], str]] = []
hidden_global = False
needle = target.lower()
for app in installed:
if needle and needle not in str(app["name"]).lower():
continue
latest = latest_by_key.get(
(str(app["bucket"]).lower(), str(app["name"]).lower())
) or latest_by_name.get(str(app["name"]).lower(), "")
if not latest and root:
latest = _lookup_latest_version(root, str(app["name"]), str(app["bucket"]))
if not latest or latest == app["version"]:
continue
if app["scope"] == SCOPE_GLOBAL and not admin and not overview:
hidden_global = True
continue
updates.append((app, latest))
for app, latest in updates:
name = str(app["name"])
title = f"{name} (global)" if app["scope"] == SCOPE_GLOBAL else name
target_name = f"{app['bucket']}/{name}" if app["bucket"] != "unknown" else name
results.append(
{
"title": title,
"subtitle": f"{app['version']} -> {latest}",
"icon": f"fileicon:{app['launch']}" if app.get("launch") else PLUGIN_ICON,
"identity_key": f"{app['scope']}:{name.lower()}",
"score": _match_score(target, name, [name]) if target else 70,
"actions": [
self._run_action(
"i18n:update",
UPDATE_ICON,
f"scoop update {_ps_quote(target_name)}{_scope_arg(str(app['scope']))}",
str(app["scope"]),
)
] if app["scope"] != SCOPE_GLOBAL or admin else [],
}
)
if hidden_global:
results.append(
_message_result("i18n:update_admin", "i18n:need_admin", UPDATE_ICON)
)
if not updates and not hidden_global:
if target and target != "*":
scoped = [app for app in installed if str(app["name"]).lower() == needle]
if scoped:
for app in scoped:
if app["scope"] == SCOPE_GLOBAL and not admin:
continue
name = str(app["name"])
title = f"{name} (global)" if app["scope"] == SCOPE_GLOBAL else name
results.append(
{
"title": title,
"subtitle": str(app["version"]),
"icon": UPDATE_ICON,
"score": 60,
"actions": [
self._run_action(
"i18n:update",
UPDATE_ICON,
f"scoop update {_ps_quote(name)}{_scope_arg(str(app['scope']))}",
str(app["scope"]),
)
],
}
)
else:
results.append(
{
"title": f"Update {target}",
"subtitle": f"scoop update {target}",
"icon": UPDATE_ICON,
"score": 50,
"actions": [
self._run_action(
"i18n:update",
UPDATE_ICON,
f"scoop update {_ps_quote(target)}",
SCOPE_USER,
)
],
}
)
else:
results.append(
_message_result("i18n:update_none", "scoop update", UPDATE_ICON)
)
if not results:
results.append(
_message_result("i18n:update_none", "scoop update", UPDATE_ICON)
)
return results
def _run_action(
self, name: str, icon: str, command: str, scope: str
) -> WoxPluginBase.ActionItem:
return {
"name": name,
"id": "scoop-run",
"icon": icon,
"data": {"command": command, "scope": scope},
"preventHideAfterAction": True,
}
def _build_index_main(root: str) -> int:
"""Write a full bucket search index, then drop the build lock file."""
lock_path = _cache_path() + ".building"
try:
_write_search_index(root, _build_search_index(root))
return 0
except Exception:
return 1
finally:
try:
if os.path.isfile(lock_path):
os.remove(lock_path)
except OSError:
pass
ACTION_SVGS = {'execute': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--wox-theme-icon-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2 4.5 13.5h5.5L9 22l10-13h-6z"/></svg>', 'copy': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--wox-theme-icon-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg>', 'open': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--wox-theme-icon-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 5h5v5M19 5l-9 9"/><path d="M13 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-7"/></svg>', 'open-containing-folder': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--wox-theme-icon-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>', 'delete': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--wox-theme-icon-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>'}
class ScoopSDKPlugin:
"""Adapt the Scoop query implementation to the persistent Wox SDK host."""
async def init(self, ctx: Context, params) -> None:
global _SDK_CACHE_FOLDER
self.api = params.api
_SDK_CACHE_FOLDER = await self.api.get_cache_folder(ctx)
if not _SDK_CACHE_FOLDER:
raise RuntimeError("Wox plugin cache folder is unavailable")
self.home = await self.api.get_setting(ctx, "scoop_home") or ""
self.global_home = await self.api.get_setting(ctx, "scoop_global_home") or ""
self.messages = {key: await self.api.get_translation(ctx, key) for key in ("running", "starting", "completed", "failed", "already_running")}
self.running = set()
await self.api.on_setting_changed(ctx, self._setting_changed)
await self.api.register_plugin_tool(ctx, RegisterPluginToolOption(
tool=PluginToolDescriptor(
name="list_installed", description="i18n:tool_list",
input_schema={"type": "object", "properties": {}, "additionalProperties": False},
output_schema={"type": "object", "properties": {"packages": {"type": "array", "items": {"type": "object"}}}, "required": ["packages"]},
annotations=PluginToolAnnotations(read_only=True, idempotent=True),
), handler=self._list_installed,
))
async def _setting_changed(self, ctx, key, value):
if key == "scoop_home":
self.home = value
elif key == "scoop_global_home":
self.global_home = value
async def _list_installed(self, ctx, option):
def read():
return [{"name": app["name"], "version": app["version"], "bucket": app["bucket"], "scope": app["scope"]}
for app in _iter_installed_apps(_detect_installations(self.home, self.global_home))]
return InvokePluginToolHandlerResult(output={"packages": await asyncio.to_thread(read)})
async def query(self, ctx: Context, query: Query) -> QueryResponse:
engine = ScoopPlugin(self.home, self.global_home)
rows = await asyncio.to_thread(engine.query, query.raw_query, query.trigger_keyword, query.command, query.search)
# Match Wox's score/title ordering so refresh can select the next update.
updates = sorted(
(row for row in rows if row.get("group") == "i18n:group_updates" and row.get("identity_key")),
key=lambda row: (-row.get("score", 0), len(row["title"].encode("utf-8")), row["title"], len(row.get("subtitle", "").encode("utf-8")), row.get("subtitle", "")),
)
next_ids = {}
if len(updates) > 1:
for index, row in enumerate(updates):
next_ids[row["identity_key"]] = self._result_id(updates[(index + 1) % len(updates)]["identity_key"])
return QueryResponse(results=[self._result(row, next_ids.get(row.get("identity_key", ""), "")) for row in rows])
@staticmethod
def _result_id(identity_key: str) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, "wox:scoop:" + identity_key)) if identity_key else ""
def _result(self, row: dict, next_result_id: str = "") -> Result:
icon_type, _, icon_data = row.get("icon", PLUGIN_ICON).partition(":")
icon = WoxImage(image_type=WoxImageType(icon_type), image_data=icon_data)
actions = []
for item in row.get("actions", []):
kind = item.get("id", "")
verb = "execute" if kind == "scoop-run" else "copy" if kind == "copy-to-clipboard" else "open-containing-folder" if kind == "open-directory" else "open"
if kind == "scoop-run" and item.get("name") == "i18n:uninstall":
verb = "delete"
async def run(ctx, action_context, item=item, next_result_id=next_result_id):
await self._action(ctx, action_context, item, next_result_id)
actions.append(ResultAction(
name=item.get("name", ""), action=run,
icon=WoxImage.new_svg(ACTION_SVGS[verb]),
is_default=bool(item.get("isDefault")),
prevent_hide_after_action=bool(item.get("preventHideAfterAction")),
hotkey=item.get("hotkey", ""),
))
return Result(
id=self._result_id(row.get("identity_key", "")),
title=row.get("title", ""), sub_title=row.get("subtitle", ""), icon=icon,
score=row.get("score", 0), identity_key=row.get("identity_key", ""),
group=row.get("group", ""), group_score=row.get("group_score", 0),
tails=[ResultTail(type=ResultTailType.TEXT, text=t.get("text", "")) for t in row.get("tails", [])],
actions=actions,
)
async def _action(self, ctx, action_context: ActionContext, item: dict, next_result_id: str = "") -> None:
kind = item.get("id", "")
if kind == "scoop-run":
payload = item.get("data", {})
await self._run_command(ctx, action_context.result_id, payload.get("command", ""), payload.get("scope", SCOPE_USER), next_result_id)
elif kind in {"scoop-open-app", "open-directory"}:
path = item.get("data", {}).get("path", "") if kind == "scoop-open-app" else item.get("path", "")
if path:
await asyncio.to_thread(os.startfile, path)
elif kind == "open-url":
await asyncio.to_thread(webbrowser.open, item.get("url", ""))
elif kind == "copy-to-clipboard":
await self.api.copy(ctx, CopyParams(type=CopyType.TEXT, text=item.get("text", "")))
elif kind == "change-query":
await self.api.change_query(ctx, ChangeQueryParam(query_type=QueryType.INPUT, query_text=item.get("query", "")))
async def _run_command(self, ctx: Context, result_id: str, command: str, scope: str, next_result_id: str = "") -> None:
if not command:
return
visible = True
async def report(message: str, tails=None) -> None:
nonlocal visible
if visible:
try:
visible = await self.api.update_result(ctx, UpdatableResult(id=result_id, sub_title=message, tails=tails))
except Exception:
visible = False
async def report_status(message: str, running: bool) -> None:
nonlocal visible
if not visible:
return
try:
current = await self.api.get_updatable_result(ctx, result_id)
if current is None:
visible = False
return
tails = [tail for tail in (current.tails or []) if tail.id != "scoop-running"]
if running:
tails.append(ResultTail(id="scoop-running", type=ResultTailType.TEXT, text=self.messages["running"]))
await report(message, tails)
except Exception:
visible = False
if command in self.running:
await report(self.messages["already_running"])
return
if scope == SCOPE_GLOBAL and not _is_admin():
await report(await self.api.get_translation(ctx, "need_admin"))
return
self.running.add(command)
await report_status(self.messages["starting"], True)
last_line = ""
last_update = 0.0
cache_invalidated = False
try:
env = os.environ.copy()
for installation in _detect_installations(self.home, self.global_home):
env["SCOOP_GLOBAL" if installation["scope"] == SCOPE_GLOBAL else "SCOOP"] = installation["root"]
script = ("[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); "
"$ErrorActionPreference = 'Stop'; try { " + command +
"; if (-not $?) { exit 1 } } catch { Write-Output $_.Exception.Message; exit 1 }")
process = await asyncio.create_subprocess_exec(
_powershell_exe(), "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script,
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
creationflags=CREATE_NO_WINDOW, env=env,
)
while chunk := await process.stdout.readline():
# Scoop and Git can emit terminal control sequences even when output is piped.
line = ANSI_ESCAPE.sub("", chunk.decode("utf-8", errors="replace")).strip()
if not line:
continue
last_line = line
# Scoop repeats the version change before producing actual progress.
if re.fullmatch(r"(?:[^:]+:\s*)?\S+\s*(?:->|→)\s*\S+", line):
continue
now = time.monotonic()
if now - last_update >= 0.15:
await report(line)
last_update = now
code = await process.wait()
if code == 0:
# The refreshed query must see the newly installed version and updated buckets.
await asyncio.to_thread(_invalidate_search_cache)
cache_invalidated = True
await report_status(self.messages["completed"], False)
if visible and (command == "scoop update" or command.startswith("scoop update ")):
try:
await self.api.refresh_query(ctx, RefreshQueryParam(selected_result_id=next_result_id))
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"Failed to refresh Scoop results: {exc}")
else:
await report_status(f"{self.messages['failed']}: {last_line or f'exit {code}'}", False)
except Exception as exc:
await report_status(f"{self.messages['failed']}: {exc}", False)
finally:
self.running.discard(command)
if not cache_invalidated:
await asyncio.to_thread(_invalidate_search_cache)
plugin = ScoopSDKPlugin()
if __name__ == "__main__" and len(sys.argv) >= 3 and sys.argv[1] == "--build-index":
sys.exit(_build_index_main(sys.argv[2]))
@qianlifeng

Copy link
Copy Markdown
Author
screenshot

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