10.5: Fix a Terminal window position AppleScript issue

Dec 16, '08 07:30:00AM

Contributed by: Anonymous

I was trying to use AppleScript to open, title, change directory, and position several Terminal windows. Titling and changing directories wasn't a problem, but there appears to be a bug positioning the windows using set bounds of front window to {x,y,w,h}. I Google'd around for answers and found this page which confirms the bug.

I tried the alternative suggested in the above page to no avail; it was better, but still not positioning the windows exactly where I wanted. I then found this page, and the Unix commands listed there did the trick!

So, I cranked out an AppleScript to achieve what I'd originally set out to do, and it works flawlessly. Here's the commented code; it should be self-explanatory.

-- Check if Terminal is running
tell application "System Events" to set terminalRunning to (name of processes) contains "Terminal"
-- Open Terminal if it's not running
-- Close the window that opens automatically
tell application "Terminal"
  if terminalRunning = false then
    activate
    close window 1
  end if
end tell

-- Call newWindow sub-routine
-- Usage:
-- newWindow(winName,newPath,x,y,w,h)
--
-- winName - Sets the window name
--      set to "" for no name
--
-- newPath - Unix format path to change directory to
--      set to "" to open your default location
--
-- x - x position in pixels
-- y - y position in pixels
-- w - width in pixels
-- h - height in pixels

-- Example usage:

set winId to newWindow("my terminal window", "/", 0, 0, 650, 380)

--  The following line clears the terminal window.
-- (NB, 'Enable access for assistive devices' needs to be ticked in the Universal Access System Preference)

tell application "System Events" to tell process "Terminal" to keystroke "k" using command down

-- The above two lines can be repeated in order to open multiple windows with different titles and positions


-- newWindow sub-routine

on newWindow(winName, newPath, x, y, w, h)
  tell application "Terminal"
    activate
    set positionScript to "echo -en '\\E[3;'" & x & "';'" & y & "'t'"
    set positionScript to positionScript & ";echo -en '\\E[4;'" & h & "';'" & w & "'t'"
    if newPath is not equal to "" then
      if newPath is not equal to "~" then
        set newPath to the quoted form of newPath
      end if
      set positionScript to positionScript & ";cd " & newPath
    end if
    do script positionScript
    set a to get id of front window
    if winName is not equal to "" then
      set custom title of tab 1 of window id a to winName
    end if
    
  end tell
  return a
end newWindow
I hope it's of use to someone...

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20081214133755694