Wednesday, June 17, 2009

Closing the tab that you gestured over

Hey, remember this blog?  I barely do.

I just solved an interesting xGestures problem someone posed to me: how can they get it so that the tab they gesture over is closed, rather than making a gesture type Command-W, thus closing whichever tab is active?  Furthermore, how can they close tabs when Safari is in the background?

To solve it, I wrote an AppleScript that should do exactly that.  Maybe someone else will find it interesting.  The thing to remember about xGestures is that it can have practically any behavior you want by using AppleScript.  The problem is that writing AppleScripts is really only an option for people who are already programmers and have the time and inclination to learn to write them.  So I'll keep posting the interesting ones I write.

Here's the script:

set x to mouse x
set y to mouse y
tell application "Safari"
set targetWindow to {}
set theWindows to the windows
repeat with i from 1 to the count of theWindows
set theBounds to bounds of item i of theWindows
if x ≥ item 1 of theBounds and x ≤ item 3 of theBounds and y ≥ item 2 of theBounds and y ≤ item 4 of theBounds then
if targetWindow ≠ {} then
if index of item i of theWindows <>
set targetWindow to item i of theWindows
end if
else
set targetWindow to item i of theWindows
end if
end if
end repeat
if targetWindow ≠ {} then
close current tab of targetWindow
end if
end tell

This script requires the XTools scripting addition because otherwise there's no way to get the mouse location in an AppleScript.  XTools can be downloaded here: http://osaxen.com/files/xtool1.1.html