Lion: Waiting for an arbitrary process's window to open

In Lion, I want to start an application and wait for its window to actually open on the screen.

I know that I can start the application (arbitrarily called “TheApplication”) and wait for the existence of its process (arbitrarily called “TheProcess”), as follows:

tell application "TheApplication" to activate
tell application "System Events"
set theProc to a reference to process "TheProcess"
repeat until exists theProc
end repeat
end tell

However, there is no guarantee that the application’s window will actually be open after the process’s existence is detected.

I need to wait for this window opening, because I want to programmatically switch to a new space after the window is showing on the screen. If I perform the space switch too soon, the window could open in the new space, which is not my intent.

I know that I could just wait for an arbitrary amount of time, during which I can assume that the window has probably opened. However, that is not definitive. Is there any kind of test I can perform or event that I can wait for which I can count on to tell me when an arbitrary application’s window is actually showing on the screen?

If the only way to do this is within Cocoa, I’m happy to do so as part of an ASOC application.

Thanks in advance for your suggestions.

Something like this?


tell application "Safari"
	set W to windows whose visible is true
	if W ≠ {} then beep -- empty list means no windows.
end tell

As Adam was saying, you just need to wait for the windows to appear.

Not all applications are scriptable though and even some that are don’t have a “window” class. As such it may be best to just use system events because it does know about the windows of applications, whether they’re scriptable or not. So try this. Note I used iTunes to test this because its window takes a few seconds to appear.

tell application "iTunes" to activate
tell application "System Events"
	repeat until exists process "iTunes"
		delay 0.2
	end repeat
	
	tell process "iTunes"
		repeat
			try
				if (count of windows) is greater than or equal to 1 then exit repeat
			end try
			delay 0.2
		end repeat
	end tell
end tell

Thank you to Adam and regulus6633!

I’ll use the System Events method.

And yes, I will not try this for applications which don’t open windows in the first place.