PDA

View Full Version : Need help with Applescript to manage Finder windows




asmilingknight
Jul 10, 2013, 11:27 PM
I'm trying to make an applescript that does the following:

1. check how many open finder windows there are (if any)
2. if there are finder windows open then cycle through them when the script is run.
3. if there aren't any open finder windows make a new one.


This is what I've come up with so far:


property finderwindownumber : 1
tell application "Finder"
set TotalNumberOfFinderWindows to (count of (every window where visible is true))
if TotalNumberOfFinderWindows is greater than 0 then
tell application "Finder"
select window finderwindownumber
activate
set finderwindownumber to finderwindownumber + 1
if finderwindownumber is greater than TotalNumberOfFinderWindows then
set finderwindownumber to 1
end if
end tell
else
tell application "Finder" to open home
end if
end tell


I've managed to get the Finder Windows to activate incrementally (window 1, then 2, then 3, etc.) as they should. But when it reaches the maximum limit of finder windows it resets the value of the last finder window to the first one, and then procedes to activate them in a decremental fashion. (first window 3, then 2, then 1). I would like to make them cycle again back to the first window and so on.

I could use some help with this,
Thank you in advance.



HexMonkey
Jul 11, 2013, 03:22 AM
The windows are indexed by their order, so as you activate windows and change their order, their indices change accordingly, resulting in the problem you have.

The simplest fix would be to always activate the backmost window (ie, "select window TotalNumberOfFinderWindows"). This would initially select the windows in the opposite order to what you have on the first cycle, but would always cycle in the same way.

If the initial order is important, you could cap finderwindownumber to TotalNumberOfFinderWindows rather than resetting it to 1, ie:
if finderwindownumber is less than TotalNumberOfFinderWindows then
set finderwindownumber to finderwindownumber + 1
end if

After the first cycle, it will always cycle in the same way again since the back window is the one that was activated TotalNumberOfFinderWindows events ago.

The exception is if the user activates/closes/opens windows in between runs. If you want to maintain the order when this happens, you could store a list of the window IDs (eg "set windowIDs to id of (every window where visible is true)") and use that stored list to determine the order.