package krasa.frameswitcher;

import java.awt.*;
import java.awt.event.InputEvent;

import javax.swing.*;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.WindowManager;

/**
 * @author Vojtech Krasa
 */
public class FocusUtils {

	public static void requestFocus(Project project, final boolean useRobot) {
		JFrame frame = WindowManager.getInstance().getFrame(project);

		// the only reliable way I found to bring it to the top
		boolean aot = frame.isAlwaysOnTop();
		frame.setAlwaysOnTop(true);
		frame.setAlwaysOnTop(aot);

		int frameState = frame.getExtendedState();
		if ((frameState & Frame.ICONIFIED) == Frame.ICONIFIED) {
			// restore the frame if it is minimized
			frame.setExtendedState(frameState ^ Frame.ICONIFIED);
		}
		frame.toFront();
		frame.requestFocus();
		if (useRobot && runningOnWindows7()) {
			try {
				// remember the last location of mouse
				final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation();

				// simulate a mouse click on title bar of window
				Robot robot = new Robot();
				robot.mouseMove(frame.getX(), frame.getY());
				robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
				robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

				// move mouse to old location
				robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY());
			} catch (Exception ex) {
				// just ignore exception, or you can handle it as you want
			} finally {
				frame.setAlwaysOnTop(false);
			}
		}
	}

	public static boolean runningOnWindows7() {
		String osName = System.getProperty("os.name");
		String osVersion = System.getProperty("os.version");
		return "Windows 7".equals(osName) && "6.1".equals(osVersion);
	}

}

@@ -27,85 +27,8 @@
 r;%0A%0A
-import java.awt.*;%0Aimport java.awt.event.InputEvent;%0A%0Aimport javax.swing.*;%0A%0A
 impo
@@ -115,16 +115,92 @@
 nager;%0A%0A
+import javax.swing.*;%0Aimport java.awt.*;%0Aimport java.awt.event.InputEvent;%0A%0A
 /**%0A * @
@@ -391,16 +391,53 @@
 oject);%0A
+%09%09if (frame == null) %7B%0A%09%09%09return;%0A%09%09%7D
 %0A%09%09// th

possible NPE