Revealing a Finder window regardless of space assignment in cur. space

Hello!

I hate it, when I am to get a finder window up in the space I am working on, and I have to go to another space and drag it over, or go looking for it, if I have set “When switching to an application, take me to a space with open windows for the application” turned off or unchecked.

I also want to tell that I use the function cycle through windows Ctrl -F4 / Shift Ctr F4 to move back and forth between windows while I work. It may not be perfect, and I may have to click on windows, to get them into the loop so to speak, but it works perfeclty after a couple of clicks, as long as the applications are well behaved.

It is kind of hard to press Shift Ctrl F4 and Ctrl F4 so I have used a nice utility called KeyRemap4MacBook to put the function onto the key F12 as well, with the added functionality of having one extra Control key when hold down.

The KeyRemap4MacBook is free and can be found here: http://pqrs.org/macosx/keyremap4macbook/

The programmer was so kind as to provide me with the necessary Xml to obtain this functionality, I have pasted it here:

[code]<?xml version="1.0"?>


F12 duplicates control+F4 or is just control_L when held down

	<identifier>private.F12forctrlF4</identifier>
	<autogen>--HoldingKeyToKey-- KeyCode::F12, KeyCode::F4,ModifierFlag::CONTROL_L, KeyCode::VK_NONE, KeyCode::CONTROL_L</autogen>
</item>

[/code]
Well, here goes the code for getting a Finder window into your current space if it is not there:[/b] it is reusing windows, so if the window is in another space, then it will get it for you, and every other window as well.

You know what to do after that! :slight_smile:

The code below works because I have configured Finder to show the posix paths in the title bar I think

You have to enter this in your terminal window, it should work for Leopard and later, but I used to have it this way
in Tiger as well.

defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES killall Finder
You can read more about that here:http://hints.macworld.com/article.php?s . 1210524604

Edit I have removed one errant and some superfluos lines.

I also want to state, that sometimes the Finder window, won’t show up as visible, ant that is because some other window is in front, but hitting ctrl F4 brings it to the foreground. This as an alternative to getting all the Finder Windows in front.



openFinderWindowInThisSpace of me for "My Hd:Users:Me:My Project Folder"



to openFinderWindowInThisSpace for folderName
    set foundIt to false
    
    if openFinderWindow of me for folderName then
        
        if not character 1 of folderName is "/" then
            set pxName to (POSIX path of folderName as text)
        else
            set pxName to folderName
            set folderName to POSIX file pxName as text
        end if
        set pxName to characters 1 thru -2 of pxName as text

        -- check with system events 
        tell application "System Events" to tell process "Finder"
            set wnNames to (get name of its every window) as list
        end tell
        
        -- we see if the window name has turned up in this space
        repeat with awName in wnNames
        
            if contents of awName is pxName then
                set foundIt to true
                exit repeat
            end if
        end repeat
    
            if not foundIt then removeFindersSpaceAssignment()
            
    else
        error folderName & "is not a valid folder specifier"
        
    end if
    if foundIt then
        tell application "Finder" to open folder folderName
        -- we had it in our space
    
        tell application "System Events" to tell application process id "com.apple.finder"
                 -- We tickle the Finder window, to make it colourful and active when we leave
            key down control
            key code 118
            key up control
            delay 0.1
        end tell
    else
        tell application "Finder" to activate
    end if
end openFinderWindowInThisSpace



on removeFindersSpaceAssignment()
    -- not made by Me, but by : Jesse Newland
    -- The scripts he has made for Spaces can be found here: 
    -- http://jnewland.github.com/articles/2007/11/22/spaces-application-assignments-and-applescript/
    
    setFindersSpaceAssignment(65544)
    -- 65544 is the code for being assigned to every space 
    
end removeFindersSpaceAssignment

on setFindersSpaceAssignment(spaceNumber)
    -- not made by Me, but by : Jesse Newland
    -- The scripts he has made for Spaces can be found here: 
    -- http://jnewland.github.com/articles/2007/11/22/spaces-application-assignments-and-applescript/
    
    set app_construct to (run script "{|" & "com.apple.finder" & "|:" & spaceNumber & "}")
    
    
    tell application "System Events"
        tell spaces preferences of expose preferences
            set app_layout to application bindings
        end tell
    end tell
    set app_identifier to bundle identifier of (info for (path to frontmost application))
    try
        app_layout as number -- causes an error anyway
    on error errstr
        set app_locations to {}
        set {TID, text item delimiters} to {text item delimiters, "{"}
        set errstr to text item 2 of errstr
        set text item delimiters to "}"
        set errstr to text item 1 of errstr
        set text item delimiters to ", "
        set errstr to text items of errstr
        set text item delimiters to TID
        repeat with i in errstr
            set o to offset of "|:" in i
            tell i
                set app_location to {}
                set end of app_location to text 2 thru (o - 1)
                set end of app_location to text (o + 2) thru -1
                set end of app_locations to app_location
            end tell
        end repeat
    end try
    set spaces_bindings to {}
    repeat with i from 1 to count app_locations
        if "com.apple.finder" = item 1 of (item i of app_locations) then
            --skip it
        else
            set spaces_bindings to spaces_bindings & (run script "{|" & item 1 of (item i of app_locations) & "|: " & item 2 of (item i of app_locations) & "}")
        end if
    end repeat
    tell application "System Events"
        tell expose preferences
            tell spaces preferences
                set application bindings to spaces_bindings
                set spaces_bindings to app_construct & spaces_bindings
                set application bindings to spaces_bindings
            end tell
        end tell
    end tell
    
    
end setFindersSpaceAssignment


to openFinderWindow for folderName
    
    tell application "Finder"
        set aw to (get its every Finder window) as list
        set hw to {}
        set failed to false
        try
            set aliasOfit to folderName as alias
        on error
            try
                set aliasOfit to (POSIX file folderName as text) as alias
            on error
                set failed to true
            end try
        end try
        repeat with w in aw
            if (target of w as alias) is aliasOfit then
                copy w to end of hw
                exit repeat
            end if
        end repeat
        if not hw is {} then
            select item 1 of hw
        else
            open aliasOfit
        end if
    end tell
    return not failed
end openFinderWindow


Hello!

There were one very smart guy here who often used the word “compromise” often.

My previous solution to the problem of getting the finder windows into the current space, was later as I discovered, based on a lack of knowledge on how the spaces, and spaces preferences operate.

Since then, I have taken a “methodlogical approach” dissecting the various combinations of settings between the “autoswoosh” system defaults setting, the checkbox probably marked named “Switch to a space that has open windows for the program”, from Snow Leopard onwards I believe, and the three possible combinations of program assignment in the preferences pane, namely “unassigned”, “assigned to a Space”, and “assigned to all spaces”.

There is one problem though, and that is bringing up the preference pane and clicking off the checkbox. Or reading it from Expose’s preferences pane, at least for me it is.

Sometimes, I like to go to the last open window in an app. As a matter of fact, I like that most of the times, because then I go back to where I left off. So that behaviour by that checkbox is just splendid.

The problem starts when I want to open a window in my current space. If an app is then assigned to one particular space, then I will be dragged into that apps space. But if the app is Stellarium for instance, then that behaviour is absolutely fine, but not for Finder, which I have many uses for.

So, for applications like Stellarium, that are assigned to one particular space, the solution is really to go to that space, and drag the window over, should you need one.

The intended usage of this script is to open a project folder, or folders that you open regularily with the help of scripts, ensuring that it shows up, where it should, regardless of which space you are in, and ensuring that you don’t get a whole slew of open finder windows to that folder. This makes it also easy for you to just run the script again, when you want that window up front, without having to go looking for it!

The solution for Finder, is to not have it assigned to any space at all!
This setting lets you create a window in the current space, without

The setting, assign to all spaces, are really most useful for apps that you want to have nearby at all times, often not consisting of one window.

I have my terminal window like that, shared among all workspaces, and that works well for Me.

What the new solution does

When your system are configured a little bit different, should it deviate, which I doubt, then this new solution for getting windows into your current space work quite nicely. It actually creates a copy of the window in yoru current space, and closes the old one, in the other space. leaving your screen and other finder windows in the same state as they were before, apart from that new finder window, having become active in your current space.

How it works

When Finder is unassigned, then it will behave like it was bound, with regards to the jumping to the space where it has open windows, whether you jump directly, or jumpt to it by selecting a window, (see below). My script can then also make a new window in the space you are currently in, so what it does, is cloning the window, its view, and properties, size and position, and leaves it in exactly the same position in the space you are currently in.

This is a lightweight solution to that problem, but not simpler than necessary!

Assumptions

I assume that you, like me, likes to be taken directly to a space when you switch applications, or that you like to go to a where a window is, when you select it.

For the first condition to kick in, the result value of the line defaults read com.apple.Dock workspaces-auto-swoosh
must deliver 1. If it is 0 or -1 you will have to execute the line.

defaults write com.apple.Dock workspaces-auto-swoosh -bool YES;killall Dock

For the second condition to kick in, you must have unchecked the check box “Switch to a space that has open windows for the program” (This is something that is left for you to decide on the fly, all the time, this script will never mess with that, nor will it leave you with the auto-swoosh setting in an unaltered state.

That you have Finder set up unassigned in the spaces preferences.

Just run the scriptlet below to go directly in and change it.

do shell script "/Applications/Utilities/Spaces.app/Contents/MacOS/Spaces 1"

About this new solution:

It makes a less mess of your windows.

If it detects that Finder are assigned to a space, or all spaces, then it will tell you that Finder must be unassigned to all spaces, fire up the spaces preferences pane, and quit. leaving it up to you to decide where to collect all its open windows. I know it is unconvenient, but this will happen just once, and it will leave Finder no different to work with than it was before really, should Finder have been assigned to a space. And it will feel so much better when Finder is unassigned from all spaces, when you are working with projects only requiring a couple of folders.

Enjoy!


(*

 The Idea and implementation and any faults is totally mine.
© McUsr 20102012 and put in the Public Domain.  Under  the
terms of BSD 2.0 License
 The usually guarrantees about nothing what so ever applies,
use it at your own risk.
 Read the documentation.  You are not allowed to  post  this
code  elsewhere, but may of course refer to the post at mac
scripter.net. http://macscripter.net/viewtopic.php?id=39064
Under the terms of BSD 2.0 License plus below

if you use this in your own stuff then reefer to my code  by
a  link to MacScripter.net The sole reason for this, is that
it is so much better for all of us  to  have  a  centralized
codebase  which  are updated, than having to roam the net to
find any usable snippets. Which some of us probabaly  origi
nated in the first hand.

Under  no circumstances shall you post this code on its own,
without being corporated into something of yours. But if you
do,  then it would be nice to see that code as well, here at
Macscripters!

The above paragraphs are also valid if you violate any of my
terms.

If  you use this or have advantage of this code in a profes
sional setting, where professional setting  means  that  you
use this code to earn money by keeping yourself more produc
tive. Or if you as an employee share  the  resulting  script
with  other  coworkers,  enhancing  the productivity of your
company, then a modest donation to MacScripter.net would  be
appreciated.

©   McUsr   2010   and   put  in  Public  Domain  see:  mac
scripter.net/viewtopic.php?id=33758 for reference and  terms
of use.

Parts of this code copyright jonn8 the routines for figuring
out the space bindings. 
( http://macscripter.net/viewtopic.php?id=23453 )

*)


property scriptTitle : "Open Finder Window in Current Space"



openFinderWindowInThisSpace of me for "My Hd:Users:Me:My Project Folder"



to openFinderWindowInThisSpace for folderName
    global infoIconFile, fw, wnNames
    set foundIt to false
    
    if openFinderWindow of me for folderName then
        
        if not character 1 of folderName is "/" then
            set pxName to (POSIX path of folderName as text)
        else
            set pxName to folderName
            set folderName to POSIX file pxName as text
        end if
        set pxName to characters 1 thru -2 of pxName as text
        
        -- check with system events 
        tell application "System Events" to tell process "Finder"
            set wnNames to (get name of its every window) as list
        end tell
        
        -- we see if the window name has turned up in this space
        repeat with awName in wnNames
            
            if contents of awName is pxName then
                set foundIt to true
                exit repeat
            end if
        end repeat
        set mustConfigure to false
        if not foundIt then
            set a to get_space_binding_for_application("com.apple.finder")
            if a is not 0 then
                set mustConfigure to true
                unAssignFinderDialog()
                try
                    do shell script "/Applications/Utilities/Spaces.app/Contents/MacOS/Spaces 1"
                end try
            else
                set failed to false
                tell application "Finder"
                    try
                        set fw to item 1 of (get its every Finder window whose name contains pxName)
                        set itsProps to properties of fw
                        tell fw to close
                        make new Finder window to folder folderName with itsProps
                    on error e number n
                        set failed to true
                        set {d, m} to {e, n}
                    end try
                end tell
                if failed then my displayErrorMessageAndDie(d & ":" & m)
            end if
        end if
        
    else
        displayErrorMessageAndDie(folderName & "is not a valid folder specifier")
    end if
    if foundIt then
        tell application "Finder" to open folder folderName
        -- we had it in our space
        
        tell application "System Events" to tell application process id "com.apple.finder"
            -- We tickle the Finder window, to make it colourful and active when we leave
            key down control
            key code 118
            key up control
            delay 0.1
        end tell
    else if mustConfigure is false then
        tell application "Finder" to activate
    end if
end openFinderWindowInThisSpace


to openFinderWindow for folderName
    
    tell application "Finder"
        set aw to (get its every Finder window) as list
        set hw to {}
        set failed to false
        try
            set aliasOfit to folderName as alias
        on error
            try
                set aliasOfit to (POSIX file folderName as text) as alias
            on error
                set failed to true
            end try
        end try
        repeat with w in aw
            if (target of w as alias) is aliasOfit then
                copy w to end of hw
                exit repeat
            end if
        end repeat
        if not hw is {} then
            select item 1 of hw
        else
            open aliasOfit
        end if
    end tell
    return not failed
end openFinderWindow

to unAssignFinderDialog()
    try
        set infoIconFile to a reference to file ((path to library folder from system domain as text) & "CoreServices:CoreTypes.bundle:Contents:Resources:AlertNoteIcon.icns")
    on error
        set contents of infoIconFile to 3
    end try
    
    tell application "SystemUIServer"
        activate
        try
            display dialog "You must remove Finder's space assignement in Expose Preferences.

This will not change your Finder experience notably, except that you will be able to open new windows in any space you choose.

You will be taken into the Expose Preferences as soon as you have pressed Ok. Take your time, choose the space you want all your Finder windows to appear in before removing the assignment.

You must take the preference pane with you into your chosen space and remove the assignment there.

Come back here afterwards, when you have done it." buttons {"Ok"} default button 1 cancel button 1 with title my scriptTitle with icon infoIconFile
        end try
    end tell
end unAssignFinderDialog

to displayErrorMessageAndDie(theMessage)
    set frontappId to getfrontappid()
    try
        set stopIconFile to a reference to file ((path to library folder from system domain as text) & "CoreServices:CoreTypes.bundle:Contents:Resources:AlertStopIcon.icns")
    on error
        set stopIconFile to 3
    end try
    
    tell application "SystemUIServer"
        activate
        try
            display dialog theMessage with title my scriptTitle giving up after 300 buttons {"Ok"} default button 1 with icon anIcon
        end try
    end tell
    my abortNicely({bundleIdFrontApp:frontappId})
    
end displayErrorMessageAndDie

on abortNicely(r) -- Returns Nothing
    -- R : {bundleIdFrontApp:frontappId}
    tell application "System Events" to tell application process id (bundleIdFrontApp of r)
        key down control
        key code 118
        key up control
    end tell
    error number -128
end abortNicely

on getfrontappid() -- Returns bundleid of active app
    local frontappId
    set frontappId to ""
    tell application "System Events"
        set frontappId to bundle identifier of first application process whose frontmost is true
    end tell
    return frontappId
end getfrontappid


-- SNAGGED from the venerable jonn8 in the post : http://macscripter.net/viewtopic.php?id=23453
on get_space_binding_for_application(application_bundle_id)
    set application_bundle_id to my make_lowercase(application_bundle_id)
    set app_bindings to my get_spaces_application_bindings()
    try
        get app_bindings as string
    on error error_string
        set app_bindings to my string_to_list(text 13 thru -20 of error_string, ", ")
    end try
    repeat with i from 1 to (count app_bindings)
        if item i of app_bindings starts with ("|" & application_bundle_id & "|:") then return (item 2 of (my string_to_list(item i of app_bindings, ":"))) as number
    end repeat
    return 0
end get_space_binding_for_application

on make_lowercase(the_string)
    return do shell script "echo " & quoted form of the_string & " | /usr/bin/perl -pe 'use encoding utf8; s/(\\w)/\\L$1/gi'"
end make_lowercase

on get_spaces_application_bindings()
    tell application "System Events" to tell spaces preferences of expose preferences to return (get application bindings)
end get_spaces_application_bindings

on string_to_list(s, d)
    tell (a reference to my text item delimiters)
        set {o, contents} to {contents, d}
        set {s, contents} to {s's text items, o}
    end tell
    return s
end string_to_list

I moved a line out of Finders tell block, as it had been put inside, by mistake.