Programatically Controlling Spaces
March 22nd, 2008 by Joe RanieriThere’s been a lot of questions on mailing lists about how to control Spaces programatically. So far, there’s been no results from these discussions. Well, fortunately accomplishing this is quite simple, if you’re comfortable using private APIs.
Functions to query the current settings:
CGError CGSGetWorkspace(CGSConnectionID cid, CGSWorkspaceID *outWorkspace); extern bool CoreDockGetWorkspacesEnabled(); extern void CoreDockGetWorkspacesCount(int *rows, int *columns);
You’ll probably also want to switch spaces. You can accomplish this by using a distributed notification. This tells the Dock to switch spaces, giving you all of the normal animations:
- (void)switchToSpace:(CGSWorkspaceID)spaceNumber { // note that the notification is 1 based, but CGSWorkspaceID is zero based! [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.switchSpaces" object:[NSString stringWithFormat:@"%i", spaceNumber + 1]]; }
And lastly, you’ll probably want to get notified when things change:
//! Gets called when the current space changes. void SpaceChangedCallback(CGSNotificationType type, CGSWorkspaceID *workspace, unsigned int dataLength, Controller *self) { if(*workspace != kCGSTransitioningWorkspaceID) { // do something } } //! Gets called when the user enables or disables Spaces. - (void)spacesEnabledChanged:(NSNotification *)notification { // do something } //! Start listening for workspace related changes. - (void)registerForNotifications { // listen for when Spaces is enabled or disabled [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(spacesEnabledChanged:) name:@"SpacesEnableChange" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately]; // listen for when the current space changes CGSRegisterNotifyProc((CGSNotifyProcPtr)SpaceChangedCallback, kCGSNotificationWorkspaceChanged, self); }
You can find a full code example in the CGSInternal svn repository under Examples/SpacesSwitchingMenu, which mimics the Spaces menu extra.
Happy hacking!
March 22nd, 2008 at 10:47 pm
Nope, there’s no SpacesSwitchingMenu in the Download from http://alacatialabs.com/toys/cgsinternal/
March 22nd, 2008 at 10:54 pm
Ah, I meant in the svn repository. I updated the post with the link. It might ask for authentication - but you should be able to click cancel and see it.