app.context - 上下文 API
访问 Finder 选择上下文和插件目录信息。
和菜单处理函数收到的
context参数不是一回事。> function MyPlugin:handleAction(context) > local files = context.selectedFiles -- 属性,本次点击的快照 > local files = app.context.selectedFiles() -- 函数,此刻现查 > end > ``` > > - **处理函数的 `context` 参数**:菜单**被点击那一刻**的快照,只有 > `selectedFiles` 和 `currentDirectory` 两个属性。处理函数里优先用它—— > 它保证和用户看到的选中状态一致。 > - **`app.context.*` 全局 API**:调用时**现场查询**。用在处理函数之外的地方, > 比如 `getMenuTitle`、后台定时任务、协程里——那些场合拿不到 `context` 参数。 > > 长任务执行到一半时用户可能已经改了选中,那种情况下两者会不一致; > 要的是"用户点的时候选了什么",就用参数。 > **权限**:L0 安全 — 无需声明,始终可用 ## 方法 ### app.context.selectedFiles() 获取 Finder 中选中的文件路径。 **返回值**: `table` - 绝对路径数组 ```lua local files = app.context.selectedFiles() for _, path in ipairs(files) do app.log.info(path) end
app.context.currentDirectory()
获取当前 Finder 窗口的目录。
返回值: string - 目录路径
local dir = app.context.currentDirectory()
-- "/Users/username/Documents"
app.context.pluginsDirectory()
获取插件安装目录。
返回值: string - 目录路径
local dir = app.context.pluginsDirectory()
-- "~/Library/Group Containers/group.net.ymlab.iRightMenu.pro/Plugins"
app.context.pluginDirectory()
获取当前插件的目录。
返回值: string - 目录路径
local dir = app.context.pluginDirectory()
-- "~/Library/Group Containers/.../Plugins/com.example.my-plugin"
-- 读取插件资源文件
local configPath = app.path.join(dir, "config.json")
示例
处理选中文件
function MyPlugin:handleAction(context)
local files = app.context.selectedFiles()
local dir = app.context.currentDirectory()
app.log.info("当前目录: " .. dir)
app.log.info("选中文件数: " .. #files)
for i, file in ipairs(files) do
app.log.info("文件 " .. i .. ": " .. file)
end
end
读取插件配置
function MyPlugin:loadConfig()
local pluginDir = app.context.pluginDirectory()
local configPath = app.path.join(pluginDir, "config.json")
if app.file.exists(configPath) then
local content = app.file.read(configPath)
return app.json.parse(content)
end
return {}
end