package com.m_v.test;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;


public class SecondVM {

	public static void main(String[] args)  {
		if (		System.getenv("SWT_GTK3") == null
				 || System.getenv("LIBOVERLAY_SCROLLBAR") == null )  
		{ 
			URL classResource = SecondVM.class.getResource("SecondVM.class");
			boolean fromJar = classResource.getProtocol().equals("rsrc");
			
			String exePath = ClassLoader.getSystemClassLoader().getResource(".").getPath();
			exePath =  new File(exePath).getAbsolutePath().replaceFirst("\\.$", "").replaceFirst("bin$", "");
			if (!exePath.endsWith(System.getProperty("file.separator")))
				exePath += System.getProperty("file.separator");
			
			String[] script = {
			  "/bin/bash", "-c",
			  "export SWT_GTK3=0; "
			    + "export LIBOVERLAY_SCROLLBAR=0; "
			    + (fromJar? 
					"java -jar " + exePath + "SecondVM.jar" : 				// if runs from jar
					"java -cp ./bin/:../ExtLibs/swt_linux64/swt.jar " // if runs from under Eclipse or somewhat alike 
					+ "com.m_v.test.SecondVM")
				};
			
			try {
			  Process p = new ProcessBuilder(script).start();
		    
		    // When jar is run from a bash script, it kills the second VM when exits.
		    // Let it has some time to take a breath
    	      p.waitFor(12, TimeUnit.HOURS);
			} catch (Exception e) { e.printStackTrace(); }
			System.exit(0);
		}
		
		
	Display display = Display.getDefault();
	Shell shell = new Shell(display);
	shell.setText("test");
	shell.setLayout(new FillLayout());

	Text text = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL );
	text.setText( // To fill the text to make the scrollbar appear
			"1111111111\n2222222222\n3333333333\n4444444444\n5555555555\n6666666666\n7777777777\n8888888888\n9999999999\n0000000000\n"
		+	"1111111111\n2222222222\n3333333333\n4444444444\n5555555555\n6666666666\n7777777777\n8888888888\n9999999999\n0000000000\n"
	  	+	"1111111111\n2222222222\n3333333333\n4444444444\n5555555555\n6666666666\n7777777777\n8888888888\n9999999999\n0000000000\n"
	 );
    
    shell.setSize(new Point(300,200));
    shell.open();

    while (!shell.isDisposed()) 
      if (!display.readAndDispatch()) 
      	display.sleep(); 
      	
  }
}

