Is there a way to script setting up a space (mission control) in OSX?

Solution 1:

You sure can. I wrote an AppleScript some time ago to perform the tedious task of opening a Terminal window in every space.

Most of the examples on the internet ultimately use AppleScript to generate keystrokes. For instance, if you have it set up so "control-2" takes you to space 2 (this can be set in the "keyboard" preference pane), you can use the following AppleScript:

tell application "System Events"
        tell process "Finder"
                keystroke "2" using control down --switches to space 2
        end tell
end tell

to change to space 2. So my script, which opens a Terminal window in each space, works like this:

tell application "System Events"
    tell process "Finder"
            keystroke "1" using control down --switches to space 1
    end tell
    tell process "Terminal"
            activate
            keystroke "t" using command down --new terminal tab
    end tell
    tell process "Finder"
            keystroke "2" using control down --switches to space 2
    end tell
    ...etc...
end tell

Clearly, you can instruct applications other than Terminal to open windows in a given space.

You can launch a non-running app with do shell script "open -a application_name".

The problem with this approach is that it is entirely dependent on sending keystrokes, where it's possible for them to be sent too fast, end up queued, and ultimately execute in the wrong order. To prevent this it's necessary to add a delay (for instance, delay 0.1) after each scripted keystroke, making the entire script take some time to execute.

Or, for instance, if you launch an app, it may take some time to initialize, and it will open its windows in whatever space is active once it gets that far along (as opposed to whatever space was active when you first launched the app). So, the delay must be set appropriately each time, and sometimes it may be several seconds. Even worse, due to system load variances, the time may not even be consistent from execution to execution, forcing you to use a delay long enough to account for the worst-case scenario. (For example, if you launch an app which may take as long as 5 seconds from the moment of execution to display its first window, you'll need to delay 5 seconds before switching to the next space and moving on.)

Unfortunately, I haven't seen another approach to switching spaces. Hopefully someone can come along and provide a better way to switch than sending keystrokes, or perhaps a way to make the script wait without giving an arbitrary delay.

Still, if you don't mind giving your script a few seconds to get your environment up and running, you should be able to easily sequence a series of application launches or window openings and space selections with what I've provided.