bug 415736: Invalid thread access when terminating Scout SWT Application
with Eclipse Luna M1 

https://bugs.eclipse.org/bugs/show_bug.cgi?id=415736

Dispose display when closing and make sure the workbench gets closed
only once

Change-Id: I1367818a541cb950352ed6a60f9ae982c2b3e315
Signed-off-by: Matthias Nick <Matthias.Nick@bsiag.com>
Reviewed-on: https://git.eclipse.org/r/18546
Tested-by: Hudson CI
Reviewed-by: Matthias Villiger <mvi@bsiag.com>
IP-Clean: Matthias Villiger <mvi@bsiag.com>
diff --git a/org.eclipse.scout.sdk/templates/ui.swt/src/SwtEnvironment.java b/org.eclipse.scout.sdk/templates/ui.swt/src/SwtEnvironment.java
index 11234a1..818cc14 100644
--- a/org.eclipse.scout.sdk/templates/ui.swt/src/SwtEnvironment.java
+++ b/org.eclipse.scout.sdk/templates/ui.swt/src/SwtEnvironment.java
@@ -53,7 +53,9 @@
       @Override
       public void environmentChanged(SwtEnvironmentEvent e) {
         if (e.getType() == SwtEnvironmentEvent.STOPPED) {
-          PlatformUI.getWorkbench().close();
+          if (!PlatformUI.getWorkbench().isClosing()) {
+            PlatformUI.getWorkbench().close();
+          }
         }
       }
     });
diff --git a/org.eclipse.scout.sdk/templates/ui.swt/src/application/Application.java b/org.eclipse.scout.sdk/templates/ui.swt/src/application/Application.java
index a9301bf..125c688 100644
--- a/org.eclipse.scout.sdk/templates/ui.swt/src/application/Application.java
+++ b/org.eclipse.scout.sdk/templates/ui.swt/src/application/Application.java
@@ -14,17 +14,25 @@
  *  This class controls all aspects of the application's execution
  */
 public class Application implements IApplication {
+  private Display m_display;
 
   @Override
   public Object start(final IApplicationContext context) throws Exception {
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new SimplePrincipal(System.getProperty("user.name")));
-    return Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
-      @Override
-      public Object run() throws Exception {
-        return startSecure(context);
+    m_display = getApplicationDisplay();
+    try {
+      Subject subject = new Subject();
+      subject.getPrincipals().add(new SimplePrincipal(System.getProperty("user.name")));
+      return Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
+        @Override
+        public Object run() throws Exception {
+          return startSecure(context);
+        }
+      });
+    } finally {
+      if (m_display != null) {
+        m_display.dispose();
       }
-    });
+    }
   }
 
   public Integer startSecure(final IApplicationContext context) throws Exception {
@@ -49,4 +57,11 @@
         }
     });
   }
+
+  public Display getApplicationDisplay() {
+    if (m_display == null) {
+      m_display = Display.getDefault();
+    }
+    return m_display;
+  }
 }