Plaintalk 1.4.1: AppleScript for "Universal Quit"

Is it possible to create a universal "Quit" (like Close Window) for any application using PlainTalk?
A first attempt at an AppleScript to quit an application is as simple as the following:


tell application "Finder"
set AppName to name of every process whose frontmost is true
end tell
tell application AppName to quit


Call it "Quit Application", since speech recognition seems to be able to better discern things that are more than one syllable.

This worked fine for most cases. Other cases to handle are desk accessories (not scriptable at all), old applications that do not support the core AppleEvents and the Finder itself. This involved more checking and trapping of errors. Instead of putting up dialogs to display error messages, these additional lines of code will cause the Macintosh to speak the error messages in response to a spoken command.

By adding more error checking, the script evolved into:


property SpeakErrs : true -- false => display dialog

try
  set AppScriptable to false
  set AppName to "the current process" -- initialize from leftover values
  tell application "Finder"

  set ProcName to every process whose frontmost is true
  if ProcName is not {} then --something other than Finder
  set AppName to the name of every process whose frontmost is true
  --kinds are "application program", "desk accessory"
  set ProcKind to kind of file of every process whose frontmost is true
  with timeout of 5 seconds -- sluggish section for unresponsive applications
  if ProcKind is "application program" then
  set AppScriptable to
       the scriptable of file of every process whose frontmost is true
  else
  set Msg to "Sorry, cannot quit " & ProcKind & AppName &
        ". It does not support scripting."
  end if
  end timeout
  else
  set AppName to "Finder"
  set Msg to "You should not quit the Finder."
  end if
  end tell

  -- note: this section operates in the context of the frontmost application
-- in case dialogs are displayed
  if AppScriptable then
  with timeout of 3 seconds
  tell application AppName to quit
  end timeout
  else
  GiveError(Msg)
  end if


on error ErrMsg number ErrNmbr
  -- - 903 = no PPC port; i.e. not scriptable
  -- -2704 = application not scriptable
  if ErrNmbr = -903 or ErrNmbr = -2704 then
  set Msg to AppName &
     " is not scriptable or does not support the quit AppleEvent."
  GiveError(Msg)
  else
  log ("Error " & ErrNmbr & ": " & ErrMsg)
  display dialog "Error " & ErrNmbr & ": " & ErrMsg
  end if
end try

on GiveError(TheMsg)
  if SpeakErrs then
  say TheMsg
  else
  display dialog TheMsg buttons {"OK"} default button 1
  end if
end GiveError

Published Date: Feb 19, 2012