Swift - get file path of open document in another application
I am trying to get the file path of an open document from another application using swift code. I know how to do it in AppleScript, 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 one option is to run this script from within my program, but I was hoping to find another way to do this, perhaps without using Accessibility.
In my application, I can get the application as 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 when I do this. Any help would be greatly appreciated.
source to share
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 an AXDocument like AppleScript does. It will still be open to other ways to do this, which might be better or not using Accessibility.
source to share