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 - 绝对路径数组
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")
只读。 这里是随插件包分发的内容,升级时整个目录会被替换掉。 往这里写东西,轻则升级后丢失,重则改动了随包文件导致签名校验失败。 要写入请用下面的
dataDirectory()。
app.context.dataDirectory()
获取当前插件自己的可写目录(since 1.3.0)。缓存、数据库、状态文件都放这里。
返回值: string - 目录路径;失败时返回 nil, error
目录会在首次调用时自动创建。它跟安装目录是两个地方,因此:
- 升级插件不会清空它 —— 这正是它存在的理由
- 卸载插件会连同它一起删除
- 开启 iCloud 备份后,它会被一并备份和恢复
app.settings 的数据本来就存在这个目录下,不需要你自己管。
local dataDir = app.context.dataDirectory()
-- "~/Library/Group Containers/group.net.ymlab.iRightMenu.pro/PluginData/com.example.my-plugin"
-- 攒一份缓存,升级后还在
local cachePath = app.path.join(dataDir, "cache.json")
app.file.write(cachePath, app.json.stringify(myCache))
失败只会发生在拿不到插件上下文的场合(比如在插件生命周期之外调用), 正常插件代码里不会遇到,但照例要接住:
local dataDir, err = app.context.dataDirectory()
if not dataDir then
app.log.error("拿不到数据目录: " .. tostring(err))
return
end
示例
处理选中文件
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.path.exists(configPath) then
local content = app.file.read(configPath)
return app.json.parse(content)
end
return {}
end