package org.lamport.tla.toolbox.tool.tlc.ui.test;

import java.io.File;

import junit.framework.Assert;

import org.eclipse.swt.widgets.Shell;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.matchers.WithText;
import org.eclipse.swtbot.swt.finder.waits.Conditions;
import org.eclipse.swtbot.swt.finder.waits.WaitForObjectCondition;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.Before;
import org.lamport.tla.toolbox.test.RCPTestSetupHelper;

public abstract class AbstractTest {
	
	/**
	 * workbench handle used by tests to access UI elements 
	 */
	protected SWTWorkbenchBot bot;

	/**
	 * Full qualified spec name
	 */
	protected static final String specA = System
			.getProperty("org.lamport.tla.toolbox.tool.tlc.ui.test.PathToSpecA");

	/**
	 * Pre flight checks (run once for each test _class_)
	 */
	public static void beforeClass() {
		// check to make sure the given spec files exist
		Assert.assertTrue("Given spec file does not exist: " + specA, new File(
				specA).exists());

		// Reset the workbench
		RCPTestSetupHelper.beforeClass();
	}
	
	/**
	 * Pre flight initialization (run once for each test _case_)
	 */
	@Before
	public void setUp() throws Exception {
		bot = new SWTWorkbenchBot();
	}

	/**
	 * @param aFile 
	 * @return The file name without path or suffix/extension
	 */
	protected String getSpecName(final File aFile) {
		final String name = aFile.getName();
		return name.substring(0, name.lastIndexOf("."));
	}
	
	/**
	 * @return waits for the TLA+ Toolbox shell to come available
	 */
	protected SWTBotShell waitForToolboxShell() {
		final WaitForObjectCondition<Shell> waitForShell = Conditions.waitForShell(WithText
				.<Shell> withText("TLA+ Toolbox"));
		bot.waitUntil(waitForShell);
		return new SWTBotShell(waitForShell.get(0));
	}
}

@@ -77,33 +77,42 @@
 ort 
-junit.framework.Assert
+org.eclipse.swt.widgets.MenuItem
 ;%0A
-%0A
 impo
@@ -203,16 +203,84 @@
 nchBot;%0A
+import org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory;%0A
 import o
@@ -449,16 +449,16 @@
 dition;%0A
-
 import o
@@ -503,24 +503,78 @@
 WTBotShell;%0A
+import org.hamcrest.Matcher;%0Aimport org.junit.Assert;%0A
 import org.j
@@ -1408,16 +1408,360 @@
 chBot();
+%0A%0A%09%09// Wait for the Toolbox UI to be fully started.%0A%09%09final Matcher%3CMenuItem%3E withMnemonic = WidgetMatcherFactory.withMnemonic(%22File%22);%0A%09%09final Matcher%3CMenuItem%3E matcher = WidgetMatcherFactory.allOf(WidgetMatcherFactory.widgetOfType(MenuItem.class),%0A%09%09%09%09withMnemonic);%0A%09%09bot.waitUntil(Conditions.waitForMenu(bot.activeShell(), matcher), 30000);
 %0A%09%7D%0A%0A%09/*

Make UI tests more robust against timing problems when the Toolbox takes longer to fully initialize by waiting 30 seconds for the "File" menu to appear in the main menu.