Zoom Frontmost Window to Centre Top

Description

Finds the topmost window, and presses the zoom button. Seems easy, doesn't it.

The Code

(*
 * This script attempts to give you a 'reasonable' size window regardless of your screen,
 * and/or application.  It does this by triggering the 'zoom' event on the window.  This event
 * is 'smart', and will attempt to make the window just the right size for the contents.  Mostly
 * this works reasonably well, and with Safari, which is why I originally wrote it, this works
 * quite well.
 *
 * This works very well as a Service created with Automator.
 *)


-- find the frontmost application window
tell application "System Events"
    set frontApp to first application process whose frontmost is true
end tell

-- Zoom the window, so it's a 'reasonable' size
tell application (name of frontApp)
    -- set the size of the window appropriately for the current Web page
    set zoomed of window 1 to false
    set zoomed of window 1 to true
    (* The pair of lines above is very strange, so here's what's going on: First you make the window smaller, then you make it the right size for the Web page.  This is the way the 'Zoom' feature works.  It's not a scripting issue. *)
end tell

--calculate the dimensions of the desktop
tell application "Finder"
    set dimensions to bounds of window of desktop
    set screenWidth to item 3 of dimensions
    set screenHeight to item 4 of dimensions
end tell

--calculate the centre
tell application (name of frontApp)
    set fSize to bounds of window 1
    set wLeft to item 1 of fSize
    set wTop to item 2 of fSize
    set wRight to item 3 of fSize
    set wBottom to item 4 of fSize
   
    set windowWidth to wRight - wLeft
    set windowHeight to wBottom - wTop
   
    -- calculate the corner locations of all four corners
    -- I'm doing it this way just to be pedantic.  The 'set bounds' line could include all of this. ...cb
    set x1 to ((screenWidth - windowWidth) / 2.0) -- left
    set x2 to ((screenWidth + windowWidth) / 2.0) -- right
    set y1 to 22 -- top, allowing for the menu bar. The finder will otherwise go under the menu bar.  Note that this is wrong for the Finder, and I don't know why - try it.
    set y2 to (windowHeight + 22) -- bottom
   
    set bounds of window 1 to {x1, y1, x2, y2}
end tell