如何获取应用程序打开的 window 文件的路径?

How do I get the path to the file of an open window of an application?

我想编写一个 AppleScript,它在与我当前打开的文件相同的目录中创建一个新文件(在本例中,在应用程序 TexShop 中)。

如果我能得到路径,那么我可以编写如下脚本:

set thePath to get path to open window / tell TexShop to get path...?

set response to display dialog "Some text:" default answer ""

set toWrite to text returned of response

tell application "Finder" to set newFile to make new file at thePath

set openFile to open for access file (newFile as string) with write permission

write toWrite to openFile starting at eof

我最终只是在寻找一种方法来根据不断变化的情况指定文件的位置,也就是说,当我在不同目录中处理不同文件时。

以下 AppleScript 代码应该有助于实现获取最前面应用程序中最前面文档的路径及其包含文件夹的路径的目标。

(* The Delay Command  Gives You Time To Bring The Desired App To The Front
Mainly For Use While Testing This Code In Script Editor.app *)

delay 5 -- Can Be Removed If Not Needed

tell application (path to frontmost application as text) to ¬
    set documentPath to (get path of document 1) as POSIX file as alias

tell application "Finder" to set containingFolder to container ¬
    of documentPath as alias

这是一种应该涵盖可编写脚本和不可编写脚本的应用程序的技术,但需要注意的是,它显然不能 return 开发人员未通过辅助功能挂钩提供的信息。但是,如果它是可脚本化的,或者如果开发人员选择公开应用程序数据以实现可访问性,那么这将提供超出 AppleScriptable 软件不断减少的圈子之外的一点额外范围:

tell application id "com.apple.systemevents" to tell (the first process ¬
    where it is frontmost) to tell (a reference to the front window) ¬
    to if it exists then tell its attribute "AXDocument"'s value to ¬
    if it is not in [missing value, "file:///Irrelevent"] then ¬
        return my (POSIXPathOfFolder for it)

false

on POSIXPathOfFolder for (fileURL as text)
    local fileURL

    set fp to "/tmp/rw" as «class furl»
    close access (open for access fp)
    set eof of fp to 0
    write the fileURL to fp
    read fp as «class furl»
    POSIX path of (result & "::" as text)
end POSIXPathOfFolder

我也尽可能避免使用 Finder,因为它速度慢、有缺陷且易变。底部的处理程序使用标准添加和内置功能来获取检索到的文档路径的包含文件夹。

如果文档路径不可用,脚本 returns false.