Finding the File Path for the Front Document in the Front Application

Hey Mike,

Okay, first problem solved.

The proper format for an alias in AppleScript is (note the quotes):

alias "Macintosh SSD:Users:mikekentdavies:Desktop:Blank MS 9 staves.tif"

But — Keyboard Maestro does NOT understand aliases — it understands POSIX Paths.

Keyboard Maestro munges AppleScript-Objects when it returns them as plain-text, so for instance you cannot return a list-object from AppleScript to Keyboard Maestro and then use it without any other processing.

This italicized portion of the quote is what my script above is designed to do.

To alter it to choose a file if the current working file is NOT found is simple:

------------------------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2017/05/22 15:10
# dMod: 2017/05/29 14:16
# Appl: System Events
# Task: Attempt to acquire the POSIX Path of the file associated with the front window of the front app.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @ASObjC, @System_Events, @Acquire, @POSIX_Path, @Path, @File, @Associated, @Front, @Window, @Front_App
------------------------------------------------------------------------------

use framework "Foundation"
use scripting additions

try
   
   tell application "System Events"
      set frontProcess to first process whose frontmost is true
      set procName to name of frontProcess
      tell frontProcess
         tell front window
            tell attribute "AXDocument"
               set fileUrlOfFrontWindow to its value
            end tell
         end tell
      end tell
   end tell
   
on error
   set fileUrlOfFrontWindow to missing value
end try

if fileUrlOfFrontWindow ≠ missing value and fileUrlOfFrontWindow ≠ "file:///Irrelevent" then
   set posixPath to (current application's class "NSURL"'s URLWithString:fileUrlOfFrontWindow)'s |path|() as text
   return posixPath
else
   set theFile to POSIX path of (choose file)
end if

------------------------------------------------------------------------------

-Chris