How to determine which application launched automator service

applescriptautomator

Is there a way to determine which application launched a Automator Service?

The idea is to check the app that launched the service, with a shell/apple script and react differently depending which app it was.

EDIT:

So when I do something like this…

Launching service

the service, created in Automator, can tell which application was that it was launched from.

EDIT2:

The solution suggested, to query for the front most app using Applescript, while a possible solution is far from ideal. It seems to me that if the system is busy or there are delays in the launching of the workflow, it could return the wrong app and confuse the workflow.

Best Answer

Buscar's comment made me check the process hierarchy and it turns out, a service is a sub-sub-sub process of the application that launched it.

Application and it's service

So, even though in many cases, a query for the frontmost application may be ok, I think looking at the process tree is better.

Here is some sample code from a test Service Workflow that for me appears to work every time...

on run {input, parameters}

    set arpid to (do shell script "echo $PPID")
    display dialog "Automator Runner PID is: " & arpid

    set srpid to (do shell script "ps -o ppid -p " & arpid & " | tail -1")
    display dialog "Service Runner PID is: " & srpid

    set appid to (do shell script "ps -o ppid -p " & srpid & " | tail -1")
    display dialog "Application PID is: '" & first word of appid & "'"

    tell application "System Events"
        set activeApp to (name of first process whose unix id is (appid as integer))
    end tell

    display dialog activeApp

    return input
end run