Search code examples
swiftxcodemacosaccessibilityaxuielement

Swift - Get file path of currently opened document in another application


I am attempting to get the file path of an open document from another application using swift code. I know how to do it in AppleScript, which is like this:

tell application "System Events"

if exists (process "Pro Tools") then

    tell process "Pro Tools"

        set thefile to value of attribute "AXDocument" of window 1

    end tell

end if

end tell

This AppleScript does what I want, but I was hoping to do it natively in Swift. I know that one option is to run this script from my program, but I was hoping to find another way of doing it, potentially without using Accessibility.

In my app I can get the application as a AXUIElement by doing the following:

let proToolsBundleIdentifier = "com.avid.ProTools"
let proToolsApp : NSRunningApplication? = NSRunningApplication
        .runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?


if let app = proToolsApp {
    app.activate(options: .activateAllWindows)
}


if let pid = proToolsApp?.processIdentifier {   
    let app = AXUIElementCreateApplication(pid)
}

I'm just not sure what to do with the AXUIElement once I make it. Any help would be greatly appreciated.


Solution

  • Thanks to the help of another post from @JamesWaldrop, I was able to answer this myself and wanted to post here for anyone looking for something similar:

    let proToolsBundleIdentifier = "com.avid.ProTools"
    let proToolsApp : NSRunningApplication? = NSRunningApplication
            .runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?
    
    
    if let pid = proToolsApp?.processIdentifier {
    
        var result = [AXUIElement]()
        var windowList: AnyObject? = nil // [AXUIElement]
    
        let appRef = AXUIElementCreateApplication(pid)
        if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success {
                result = windowList as! [AXUIElement]
        }
    
        var docRef: AnyObject? = nil
        if AXUIElementCopyAttributeValue(result.first!, "AXDocument" as CFString, &docRef) == .success {
            let result = docRef as! AXUIElement
            print("Found Document: \(result)")
            let filePath = result as! String
            print(filePath)
        }
    }
    

    This gets the AXDocument just like the AppleScript does. Would still be open to other methods of doing this that may be better or not using Accessibility.