DEV Community

whiskeypls
whiskeypls

Posted on

Count Open Space - Mission Control

Here's the main goal:
I'm writing an application that opens 13 spaces before it opens my programs and apps in specific spaces.

Sometimes I'll already have 2 or 3 spaces open before I run the app so I'd like it to count the total open spaces and only open a total of 13

The Problem
The problem isn't how to have the code repeat 13 or less times. The problem is that when I count the number of spaces that are open it's returning 1 even if 6 spaces are open. I believe the reason for this is that when a shortcut is used to activate mission control like "Control Up" only the titles of the spaces appear. It's not until the mouse is moved over the top mission control bar that the spaces are visible.

The Questions
How do I either count the titles of the spaces ie Display 1, Display 2, etc, or how do I make the spaces visible before they are counted?

set totalSpaces to 13

tell application "System Events"
    do shell script quoted form of "/System/Applications/Mission Control.app/Contents/MacOS/Mission Control"
    set spacesCount to count of group 1 of group "Mission Control" of process "Dock"
    do shell script quoted form of "/System/Applications/Mission Control.app/Contents/MacOS/Mission Control"
    delay 0.5
    key up control
end tell

set repeatSpaces to totalSpaces - spacesCount

if repeatSpaces > 0 then
    display dialog "Number of spaces to repeat: " & repeatSpaces
else
    display dialog "No spaces need to be repeated."
end if

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
whiskeypls profile image
whiskeypls

Here's the code:

property numberOfSpaces : 13

---------- Open Spaces

tell application "System Events"
    key code 160 -- Launch Mission Control
    delay 2

    tell list 1 of group 2 of group 1 of group 1 of process "Dock"
        set countSpaces to count of buttons
        if countSpaces is greater than numberOfSpaces then
            set plusSpaces to countSpaces - numberOfSpaces
            repeat plusSpaces times
                perform action "AXRemoveDesktop" of button countSpaces
                set countSpaces to countSpaces - 1
            end repeat
        else
            tell application "System Events"
                set minusSpaces to numberOfSpaces - countSpaces
                repeat minusSpaces times
                    click (every button whose value of ¬
                        attribute "AXDescription" is "add desktop") of ¬
                        group 2 of group 1 of group 1 of process "Dock"
                end repeat
            end tell
        end if
    end tell
    delay 1
    key code 53
end tell
Enter fullscreen mode Exit fullscreen mode