import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ScrollManager {
	private static final int gap = 10;
	
	private static final String[] read = new String[] { "sh", "-c", "wmctrl -d | tr -s ' ' | cut -d' ' -f6" };
	
	private static final Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
	private static final String MAXHORZ = Integer.toString(screensize.width), MAXVERT = Integer.toString(screensize.height);
	
	public static void main(String[] args) {
		Point mouse;
		while (true) try {
			mouse = MouseInfo.getPointerInfo().getLocation();
			if (mouse.x > screensize.width-gap)
				moveright();
			else if (mouse.x < gap)
				moveleft();
			if (mouse.y > screensize.height-gap)
				movedown();
			else if (mouse.y < gap)
				moveup();
			Thread.sleep(50);
		} catch (Exception e) {}
	}
	
	private static String exec(String[] command) {
		try {
			return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(command).getInputStream())).readLine();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	private static void moveup() {
		String[] vp = exec(read).split(",");
		if ("0".equals(vp[1])) return;
		exec(new String[] { "wmctrl", "-o", vp[0]+","+Integer.toString(Integer.parseInt(vp[1])-gap) });
	}
	
	private static void movedown() {
		String[] vp = exec(read).split(",");
		if (MAXVERT.equals(vp[1])) return;
		exec(new String[] { "wmctrl", "-o", vp[0]+","+Integer.toString(Integer.parseInt(vp[1])+gap) });
	}
	
	private static void moveleft() {
		String[] vp = exec(read).split(",");
		if ("0".equals(vp[0])) return;
		exec(new String[] { "wmctrl", "-o", Integer.toString(Integer.parseInt(vp[0])-gap)+","+vp[1] });
	}
	
	private static void moveright() {
		String[] vp = exec(read).split(",");
		if (MAXHORZ.equals(vp[0])) return;
		exec(new String[] { "wmctrl", "-o", Integer.toString(Integer.parseInt(vp[0])+gap)+","+vp[1] });
	}
}
